id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_3962_0 | /* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2015, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "common.h"
#include "secure.h"
#include "aes.h"
#include "debug.h"
#include "string.h"
#include "autoconf.h"
static inline void init_keys(at91_aes_key_size_t *key_size,
unsigned int *cipher_key,
unsigned int *cmac_key,
unsigned int *iv)
{
#if defined(CONFIG_AES_KEY_SIZE_128)
*key_size = AT91_AES_KEY_SIZE_128;
#elif defined(CONFIG_AES_KEY_SIZE_192)
*key_size = AT91_AES_KEY_SIZE_192;
#elif defined(CONFIG_AES_KEY_SIZE_256)
*key_size = AT91_AES_KEY_SIZE_256;
#else
#error "bad AES key size"
#endif
iv[0] = CONFIG_AES_IV_WORD0;
iv[1] = CONFIG_AES_IV_WORD1;
iv[2] = CONFIG_AES_IV_WORD2;
iv[3] = CONFIG_AES_IV_WORD3;
cipher_key[0] = CONFIG_AES_CIPHER_KEY_WORD0;
cmac_key[0] = CONFIG_AES_CMAC_KEY_WORD0;
cipher_key[1] = CONFIG_AES_CIPHER_KEY_WORD1;
cmac_key[1] = CONFIG_AES_CMAC_KEY_WORD1;
cipher_key[2] = CONFIG_AES_CIPHER_KEY_WORD2;
cmac_key[2] = CONFIG_AES_CMAC_KEY_WORD2;
cipher_key[3] = CONFIG_AES_CIPHER_KEY_WORD3;
cmac_key[3] = CONFIG_AES_CMAC_KEY_WORD3;
#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)
cipher_key[4] = CONFIG_AES_CIPHER_KEY_WORD4;
cmac_key[4] = CONFIG_AES_CMAC_KEY_WORD4;
cipher_key[5] = CONFIG_AES_CIPHER_KEY_WORD5;
cmac_key[5] = CONFIG_AES_CMAC_KEY_WORD5;
#endif
#if defined(CONFIG_AES_KEY_SIZE_256)
cipher_key[6] = CONFIG_AES_CIPHER_KEY_WORD6;
cmac_key[6] = CONFIG_AES_CMAC_KEY_WORD6;
cipher_key[7] = CONFIG_AES_CIPHER_KEY_WORD7;
cmac_key[7] = CONFIG_AES_CMAC_KEY_WORD7;
#endif
}
int secure_decrypt(void *data, unsigned int data_length, int is_signed)
{
at91_aes_key_size_t key_size;
unsigned int cmac_key[8], cipher_key[8];
unsigned int iv[AT91_AES_IV_SIZE_WORD];
unsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];
unsigned int fixed_length;
const unsigned int *cmac;
int rc = -1;
/* Init keys */
init_keys(&key_size, cipher_key, cmac_key, iv);
/* Init periph */
at91_aes_init();
/* Check signature if required */
if (is_signed) {
/* Compute the CMAC */
if (at91_aes_cmac(data_length, data, computed_cmac,
key_size, cmac_key))
goto exit;
/* Check the CMAC */
fixed_length = at91_aes_roundup(data_length);
cmac = (const unsigned int *)((char *)data + fixed_length);
if (!consttime_memequal(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))
goto exit;
}
/* Decrypt the whole file */
if (at91_aes_cbc(data_length, data, data, 0,
key_size, cipher_key, iv))
goto exit;
rc = 0;
exit:
/* Reset periph */
at91_aes_cleanup();
/* Reset keys */
memset(cmac_key, 0, sizeof(cmac_key));
memset(cipher_key, 0, sizeof(cipher_key));
memset(iv, 0, sizeof(iv));
return rc;
}
int secure_check(void *data)
{
const at91_secure_header_t *header;
void *file;
if (secure_decrypt(data, sizeof(*header), 0))
return -1;
header = (const at91_secure_header_t *)data;
if (header->magic != AT91_SECURE_MAGIC)
return -1;
file = (unsigned char *)data + sizeof(*header);
return secure_decrypt(file, header->file_size, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-203/c/good_3962_0 |
crossvul-cpp_data_bad_3962_0 | /* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2015, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "common.h"
#include "secure.h"
#include "aes.h"
#include "debug.h"
#include "string.h"
#include "autoconf.h"
static inline void init_keys(at91_aes_key_size_t *key_size,
unsigned int *cipher_key,
unsigned int *cmac_key,
unsigned int *iv)
{
#if defined(CONFIG_AES_KEY_SIZE_128)
*key_size = AT91_AES_KEY_SIZE_128;
#elif defined(CONFIG_AES_KEY_SIZE_192)
*key_size = AT91_AES_KEY_SIZE_192;
#elif defined(CONFIG_AES_KEY_SIZE_256)
*key_size = AT91_AES_KEY_SIZE_256;
#else
#error "bad AES key size"
#endif
iv[0] = CONFIG_AES_IV_WORD0;
iv[1] = CONFIG_AES_IV_WORD1;
iv[2] = CONFIG_AES_IV_WORD2;
iv[3] = CONFIG_AES_IV_WORD3;
cipher_key[0] = CONFIG_AES_CIPHER_KEY_WORD0;
cmac_key[0] = CONFIG_AES_CMAC_KEY_WORD0;
cipher_key[1] = CONFIG_AES_CIPHER_KEY_WORD1;
cmac_key[1] = CONFIG_AES_CMAC_KEY_WORD1;
cipher_key[2] = CONFIG_AES_CIPHER_KEY_WORD2;
cmac_key[2] = CONFIG_AES_CMAC_KEY_WORD2;
cipher_key[3] = CONFIG_AES_CIPHER_KEY_WORD3;
cmac_key[3] = CONFIG_AES_CMAC_KEY_WORD3;
#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)
cipher_key[4] = CONFIG_AES_CIPHER_KEY_WORD4;
cmac_key[4] = CONFIG_AES_CMAC_KEY_WORD4;
cipher_key[5] = CONFIG_AES_CIPHER_KEY_WORD5;
cmac_key[5] = CONFIG_AES_CMAC_KEY_WORD5;
#endif
#if defined(CONFIG_AES_KEY_SIZE_256)
cipher_key[6] = CONFIG_AES_CIPHER_KEY_WORD6;
cmac_key[6] = CONFIG_AES_CMAC_KEY_WORD6;
cipher_key[7] = CONFIG_AES_CIPHER_KEY_WORD7;
cmac_key[7] = CONFIG_AES_CMAC_KEY_WORD7;
#endif
}
int secure_decrypt(void *data, unsigned int data_length, int is_signed)
{
at91_aes_key_size_t key_size;
unsigned int cmac_key[8], cipher_key[8];
unsigned int iv[AT91_AES_IV_SIZE_WORD];
unsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];
unsigned int fixed_length;
const unsigned int *cmac;
int rc = -1;
/* Init keys */
init_keys(&key_size, cipher_key, cmac_key, iv);
/* Init periph */
at91_aes_init();
/* Check signature if required */
if (is_signed) {
/* Compute the CMAC */
if (at91_aes_cmac(data_length, data, computed_cmac,
key_size, cmac_key))
goto exit;
/* Check the CMAC */
fixed_length = at91_aes_roundup(data_length);
cmac = (const unsigned int *)((char *)data + fixed_length);
if (memcmp(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))
goto exit;
}
/* Decrypt the whole file */
if (at91_aes_cbc(data_length, data, data, 0,
key_size, cipher_key, iv))
goto exit;
rc = 0;
exit:
/* Reset periph */
at91_aes_cleanup();
/* Reset keys */
memset(cmac_key, 0, sizeof(cmac_key));
memset(cipher_key, 0, sizeof(cipher_key));
memset(iv, 0, sizeof(iv));
return rc;
}
int secure_check(void *data)
{
const at91_secure_header_t *header;
void *file;
if (secure_decrypt(data, sizeof(*header), 0))
return -1;
header = (const at91_secure_header_t *)data;
if (header->magic != AT91_SECURE_MAGIC)
return -1;
file = (unsigned char *)data + sizeof(*header);
return secure_decrypt(file, header->file_size, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-203/c/bad_3962_0 |
crossvul-cpp_data_bad_4748_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/simplexml/ext_simplexml.h"
#include <vector>
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/file.h"
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/ext/simplexml/ext_simplexml_include.h"
#include "hphp/runtime/ext/domdocument/ext_domdocument.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
#include "hphp/runtime/ext/libxml/ext_libxml.h"
#include "hphp/system/systemlib.h"
#include "hphp/runtime/vm/vm-regs.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// Iter type
enum SXE_ITER {
SXE_ITER_NONE = 0,
SXE_ITER_ELEMENT = 1,
SXE_ITER_CHILD = 2,
SXE_ITER_ATTRLIST = 3
};
const StaticString
s_SimpleXMLElement("SimpleXMLElement"),
s_SimpleXMLElementIterator("SimpleXMLElementIterator"),
s_SimpleXMLIterator("SimpleXMLIterator");
const Class* SimpleXMLElement_classof() {
static auto cls = Unit::lookupClass(s_SimpleXMLElement.get());
return cls;
}
const Class* SimpleXMLElementIterator_classof() {
static auto cls = Unit::lookupClass(s_SimpleXMLElementIterator.get());
return cls;
}
const Class* SimpleXMLIterator_classof() {
static auto cls = Unit::lookupClass(s_SimpleXMLIterator.get());
return cls;
}
///////////////////////////////////////////////////////////////////////////////
// NativeData definitions
namespace {
struct SimpleXMLElement {
SimpleXMLElement() {
auto obj = Native::object<SimpleXMLElement>(this);
obj->setAttribute(ObjectData::HasPropEmpty);
obj->setAttribute(ObjectData::CallToImpl);
}
SimpleXMLElement& operator=(const SimpleXMLElement &src) {
iter.isprefix = src.iter.isprefix;
if (src.iter.name != nullptr) {
iter.name = xmlStrdup((xmlChar*)src.iter.name);
}
if (src.iter.nsprefix != nullptr) {
iter.nsprefix = xmlStrdup((xmlChar*)src.iter.nsprefix);
}
iter.type = src.iter.type;
if (src.nodep()) {
node = libxml_register_node(
xmlDocCopyNode(src.nodep(), src.docp(), 1)
);
}
return *this;
}
~SimpleXMLElement() { sweep(); }
void sweep() {
if (iter.name) {
xmlFree(iter.name);
}
if (iter.nsprefix) {
xmlFree(iter.nsprefix);
}
if (xpath) {
xmlXPathFreeContext(xpath);
}
}
xmlNodePtr nodep() const {
return node ? node->nodep() : nullptr;
}
xmlDocPtr docp() const {
return node ? node->docp() : nullptr;
}
XMLNode node{nullptr};
xmlXPathContextPtr xpath{nullptr};
struct {
xmlChar* name{nullptr};
xmlChar* nsprefix{nullptr};
bool isprefix{false};
SXE_ITER type{SXE_ITER_NONE};
Object data;
} iter;
};
struct SimpleXMLElementIterator {
SimpleXMLElement* sxe() {
assert(m_sxe->instanceof(SimpleXMLElement_classof()));
return Native::data<SimpleXMLElement>(m_sxe.get());
}
void setSxe(const Object& sxe) {
assert(sxe->instanceof(SimpleXMLElement_classof()));
m_sxe = Object(sxe.get());
}
private:
Object m_sxe;
};
using SimpleXMLIterator = SimpleXMLElement;
} // anon namespace
///////////////////////////////////////////////////////////////////////////////
// Helpers
#define SKIP_TEXT(__p) \
if ((__p)->type == XML_TEXT_NODE) { \
goto next_iter; \
}
#define SXE_NS_PREFIX(ns) (ns->prefix ? (char*)ns->prefix : "")
static inline void sxe_add_namespace_name(Array& ret, xmlNsPtr ns) {
String prefix = String(SXE_NS_PREFIX(ns));
if (!ret.exists(prefix)) {
ret.set(prefix, String((char*)ns->href, CopyString));
}
}
static void sxe_add_registered_namespaces(SimpleXMLElement* sxe,
xmlNodePtr node, bool recursive,
Array& return_value) {
if (node != nullptr && node->type == XML_ELEMENT_NODE) {
xmlNsPtr ns = node->nsDef;
while (ns != nullptr) {
sxe_add_namespace_name(return_value, ns);
ns = ns->next;
}
if (recursive) {
node = node->children;
while (node) {
sxe_add_registered_namespaces(sxe, node, recursive, return_value);
node = node->next;
}
}
}
}
static void sxe_add_namespaces(SimpleXMLElement* sxe, xmlNodePtr node,
bool recursive, Array& return_value) {
if (node->ns) {
sxe_add_namespace_name(return_value, node->ns);
}
xmlAttrPtr attr = node->properties;
while (attr) {
if (attr->ns) {
sxe_add_namespace_name(return_value, attr->ns);
}
attr = attr->next;
}
if (recursive) {
node = node->children;
while (node) {
if (node->type == XML_ELEMENT_NODE) {
sxe_add_namespaces(sxe, node, recursive, return_value);
}
node = node->next;
}
}
}
static Object _node_as_zval(SimpleXMLElement* sxe, xmlNodePtr node,
SXE_ITER itertype, const char* name,
const xmlChar* nsprefix, bool isprefix) {
auto sxeObj = Native::object<SimpleXMLElement>(sxe);
Object obj = create_object(sxeObj->getClassName(), Array(), false);
auto subnode = Native::data<SimpleXMLElement>(obj.get());
subnode->iter.type = itertype;
if (name) {
subnode->iter.name = xmlStrdup((xmlChar*)name);
}
if (nsprefix && *nsprefix) {
subnode->iter.nsprefix = xmlStrdup(nsprefix);
subnode->iter.isprefix = isprefix;
}
subnode->node = libxml_register_node(node);
return obj;
}
static inline bool match_ns(SimpleXMLElement* sxe, xmlNodePtr node,
xmlChar* name, bool prefix) {
if (name == nullptr && (node->ns == nullptr || node->ns->prefix == nullptr)) {
return true;
}
if (RuntimeOption::SimpleXMLEmptyNamespaceMatchesAll &&
(name == nullptr || *name == '\0')) {
return true;
}
if (node->ns &&
!xmlStrcmp(prefix ? node->ns->prefix : node->ns->href, name)) {
return true;
}
return false;
}
static xmlNodePtr sxe_get_element_by_offset(SimpleXMLElement* sxe,
long offset, xmlNodePtr node,
long* cnt) {
if (sxe->iter.type == SXE_ITER_NONE) {
if (offset == 0) {
if (cnt) {
*cnt = 0;
}
return node;
} else {
return nullptr;
}
}
long nodendx = 0;
while (node && nodendx <= offset) {
SKIP_TEXT(node)
if (node->type == XML_ELEMENT_NODE &&
match_ns(sxe, node, sxe->iter.nsprefix, sxe->iter.isprefix)) {
if (sxe->iter.type == SXE_ITER_CHILD ||
(sxe->iter.type == SXE_ITER_ELEMENT
&& !xmlStrcmp(node->name, sxe->iter.name))) {
if (nodendx == offset) {
break;
}
nodendx++;
}
}
next_iter:
node = node->next;
}
if (cnt) {
*cnt = nodendx;
}
return node;
}
static xmlNodePtr php_sxe_iterator_fetch(SimpleXMLElement* sxe,
xmlNodePtr node, int use_data) {
xmlChar* prefix = sxe->iter.nsprefix;
bool isprefix = sxe->iter.isprefix;
bool test_elem = sxe->iter.type == SXE_ITER_ELEMENT && sxe->iter.name;
bool test_attr = sxe->iter.type == SXE_ITER_ATTRLIST && sxe->iter.name;
while (node) {
SKIP_TEXT(node)
if (sxe->iter.type != SXE_ITER_ATTRLIST && node->type == XML_ELEMENT_NODE) {
if ((!test_elem || !xmlStrcmp(node->name, sxe->iter.name))
&& match_ns(sxe, node, prefix, isprefix)) {
break;
}
} else if (node->type == XML_ATTRIBUTE_NODE) {
if ((!test_attr || !xmlStrcmp(node->name, sxe->iter.name)) &&
match_ns(sxe, node, prefix, isprefix)) {
break;
}
}
next_iter:
node = node->next;
}
if (node && use_data) {
sxe->iter.data = _node_as_zval(sxe, node, SXE_ITER_NONE, nullptr, prefix,
isprefix);
}
return node;
}
static void php_sxe_move_forward_iterator(SimpleXMLElement* sxe) {
xmlNodePtr node = nullptr;
auto data = sxe->iter.data;
if (!data.isNull()) {
assert(data->instanceof(SimpleXMLElement_classof()));
auto intern = Native::data<SimpleXMLElement>(data.get());
node = intern->nodep();
sxe->iter.data.reset();
}
if (node) {
php_sxe_iterator_fetch(sxe, node->next, 1);
}
}
static xmlNodePtr php_sxe_reset_iterator(SimpleXMLElement* sxe,
bool use_data) {
if (!sxe->iter.data.isNull()) {
sxe->iter.data.reset();
}
xmlNodePtr node = sxe->nodep();
if (node) {
switch (sxe->iter.type) {
case SXE_ITER_ELEMENT:
case SXE_ITER_CHILD:
case SXE_ITER_NONE:
node = node->children;
break;
case SXE_ITER_ATTRLIST:
node = (xmlNodePtr)node->properties;
}
return php_sxe_iterator_fetch(sxe, node, use_data);
}
return nullptr;
}
static int64_t php_sxe_count_elements_helper(SimpleXMLElement* sxe) {
Object data = sxe->iter.data;
sxe->iter.data.reset();
xmlNodePtr node = php_sxe_reset_iterator(sxe, false);
int64_t count = 0;
while (node) {
count++;
node = php_sxe_iterator_fetch(sxe, node->next, 0);
}
sxe->iter.data = data;
return count;
}
static xmlNodePtr php_sxe_get_first_node(SimpleXMLElement* sxe,
xmlNodePtr node) {
if (sxe && sxe->iter.type != SXE_ITER_NONE) {
php_sxe_reset_iterator(sxe, true);
xmlNodePtr retnode = nullptr;
if (!sxe->iter.data.isNull()) {
assert(sxe->iter.data->instanceof(SimpleXMLElement_classof()));
retnode = Native::data<SimpleXMLElement>(sxe->iter.data.get())->nodep();
}
return retnode;
} else {
return node;
}
}
xmlNodePtr SimpleXMLElement_exportNode(const Object& sxe) {
assert(sxe->instanceof(SimpleXMLElement_classof()));
auto data = Native::data<SimpleXMLElement>(sxe.get());
return php_sxe_get_first_node(data, data->nodep());
}
static Object sxe_prop_dim_read(SimpleXMLElement* sxe, const Variant& member,
bool elements, bool attribs) {
xmlNodePtr node = sxe->nodep();
String name = "";
if (member.isNull() || member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
} else if (member.isNull()) {
/* This happens when the user did: $sxe[]->foo = $value */
raise_error("Cannot create unnamed attribute");
return Object{};
}
} else {
name = member.toString();
}
xmlAttrPtr attr = nullptr;
bool test = false;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
if (member.isNull() && node && node->parent &&
node->parent->type == XML_DOCUMENT_NODE) {
/* This happens when the user did: $sxe[]->foo = $value */
raise_error("Cannot create unnamed attribute");
return Object{};
}
}
Object return_value;
if (node) {
if (attribs) {
if (!member.isInteger() || sxe->iter.type == SXE_ITER_ATTRLIST) {
if (member.isInteger()) {
int64_t nodendx = 0;
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
return_value = _node_as_zval(sxe, (xmlNodePtr) attr,
SXE_ITER_NONE, nullptr,
sxe->iter.nsprefix,
sxe->iter.isprefix);
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)name.data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
return_value = _node_as_zval(sxe, (xmlNodePtr) attr,
SXE_ITER_NONE,
nullptr,
sxe->iter.nsprefix,
sxe->iter.isprefix);
break;
}
attr = attr->next;
}
}
}
}
if (elements) {
if (!sxe->nodep()) {
sxe->node = libxml_register_node(node);
}
if (member.isNull() || member.isInteger()) {
long cnt = 0;
xmlNodePtr mynode = node;
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
if (sxe->iter.type == SXE_ITER_NONE) {
if (!member.isNull() && member.toInt64() > 0) {
raise_warning("Cannot add element %s number %" PRId64 " when "
"only 0 such elements exist", mynode->name,
member.toInt64());
}
} else if (!member.isNull()) {
node = sxe_get_element_by_offset(sxe, member.toInt64(), node, &cnt);
} else {
node = nullptr;
}
if (node) {
return_value = _node_as_zval(sxe, node, SXE_ITER_NONE, nullptr,
sxe->iter.nsprefix, sxe->iter.isprefix);
}
// Zend would check here if this is a write operation, but HHVM always
// handles that with offsetSet so we just want to return nullptr here.
} else {
#if SXE_ELEMENT_BY_NAME
int newtype;
node = sxe->nodep();
node = sxe_get_element_by_name(sxe, node, &name.data(), &newtype);
if (node) {
return_value = _node_as_zval(sxe, node, newtype, name.data(),
sxe->iter.nsprefix, sxe->iter.isprefix);
}
#else
return_value = _node_as_zval(sxe, node, SXE_ITER_ELEMENT, name.data(),
sxe->iter.nsprefix, sxe->iter.isprefix);
#endif
}
}
}
return return_value;
}
static void change_node_zval(xmlNodePtr node, const Variant& value) {
if (value.isNull()) {
xmlNodeSetContentLen(node, (xmlChar*)"", 0);
return;
}
if (value.isInteger() || value.isBoolean() || value.isDouble() ||
value.isNull() || value.isString()) {
xmlChar* buffer =
xmlEncodeEntitiesReentrant(node->doc,
(xmlChar*)value.toString().data());
int64_t buffer_len = xmlStrlen(buffer);
/* check for nullptr buffer in case of
* memory error in xmlEncodeEntitiesReentrant */
if (buffer) {
xmlNodeSetContentLen(node, buffer, buffer_len);
xmlFree(buffer);
}
} else {
raise_warning("It is not possible to assign complex types to nodes");
}
}
static void sxe_prop_dim_delete(SimpleXMLElement* sxe, const Variant& member,
bool elements, bool attribs) {
xmlNodePtr node = sxe->nodep();
if (member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
}
}
xmlAttrPtr attr = nullptr;
bool test = 0;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
}
if (node) {
if (attribs) {
if (member.isInteger()) {
int64_t nodendx = 0;
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
libxml_register_node((xmlNodePtr) attr)->unlink();
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
xmlAttrPtr anext;
while (attr) {
anext = attr->next;
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)member.toString().data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
libxml_register_node((xmlNodePtr) attr)->unlink();
break;
}
attr = anext;
}
}
}
if (elements) {
if (member.isInteger()) {
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
node = sxe_get_element_by_offset(sxe, member.toInt64(), node, nullptr);
if (node) {
libxml_register_node(node)->unlink();
}
} else {
node = node->children;
xmlNodePtr nnext;
while (node) {
nnext = node->next;
SKIP_TEXT(node);
if (!xmlStrcmp(node->name, (xmlChar*)member.toString().data())) {
libxml_register_node(node)->unlink();
}
next_iter:
node = nnext;
}
}
}
}
}
static bool sxe_prop_dim_exists(SimpleXMLElement* sxe, const Variant& member,
bool check_empty, bool elements, bool attribs) {
xmlNodePtr node = sxe->nodep();
if (member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
}
}
xmlAttrPtr attr = nullptr;
bool test = false;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
}
bool exists = false;
if (node) {
if (attribs) {
if (member.isInteger()) {
int64_t nodendx = 0;
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
exists = true;
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)member.toString().data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
exists = true;
break;
}
attr = attr->next;
}
}
if (exists && check_empty == 1 &&
(!attr->children || !attr->children->content ||
!attr->children->content[0] ||
!xmlStrcmp(attr->children->content, (const xmlChar*)"0")) ) {
/* Attribute with no content in it's text node */
exists = false;
}
}
if (elements) {
if (member.isInteger()) {
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
node = sxe_get_element_by_offset(sxe, member.toInt64(), node, nullptr);
}
else {
node = node->children;
while (node) {
xmlNodePtr nnext;
nnext = node->next;
if ((node->type == XML_ELEMENT_NODE) &&
!xmlStrcmp(node->name, (xmlChar*)member.toString().data())) {
break;
}
node = nnext;
}
}
if (node) {
exists = true;
if (check_empty == true &&
(!node->children || (node->children->type == XML_TEXT_NODE &&
!node->children->next &&
(!node->children->content ||
!node->children->content[0] ||
!xmlStrcmp(node->children->content,
(const xmlChar*)"0"))))) {
exists = false;
}
}
}
}
return exists;
}
static inline String sxe_xmlNodeListGetString(xmlDocPtr doc, xmlNodePtr list,
bool inLine) {
xmlChar* tmp = xmlNodeListGetString(doc, list, inLine);
if (tmp) {
String ret = String((char*)tmp);
xmlFree(tmp);
return ret;
} else {
return empty_string();
}
}
static Variant _get_base_node_value(SimpleXMLElement* sxe_ref,
xmlNodePtr node, xmlChar* nsprefix,
bool isprefix) {
if (node->children &&
node->children->type == XML_TEXT_NODE &&
!xmlIsBlankNode(node->children)) {
xmlChar* contents = xmlNodeListGetString(node->doc, node->children, 1);
if (contents) {
String obj = String((char*)contents);
xmlFree(contents);
return obj;
}
} else {
auto sxeRefObj = Native::object<SimpleXMLElement>(sxe_ref);
Object obj = create_object(sxeRefObj->getClassName(), Array(), false);
auto subnode = Native::data<SimpleXMLElement>(obj.get());
if (nsprefix && *nsprefix) {
subnode->iter.nsprefix = xmlStrdup((xmlChar*)nsprefix);
subnode->iter.isprefix = isprefix;
}
subnode->node = libxml_register_node(node);
return obj;
}
return init_null();
}
static void sxe_properties_add(Array& rv, char* name, const Variant& value) {
String sName = String(name);
if (rv.exists(sName)) {
Variant existVal = rv[sName];
if (existVal.isArray()) {
Array arr = existVal.toArray();
arr.append(value);
rv.set(sName, arr);
} else {
Array arr = Array::Create();
arr.append(existVal);
arr.append(value);
rv.set(sName, arr);
}
} else {
rv.set(sName, value);
}
}
static void sxe_get_prop_hash(SimpleXMLElement* sxe, bool is_debug,
Array& rv, bool isBoolCast = false) {
rv.clear();
Object iter_data;
bool use_iter = false;
xmlNodePtr node = sxe->nodep();
if (!node) {
return;
}
if (is_debug || sxe->iter.type != SXE_ITER_CHILD) {
if (sxe->iter.type == SXE_ITER_ELEMENT) {
node = php_sxe_get_first_node(sxe, node);
}
if (!node || node->type != XML_ENTITY_DECL) {
xmlAttrPtr attr = node ? (xmlAttrPtr)node->properties : nullptr;
Array zattr = Array::Create();
bool test = sxe->iter.name && sxe->iter.type == SXE_ITER_ATTRLIST;
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr)attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
zattr.set(String((char*)attr->name),
sxe_xmlNodeListGetString(
sxe->docp(),
attr->children,
1));
}
attr = attr->next;
}
if (zattr.size()) {
rv.set(String("@attributes"), zattr);
}
}
}
node = sxe->nodep();
node = php_sxe_get_first_node(sxe, node);
if (node && sxe->iter.type != SXE_ITER_ATTRLIST) {
if (node->type == XML_ATTRIBUTE_NODE) {
rv.append(sxe_xmlNodeListGetString(node->doc, node->children, 1));
node = nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
if (sxe->iter.type == SXE_ITER_NONE || !node->children ||
!node->parent ||
node->children->next ||
node->children->children ||
node->parent->children == node->parent->last) {
node = node->children;
} else {
iter_data = sxe->iter.data;
sxe->iter.data.reset();
node = php_sxe_reset_iterator(sxe, false);
use_iter = true;
}
}
char *name = nullptr;
Variant value;
while (node) {
if (node->children != nullptr || node->prev != nullptr ||
node->next != nullptr) {
SKIP_TEXT(node);
} else {
if (node->type == XML_TEXT_NODE) {
const xmlChar* cur = node->content;
if (*cur != 0) {
rv.append(sxe_xmlNodeListGetString(node->doc, node, 1));
}
goto next_iter;
}
}
if (node->type == XML_ELEMENT_NODE &&
(!match_ns(sxe, node, sxe->iter.nsprefix, sxe->iter.isprefix))) {
goto next_iter;
}
name = (char*)node->name;
if (!name) {
goto next_iter;
}
value = _get_base_node_value(sxe, node, sxe->iter.nsprefix,
sxe->iter.isprefix);
if (use_iter) {
rv.append(value);
} else {
sxe_properties_add(rv, name, value);
}
if (isBoolCast) break;
next_iter:
if (use_iter) {
node = php_sxe_iterator_fetch(sxe, node->next, 0);
} else {
node = node->next;
}
}
}
if (use_iter) {
sxe->iter.data = iter_data;
}
}
Variant SimpleXMLElement_objectCast(const ObjectData* obj, int8_t type) {
assert(obj->instanceof(SimpleXMLElement_classof()));
auto sxe = Native::data<SimpleXMLElement>(const_cast<ObjectData*>(obj));
if (type == KindOfBoolean) {
xmlNodePtr node = php_sxe_get_first_node(sxe, nullptr);
if (node) return true;
Array properties = Array::Create();
sxe_get_prop_hash(sxe, true, properties, true);
return properties.size() != 0;
}
if (isArrayType((DataType)type)) {
Array properties = Array::Create();
sxe_get_prop_hash(sxe, true, properties);
return properties;
}
xmlChar* contents = nullptr;
if (sxe->iter.type != SXE_ITER_NONE) {
xmlNodePtr node = php_sxe_get_first_node(sxe, nullptr);
if (node) {
contents = xmlNodeListGetString(sxe->docp(), node->children, 1);
}
} else {
xmlDocPtr doc = sxe->docp();
if (!sxe->nodep()) {
if (doc) {
sxe->node = libxml_register_node(xmlDocGetRootElement(doc));
}
}
if (sxe->nodep()) {
if (sxe->nodep()->children) {
contents = xmlNodeListGetString(doc, sxe->nodep()->children, 1);
}
}
}
String ret = String((char*)contents);
if (contents) {
xmlFree(contents);
}
switch (type) {
case KindOfString: return ret;
case KindOfInt64: return toInt64(ret);
case KindOfDouble: return toDouble(ret);
default: return init_null();
}
}
static bool sxe_prop_dim_write(SimpleXMLElement* sxe, const Variant& member,
const Variant& value, bool elements, bool attribs,
xmlNodePtr* pnewnode) {
xmlNodePtr node = sxe->nodep();
if (member.isNull() || member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
} else if (member.isNull()) {
/* This happens when the user did: $sxe[] = $value
* and could also be E_PARSE, but we use this only during parsing
* and this is during runtime.
*/
raise_error("Cannot create unnamed attribute");
return false;
}
} else {
if (member.toString().empty()) {
raise_warning("Cannot write or create unnamed %s",
attribs ? "attribute" : "element");
return false;
}
}
bool retval = true;
xmlAttrPtr attr = nullptr;
xmlNodePtr mynode = nullptr;
bool test = false;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
mynode = node;
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
if (member.isNull() && node && node->parent &&
node->parent->type == XML_DOCUMENT_NODE) {
/* This happens when the user did: $sxe[] = $value
* and could also be E_PARSE, but we use this only during parsing
* and this is during runtime.
*/
raise_error("Cannot create unnamed attribute");
return false;
}
if (attribs && !node && sxe->iter.type == SXE_ITER_ELEMENT) {
node = xmlNewChild(mynode, mynode->ns, sxe->iter.name, nullptr);
attr = node->properties;
}
}
mynode = node;
if (!(value.isString() || value.isInteger() || value.isBoolean() ||
value.isDouble() || value.isNull() || value.isObject())) {
raise_warning("It is not yet possible to assign complex types to %s",
attribs ? "attributes" : "properties");
return false;
}
xmlNodePtr newnode = nullptr;
if (node) {
int64_t nodendx = 0;
int64_t counter = 0;
bool is_attr = false;
if (attribs) {
if (member.isInteger()) {
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
is_attr = true;
++counter;
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)member.toString().data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
is_attr = true;
++counter;
break;
}
attr = attr->next;
}
}
}
long cnt = 0;
if (elements) {
if (member.isNull() || member.isInteger()) {
if (node->type == XML_ATTRIBUTE_NODE) {
raise_error("Cannot create duplicate attribute");
return false;
}
if (sxe->iter.type == SXE_ITER_NONE) {
newnode = node;
++counter;
if (!member.isNull() && member.toInt64() > 0) {
raise_warning("Cannot add element %s number %" PRId64 " when "
"only 0 such elements exist", mynode->name,
member.toInt64());
retval = false;
}
} else if (!member.isNull()) {
newnode =
sxe_get_element_by_offset(sxe, member.toInt64(), node, &cnt);
if (newnode) {
++counter;
}
}
} else {
node = node->children;
while (node) {
SKIP_TEXT(node)
if (!xmlStrcmp(node->name, (xmlChar*)member.toString().data())) {
newnode = node;
++counter;
}
next_iter:
node = node->next;
}
}
}
if (counter == 1) {
if (is_attr) {
newnode = (xmlNodePtr) attr;
}
if (!value.isNull()) {
xmlNodePtr tempnode;
while ((tempnode = (xmlNodePtr) newnode->children)) {
libxml_register_node(tempnode)->unlink();
}
change_node_zval(newnode, value);
}
} else if (counter > 1) {
raise_warning("Cannot assign to an array of nodes "
"(duplicate subnodes or attr detected)");
retval = false;
} else if (elements) {
if (!node) {
if (member.isNull() || member.isInteger()) {
newnode =
xmlNewTextChild(
mynode->parent, mynode->ns, mynode->name,
!value.isNull() ? (xmlChar*)value.toString().data() : nullptr);
} else {
newnode =
xmlNewTextChild(
mynode, mynode->ns, (xmlChar*)member.toString().data(),
!value.isNull() ? (xmlChar*)value.toString().data() : nullptr);
}
} else if (member.isNull() || member.isInteger()) {
if (!member.isNull() && cnt < member.toInt64()) {
raise_warning("Cannot add element %s number %" PRId64 " when "
"only %ld such elements exist", mynode->name,
member.toInt64(), cnt);
retval = false;
}
newnode = xmlNewTextChild(mynode->parent, mynode->ns, mynode->name,
!value.isNull() ?
(xmlChar*)value.toString().data() : nullptr);
}
} else if (attribs) {
if (member.isInteger()) {
raise_warning("Cannot change attribute number %" PRId64 " when "
"only %" PRId64 " attributes exist", member.toInt64(),
nodendx);
retval = false;
} else {
newnode = (xmlNodePtr)xmlNewProp(node,
(xmlChar*)member.toString().data(),
!value.isNull() ?
(xmlChar*)value.toString().data() :
nullptr);
}
}
}
if (pnewnode) {
*pnewnode = newnode;
}
return retval;
}
///////////////////////////////////////////////////////////////////////////////
// SimpleXML
static const Class* class_from_name(const String& class_name,
const char* callee) {
const Class* cls;
if (!class_name.empty()) {
cls = Unit::loadClass(class_name.get());
if (!cls) {
throw_invalid_argument("class not found: %s", class_name.data());
return nullptr;
}
if (!cls->classof(SimpleXMLElement_classof())) {
throw_invalid_argument(
"%s() expects parameter 2 to be a class name "
"derived from SimpleXMLElement, '%s' given",
callee,
class_name.data());
return nullptr;
}
} else {
cls = SimpleXMLElement_classof();
}
return cls;
}
static Variant HHVM_FUNCTION(simplexml_import_dom,
const Object& node,
const String& class_name /* = "SimpleXMLElement" */) {
auto domnode = Native::data<DOMNode>(node);
xmlNodePtr nodep = domnode->nodep();
if (nodep) {
if (nodep->doc == nullptr) {
raise_warning("Imported Node must have associated Document");
return init_null();
}
if (nodep->type == XML_DOCUMENT_NODE ||
nodep->type == XML_HTML_DOCUMENT_NODE) {
nodep = xmlDocGetRootElement((xmlDocPtr) nodep);
}
}
if (nodep && nodep->type == XML_ELEMENT_NODE) {
auto cls = class_from_name(class_name, "simplexml_import_dom");
if (!cls) {
return init_null();
}
Object obj = create_object(cls->nameStr(), Array(), false);
auto sxe = Native::data<SimpleXMLElement>(obj.get());
sxe->node = libxml_register_node(nodep);
return obj;
} else {
raise_warning("Invalid Nodetype to import");
return init_null();
}
return false;
}
static Variant HHVM_FUNCTION(simplexml_load_string,
const String& data,
const String& class_name /* = "SimpleXMLElement" */,
int64_t options /* = 0 */,
const String& ns /* = "" */,
bool is_prefix /* = false */) {
SYNC_VM_REGS_SCOPED();
auto cls = class_from_name(class_name, "simplexml_load_string");
if (!cls) {
return init_null();
}
xmlDocPtr doc = xmlReadMemory(data.data(), data.size(), nullptr,
nullptr, options);
if (!doc) {
return false;
}
Object obj = create_object(cls->nameStr(), Array(), false);
auto sxe = Native::data<SimpleXMLElement>(obj.get());
sxe->node = libxml_register_node(xmlDocGetRootElement(doc));
sxe->iter.nsprefix = ns.size() ? xmlStrdup((xmlChar*)ns.data()) : nullptr;
sxe->iter.isprefix = is_prefix;
return obj;
}
static Variant HHVM_FUNCTION(simplexml_load_file,
const String& filename,
const String& class_name /* = "SimpleXMLElement" */,
int64_t options /* = 0 */, const String& ns /* = "" */,
bool is_prefix /* = false */) {
SYNC_VM_REGS_SCOPED();
auto cls = class_from_name(class_name, "simplexml_load_file");
if (!cls) {
return init_null();
}
auto stream = File::Open(filename, "rb");
if (!stream || stream->isInvalid()) return false;
xmlDocPtr doc = nullptr;
// The XML context is also deleted in this function, so the ownership
// of the File is kept locally in 'stream'. The libxml_streams_IO_nop_close
// callback does nothing.
xmlParserCtxtPtr ctxt = xmlCreateIOParserCtxt(nullptr, nullptr,
libxml_streams_IO_read,
libxml_streams_IO_nop_close,
&stream,
XML_CHAR_ENCODING_NONE);
if (ctxt == nullptr) return false;
SCOPE_EXIT { xmlFreeParserCtxt(ctxt); };
if (ctxt->directory == nullptr) {
ctxt->directory = xmlParserGetDirectory(filename.c_str());
}
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
doc = ctxt->myDoc;
} else {
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = nullptr;
return false;
}
Object obj = create_object(cls->nameStr(), Array(), false);
auto sxe = Native::data<SimpleXMLElement>(obj.get());
sxe->node = libxml_register_node(xmlDocGetRootElement(doc));
sxe->iter.nsprefix = ns.size() ? xmlStrdup((xmlChar*)ns.data()) : nullptr;
sxe->iter.isprefix = is_prefix;
return obj;
}
///////////////////////////////////////////////////////////////////////////////
// SimpleXMLElement
static void HHVM_METHOD(SimpleXMLElement, __construct,
const String& data,
int64_t options /* = 0 */,
bool data_is_url /* = false */,
const String& ns /* = "" */,
bool is_prefix /* = false */) {
SYNC_VM_REGS_SCOPED();
xmlDocPtr docp = data_is_url ?
xmlReadFile(data.data(), nullptr, options) :
xmlReadMemory(data.data(), data.size(), nullptr, nullptr, options);
if (!docp) {
SystemLib::throwExceptionObject("String could not be parsed as XML");
}
auto sxe = Native::data<SimpleXMLElement>(this_);
sxe->iter.nsprefix = !ns.empty() ? xmlStrdup((xmlChar*)ns.data()) : nullptr;
sxe->iter.isprefix = is_prefix;
sxe->node = libxml_register_node(xmlDocGetRootElement(docp));
}
static Variant HHVM_METHOD(SimpleXMLElement, xpath, const String& path) {
auto data = Native::data<SimpleXMLElement>(this_);
if (data->iter.type == SXE_ITER_ATTRLIST) {
return init_null(); // attributes don't have attributes
}
if (!data->xpath) {
data->xpath = xmlXPathNewContext(data->docp());
}
if (!data->nodep()) {
data->node = libxml_register_node(xmlDocGetRootElement(data->docp()));
}
auto nodeptr = php_sxe_get_first_node(data, data->nodep());
data->xpath->node = nodeptr;
xmlNsPtr* ns = xmlGetNsList(data->docp(), nodeptr);
int64_t nsnbr = 0;
if (ns != nullptr) {
while (ns[nsnbr] != nullptr) {
nsnbr++;
}
}
auto& xpath = data->xpath;
xpath->namespaces = ns;
xpath->nsNr = nsnbr;
xmlXPathObjectPtr retval = xmlXPathEval((xmlChar*)path.data(), xpath);
if (ns != nullptr) {
xmlFree(ns);
xpath->namespaces = nullptr;
xpath->nsNr = 0;
}
if (!retval) {
return false;
}
xmlNodeSetPtr result = retval->nodesetval;
Array ret = Array::Create();
if (result != nullptr) {
for (int64_t i = 0; i < result->nodeNr; ++i) {
nodeptr = result->nodeTab[i];
if (nodeptr->type == XML_TEXT_NODE ||
nodeptr->type == XML_ELEMENT_NODE ||
nodeptr->type == XML_ATTRIBUTE_NODE) {
/**
* Detect the case where the last selector is text(), simplexml
* always accesses the text() child by default, therefore we assign
* to the parent node.
*/
Object obj;
if (nodeptr->type == XML_TEXT_NODE) {
obj = _node_as_zval(data, nodeptr->parent, SXE_ITER_NONE, nullptr,
nullptr, false);
} else if (nodeptr->type == XML_ATTRIBUTE_NODE) {
obj = _node_as_zval(data, nodeptr->parent, SXE_ITER_ATTRLIST,
(char*)nodeptr->name, nodeptr->ns ?
(xmlChar*)nodeptr->ns->href : nullptr, false);
} else {
obj = _node_as_zval(data, nodeptr, SXE_ITER_NONE, nullptr, nullptr,
false);
}
if (!obj.isNull()) {
ret.append(obj);
}
}
}
}
xmlXPathFreeObject(retval);
return ret;
}
static bool HHVM_METHOD(SimpleXMLElement, registerXPathNamespace,
const String& prefix, const String& ns) {
auto data = Native::data<SimpleXMLElement>(this_);
if (!data->xpath) {
data->xpath = xmlXPathNewContext(data->docp());
}
if (xmlXPathRegisterNs(data->xpath,
(xmlChar*)prefix.data(),
(xmlChar*)ns.data()) != 0) {
return false;
}
return true;
}
static Variant HHVM_METHOD(SimpleXMLElement, asXML,
const String& filename /* = "" */) {
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
xmlOutputBufferPtr outbuf = nullptr;
if (filename.size()) {
node = php_sxe_get_first_node(data, node);
if (node) {
xmlDocPtr doc = data->docp();
if (node->parent && (XML_DOCUMENT_NODE == node->parent->type)) {
int bytes;
bytes = xmlSaveFile(filename.data(), doc);
if (bytes == -1) {
return false;
} else {
return true;
}
} else {
outbuf = xmlOutputBufferCreateFilename(filename.data(), nullptr, 0);
if (outbuf == nullptr) {
return false;
}
xmlNodeDumpOutput(outbuf, doc, node, 0, 0, nullptr);
xmlOutputBufferClose(outbuf);
return true;
}
} else {
return false;
}
}
node = php_sxe_get_first_node(data, node);
if (node) {
xmlDocPtr doc = data->docp();
if (node->parent && (XML_DOCUMENT_NODE == node->parent->type)) {
xmlChar* strval;
int strval_len;
xmlDocDumpMemoryEnc(doc, &strval, &strval_len,
(const char*)doc->encoding);
String ret = String((char*)strval);
xmlFree(strval);
return ret;
} else {
/* Should we be passing encoding information instead of nullptr? */
outbuf = xmlAllocOutputBuffer(nullptr);
if (outbuf == nullptr) {
return false;
}
xmlNodeDumpOutput(outbuf, doc, node, 0, 0,
(const char*)doc->encoding);
xmlOutputBufferFlush(outbuf);
char* str = nullptr;
#ifdef LIBXML2_NEW_BUFFER
str = (char*)xmlOutputBufferGetContent(outbuf);
#else
str = (char*)outbuf->buffer->content;
#endif
String ret = String(str);
xmlOutputBufferClose(outbuf);
return ret;
}
} else {
return false;
}
return false;
}
static Array HHVM_METHOD(SimpleXMLElement, getNamespaces,
bool recursive /* = false */) {
auto data = Native::data<SimpleXMLElement>(this_);
Array ret = Array::Create();
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
if (node) {
if (node->type == XML_ELEMENT_NODE) {
sxe_add_namespaces(data, node, recursive, ret);
} else if (node->type == XML_ATTRIBUTE_NODE && node->ns) {
sxe_add_namespace_name(ret, node->ns);
}
}
return ret;
}
static Array HHVM_METHOD(SimpleXMLElement, getDocNamespaces,
bool recursive /* = false */,
bool from_root /* = true */) {
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node =
from_root ? xmlDocGetRootElement(data->docp())
: data->nodep();
Array ret = Array::Create();
sxe_add_registered_namespaces(data, node, recursive, ret);
return ret;
}
static Variant HHVM_METHOD(SimpleXMLElement, children,
const String& ns = empty_string(),
bool is_prefix = false) {
auto data = Native::data<SimpleXMLElement>(this_);
if (data->iter.type == SXE_ITER_ATTRLIST) {
return init_null(); /* attributes don't have attributes */
}
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
return _node_as_zval(data, node, SXE_ITER_CHILD, nullptr,
(xmlChar*)ns.data(), is_prefix);
}
static String HHVM_METHOD(SimpleXMLElement, getName) {
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
if (node) {
return String((char*)node->name);
}
return empty_string();
}
static Object HHVM_METHOD(SimpleXMLElement, attributes,
const String& ns /* = "" */,
bool is_prefix /* = false */) {
auto data = Native::data<SimpleXMLElement>(this_);
if (data->iter.type == SXE_ITER_ATTRLIST) {
return Object(); /* attributes don't have attributes */
}
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
return _node_as_zval(data, node, SXE_ITER_ATTRLIST, nullptr,
(xmlChar*)ns.data(), is_prefix);
}
static Variant HHVM_METHOD(SimpleXMLElement, addChild,
const String& qname,
const String& value /* = null_string */,
const Variant& ns /* = null */) {
if (qname.empty()) {
raise_warning("Element name is required");
return init_null();
}
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
if (data->iter.type == SXE_ITER_ATTRLIST) {
raise_warning("Cannot add element to attributes");
return init_null();
}
node = php_sxe_get_first_node(data, node);
if (node == nullptr) {
raise_warning("Cannot add child. "
"Parent is not a permanent member of the XML tree");
return init_null();
}
xmlChar* prefix = nullptr;
xmlChar* localname = xmlSplitQName2((xmlChar*)qname.data(), &prefix);
if (localname == nullptr) {
localname = xmlStrdup((xmlChar*)qname.data());
}
xmlNodePtr newnode = xmlNewChild(node, nullptr, localname,
(xmlChar*)value.data());
xmlNsPtr nsptr = nullptr;
if (!ns.isNull()) {
const String& ns_ = ns.toString();
if (ns_.empty()) {
newnode->ns = nullptr;
nsptr = xmlNewNs(newnode, (xmlChar*)ns_.data(), prefix);
} else {
nsptr = xmlSearchNsByHref(node->doc, node, (xmlChar*)ns_.data());
if (nsptr == nullptr) {
nsptr = xmlNewNs(newnode, (xmlChar*)ns_.data(), prefix);
}
newnode->ns = nsptr;
}
}
Object ret = _node_as_zval(data, newnode, SXE_ITER_NONE, (char*)localname,
prefix, false);
xmlFree(localname);
if (prefix != nullptr) {
xmlFree(prefix);
}
return ret;
}
static void HHVM_METHOD(SimpleXMLElement, addAttribute,
const String& qname,
const String& value /* = null_string */,
const String& ns /* = null_string */) {
if (qname.size() == 0) {
raise_warning("Attribute name is required");
return;
}
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
if (node && node->type != XML_ELEMENT_NODE) {
node = node->parent;
}
if (node == nullptr) {
raise_warning("Unable to locate parent Element");
return;
}
xmlChar* prefix = nullptr;
xmlChar* localname = xmlSplitQName2((xmlChar*)qname.data(), &prefix);
if (localname == nullptr) {
if (ns.size() > 0) {
if (prefix != nullptr) {
xmlFree(prefix);
}
raise_warning("Attribute requires prefix for namespace");
return;
}
localname = xmlStrdup((xmlChar*)qname.data());
}
xmlAttrPtr attrp = xmlHasNsProp(node, localname, (xmlChar*)ns.data());
if (attrp != nullptr && attrp->type != XML_ATTRIBUTE_DECL) {
xmlFree(localname);
if (prefix != nullptr) {
xmlFree(prefix);
}
raise_warning("Attribute already exists");
return;
}
xmlNsPtr nsptr = nullptr;
if (ns.size()) {
nsptr = xmlSearchNsByHref(node->doc, node, (xmlChar*)ns.data());
if (nsptr == nullptr) {
nsptr = xmlNewNs(node, (xmlChar*)ns.data(), prefix);
}
}
attrp = xmlNewNsProp(node, nsptr, localname, (xmlChar*)value.data());
xmlFree(localname);
if (prefix != nullptr) {
xmlFree(prefix);
}
}
static String HHVM_METHOD(SimpleXMLElement, __toString) {
return SimpleXMLElement_objectCast(this_, KindOfString).toString();
}
static Variant HHVM_METHOD(SimpleXMLElement, __get, const Variant& name) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_read(data, name, true, false);
}
static Variant HHVM_METHOD(SimpleXMLElement, __unset, const Variant& name) {
auto data = Native::data<SimpleXMLElement>(this_);
sxe_prop_dim_delete(data, name, true, false);
return init_null();
}
static bool HHVM_METHOD(SimpleXMLElement, __isset, const Variant& name) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_exists(data, name, false, true, false);
}
static Variant HHVM_METHOD(SimpleXMLElement, __set,
const Variant& name, const Variant& value) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_write(data, name, value, true, false, nullptr);
}
bool SimpleXMLElement_propEmpty(const ObjectData* this_,
const StringData* key) {
auto data = Native::data<SimpleXMLElement>(const_cast<ObjectData*>(this_));
return !sxe_prop_dim_exists(data, Variant(key->toCppString()),
true, true, false);
}
static int64_t HHVM_METHOD(SimpleXMLElement, count) {
auto data = Native::data<SimpleXMLElement>(this_);
return php_sxe_count_elements_helper(data);
}
///////////////////////////////////////////////////////////////////////////////
// ArrayAccess
static bool HHVM_METHOD(SimpleXMLElement, offsetExists,
const Variant& index) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_exists(data, index, false, false, true);
}
static Variant HHVM_METHOD(SimpleXMLElement, offsetGet,
const Variant& index) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_read(data, index, false, true);
}
static void HHVM_METHOD(SimpleXMLElement, offsetSet,
const Variant& index, const Variant& newvalue) {
auto data = Native::data<SimpleXMLElement>(this_);
sxe_prop_dim_write(data, index, newvalue, false, true, nullptr);
}
static void HHVM_METHOD(SimpleXMLElement, offsetUnset,
const Variant& index) {
auto data = Native::data<SimpleXMLElement>(this_);
sxe_prop_dim_delete(data, index, false, true);
}
///////////////////////////////////////////////////////////////////////////////
// Iterator
static void HHVM_METHOD(SimpleXMLElementIterator, __construct,
const Variant& sxe) {
if (sxe.isObject()) {
Native::data<SimpleXMLElementIterator>(this_)->setSxe(sxe.toObject());
}
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, current) {
return Native::data<SimpleXMLElementIterator>(this_)->sxe()->iter.data;
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, key) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
Object curobj = sxe->iter.data;
xmlNodePtr curnode = curobj.isNull()
? nullptr
: Native::data<SimpleXMLElement>(curobj.get())->nodep();
if (curnode) {
return String((char*)curnode->name);
} else {
return init_null();
}
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, next) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
php_sxe_move_forward_iterator(sxe);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, rewind) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
php_sxe_reset_iterator(sxe, true);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, valid) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
return !sxe->iter.data.isNull();
}
///////////////////////////////////////////////////////////////////////////////
// SimpleXMLIterator
static Variant HHVM_METHOD(SimpleXMLIterator, current) {
auto data = Native::data<SimpleXMLIterator>(this_);
return data->iter.data;
}
static Variant HHVM_METHOD(SimpleXMLIterator, key) {
auto data = Native::data<SimpleXMLIterator>(this_);
Object curobj = data->iter.data;
if (curobj.isNull()) {
return init_null();
}
assert(curobj->instanceof(SimpleXMLElement_classof()));
auto curnode = Native::data<SimpleXMLElement>(curobj.get())->nodep();
return String((char*)curnode->name);
}
static Variant HHVM_METHOD(SimpleXMLIterator, next) {
auto data = Native::data<SimpleXMLIterator>(this_);
php_sxe_move_forward_iterator(data);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLIterator, rewind) {
auto data = Native::data<SimpleXMLIterator>(this_);
php_sxe_reset_iterator(data, true);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLIterator, valid) {
auto data = Native::data<SimpleXMLIterator>(this_);
return !data->iter.data.isNull();
}
static Variant HHVM_METHOD(SimpleXMLIterator, getChildren) {
auto data = Native::data<SimpleXMLIterator>(this_);
auto current = data->iter.data;
if (current.isNull()) {
return init_null();
}
assert(current->instanceof(SimpleXMLElement_classof()));
return HHVM_MN(SimpleXMLElement, children)(current.get());
}
static bool HHVM_METHOD(SimpleXMLIterator, hasChildren) {
auto children = HHVM_MN(SimpleXMLIterator, getChildren)(this_);
if (!children.isObject()) {
return false;
}
auto od = children.toObject().get();
assert(od->instanceof(SimpleXMLElement_classof()));
return HHVM_MN(SimpleXMLElement, count)(od) > 0;
}
///////////////////////////////////////////////////////////////////////////////
static struct SimpleXMLExtension : Extension {
SimpleXMLExtension(): Extension("simplexml", "1.0") {}
void moduleInit() override {
HHVM_FE(simplexml_import_dom);
HHVM_FE(simplexml_load_string);
HHVM_FE(simplexml_load_file);
/* SimpleXMLElement */
HHVM_ME(SimpleXMLElement, __construct);
HHVM_ME(SimpleXMLElement, xpath);
HHVM_ME(SimpleXMLElement, registerXPathNamespace);
HHVM_ME(SimpleXMLElement, asXML);
HHVM_ME(SimpleXMLElement, getNamespaces);
HHVM_ME(SimpleXMLElement, getDocNamespaces);
HHVM_ME(SimpleXMLElement, children);
HHVM_ME(SimpleXMLElement, getName);
HHVM_ME(SimpleXMLElement, attributes);
HHVM_ME(SimpleXMLElement, addChild);
HHVM_ME(SimpleXMLElement, addAttribute);
HHVM_ME(SimpleXMLElement, __toString);
HHVM_ME(SimpleXMLElement, __get);
HHVM_ME(SimpleXMLElement, __unset);
HHVM_ME(SimpleXMLElement, __isset);
HHVM_ME(SimpleXMLElement, __set);
HHVM_ME(SimpleXMLElement, count);
HHVM_ME(SimpleXMLElement, offsetExists);
HHVM_ME(SimpleXMLElement, offsetGet);
HHVM_ME(SimpleXMLElement, offsetSet);
HHVM_ME(SimpleXMLElement, offsetUnset);
Native::registerNativeDataInfo<SimpleXMLElement>(
s_SimpleXMLElement.get()
);
/* SimpleXMLElementIterator */
HHVM_ME(SimpleXMLElementIterator, __construct);
HHVM_ME(SimpleXMLElementIterator, current);
HHVM_ME(SimpleXMLElementIterator, key);
HHVM_ME(SimpleXMLElementIterator, next);
HHVM_ME(SimpleXMLElementIterator, rewind);
HHVM_ME(SimpleXMLElementIterator, valid);
Native::registerNativeDataInfo<SimpleXMLElementIterator>(
s_SimpleXMLElementIterator.get(),
Native::NDIFlags::NO_SWEEP
);
/* SimpleXMLIterator */
HHVM_ME(SimpleXMLIterator, current);
HHVM_ME(SimpleXMLIterator, key);
HHVM_ME(SimpleXMLIterator, next);
HHVM_ME(SimpleXMLIterator, rewind);
HHVM_ME(SimpleXMLIterator, valid);
HHVM_ME(SimpleXMLIterator, getChildren);
HHVM_ME(SimpleXMLIterator, hasChildren);
Native::registerNativeDataInfo<SimpleXMLIterator>(
s_SimpleXMLIterator.get()
);
loadSystemlib();
}
} s_simplexml_extension;
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-345/cpp/bad_4748_0 |
crossvul-cpp_data_good_4748_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/simplexml/ext_simplexml.h"
#include <vector>
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/file.h"
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/ext/simplexml/ext_simplexml_include.h"
#include "hphp/runtime/ext/domdocument/ext_domdocument.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
#include "hphp/runtime/ext/libxml/ext_libxml.h"
#include "hphp/system/systemlib.h"
#include "hphp/runtime/vm/vm-regs.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// Iter type
enum SXE_ITER {
SXE_ITER_NONE = 0,
SXE_ITER_ELEMENT = 1,
SXE_ITER_CHILD = 2,
SXE_ITER_ATTRLIST = 3
};
const StaticString
s_SimpleXMLElement("SimpleXMLElement"),
s_SimpleXMLElementIterator("SimpleXMLElementIterator"),
s_SimpleXMLIterator("SimpleXMLIterator");
const Class* SimpleXMLElement_classof() {
static auto cls = Unit::lookupClass(s_SimpleXMLElement.get());
return cls;
}
const Class* SimpleXMLElementIterator_classof() {
static auto cls = Unit::lookupClass(s_SimpleXMLElementIterator.get());
return cls;
}
const Class* SimpleXMLIterator_classof() {
static auto cls = Unit::lookupClass(s_SimpleXMLIterator.get());
return cls;
}
///////////////////////////////////////////////////////////////////////////////
// NativeData definitions
namespace {
struct SimpleXMLElement {
SimpleXMLElement() {
auto obj = Native::object<SimpleXMLElement>(this);
obj->setAttribute(ObjectData::HasPropEmpty);
obj->setAttribute(ObjectData::CallToImpl);
}
SimpleXMLElement& operator=(const SimpleXMLElement &src) {
iter.isprefix = src.iter.isprefix;
if (src.iter.name != nullptr) {
iter.name = xmlStrdup((xmlChar*)src.iter.name);
}
if (src.iter.nsprefix != nullptr) {
iter.nsprefix = xmlStrdup((xmlChar*)src.iter.nsprefix);
}
iter.type = src.iter.type;
if (src.nodep()) {
node = libxml_register_node(
xmlDocCopyNode(src.nodep(), src.docp(), 1)
);
}
return *this;
}
~SimpleXMLElement() { sweep(); }
void sweep() {
if (iter.name) {
xmlFree(iter.name);
}
if (iter.nsprefix) {
xmlFree(iter.nsprefix);
}
if (xpath) {
xmlXPathFreeContext(xpath);
}
}
xmlNodePtr nodep() const {
return node ? node->nodep() : nullptr;
}
xmlDocPtr docp() const {
return node ? node->docp() : nullptr;
}
XMLNode node{nullptr};
xmlXPathContextPtr xpath{nullptr};
struct {
xmlChar* name{nullptr};
xmlChar* nsprefix{nullptr};
bool isprefix{false};
SXE_ITER type{SXE_ITER_NONE};
Object data;
} iter;
};
struct SimpleXMLElementIterator {
SimpleXMLElement* sxe() {
assert(m_sxe->instanceof(SimpleXMLElement_classof()));
return Native::data<SimpleXMLElement>(m_sxe.get());
}
void setSxe(const Object& sxe) {
assert(sxe->instanceof(SimpleXMLElement_classof()));
m_sxe = Object(sxe.get());
}
private:
Object m_sxe;
};
using SimpleXMLIterator = SimpleXMLElement;
} // anon namespace
///////////////////////////////////////////////////////////////////////////////
// Helpers
#define SKIP_TEXT(__p) \
if ((__p)->type == XML_TEXT_NODE) { \
goto next_iter; \
}
#define SXE_NS_PREFIX(ns) (ns->prefix ? (char*)ns->prefix : "")
static inline void sxe_add_namespace_name(Array& ret, xmlNsPtr ns) {
String prefix = String(SXE_NS_PREFIX(ns));
if (!ret.exists(prefix)) {
ret.set(prefix, String((char*)ns->href, CopyString));
}
}
static void sxe_add_registered_namespaces(SimpleXMLElement* sxe,
xmlNodePtr node, bool recursive,
Array& return_value) {
if (node != nullptr && node->type == XML_ELEMENT_NODE) {
xmlNsPtr ns = node->nsDef;
while (ns != nullptr) {
sxe_add_namespace_name(return_value, ns);
ns = ns->next;
}
if (recursive) {
node = node->children;
while (node) {
sxe_add_registered_namespaces(sxe, node, recursive, return_value);
node = node->next;
}
}
}
}
static void sxe_add_namespaces(SimpleXMLElement* sxe, xmlNodePtr node,
bool recursive, Array& return_value) {
if (node->ns) {
sxe_add_namespace_name(return_value, node->ns);
}
xmlAttrPtr attr = node->properties;
while (attr) {
if (attr->ns) {
sxe_add_namespace_name(return_value, attr->ns);
}
attr = attr->next;
}
if (recursive) {
node = node->children;
while (node) {
if (node->type == XML_ELEMENT_NODE) {
sxe_add_namespaces(sxe, node, recursive, return_value);
}
node = node->next;
}
}
}
static Object _node_as_zval(SimpleXMLElement* sxe, xmlNodePtr node,
SXE_ITER itertype, const char* name,
const xmlChar* nsprefix, bool isprefix) {
auto sxeObj = Native::object<SimpleXMLElement>(sxe);
Object obj = create_object(sxeObj->getClassName(), Array(), false);
auto subnode = Native::data<SimpleXMLElement>(obj.get());
subnode->iter.type = itertype;
if (name) {
subnode->iter.name = xmlStrdup((xmlChar*)name);
}
if (nsprefix && *nsprefix) {
subnode->iter.nsprefix = xmlStrdup(nsprefix);
subnode->iter.isprefix = isprefix;
}
subnode->node = libxml_register_node(node);
return obj;
}
static inline bool match_ns(SimpleXMLElement* sxe, xmlNodePtr node,
xmlChar* name, bool prefix) {
if (name == nullptr && (node->ns == nullptr || node->ns->prefix == nullptr)) {
return true;
}
if (RuntimeOption::SimpleXMLEmptyNamespaceMatchesAll &&
(name == nullptr || *name == '\0')) {
return true;
}
if (node->ns &&
!xmlStrcmp(prefix ? node->ns->prefix : node->ns->href, name)) {
return true;
}
return false;
}
static xmlNodePtr sxe_get_element_by_offset(SimpleXMLElement* sxe,
long offset, xmlNodePtr node,
long* cnt) {
if (sxe->iter.type == SXE_ITER_NONE) {
if (offset == 0) {
if (cnt) {
*cnt = 0;
}
return node;
} else {
return nullptr;
}
}
long nodendx = 0;
while (node && nodendx <= offset) {
SKIP_TEXT(node)
if (node->type == XML_ELEMENT_NODE &&
match_ns(sxe, node, sxe->iter.nsprefix, sxe->iter.isprefix)) {
if (sxe->iter.type == SXE_ITER_CHILD ||
(sxe->iter.type == SXE_ITER_ELEMENT
&& !xmlStrcmp(node->name, sxe->iter.name))) {
if (nodendx == offset) {
break;
}
nodendx++;
}
}
next_iter:
node = node->next;
}
if (cnt) {
*cnt = nodendx;
}
return node;
}
static xmlNodePtr php_sxe_iterator_fetch(SimpleXMLElement* sxe,
xmlNodePtr node, int use_data) {
xmlChar* prefix = sxe->iter.nsprefix;
bool isprefix = sxe->iter.isprefix;
bool test_elem = sxe->iter.type == SXE_ITER_ELEMENT && sxe->iter.name;
bool test_attr = sxe->iter.type == SXE_ITER_ATTRLIST && sxe->iter.name;
while (node) {
SKIP_TEXT(node)
if (sxe->iter.type != SXE_ITER_ATTRLIST && node->type == XML_ELEMENT_NODE) {
if ((!test_elem || !xmlStrcmp(node->name, sxe->iter.name))
&& match_ns(sxe, node, prefix, isprefix)) {
break;
}
} else if (node->type == XML_ATTRIBUTE_NODE) {
if ((!test_attr || !xmlStrcmp(node->name, sxe->iter.name)) &&
match_ns(sxe, node, prefix, isprefix)) {
break;
}
}
next_iter:
node = node->next;
}
if (node && use_data) {
sxe->iter.data = _node_as_zval(sxe, node, SXE_ITER_NONE, nullptr, prefix,
isprefix);
}
return node;
}
static void php_sxe_move_forward_iterator(SimpleXMLElement* sxe) {
xmlNodePtr node = nullptr;
auto data = sxe->iter.data;
if (!data.isNull()) {
assert(data->instanceof(SimpleXMLElement_classof()));
auto intern = Native::data<SimpleXMLElement>(data.get());
node = intern->nodep();
sxe->iter.data.reset();
}
if (node) {
php_sxe_iterator_fetch(sxe, node->next, 1);
}
}
static xmlNodePtr php_sxe_reset_iterator(SimpleXMLElement* sxe,
bool use_data) {
if (!sxe->iter.data.isNull()) {
sxe->iter.data.reset();
}
xmlNodePtr node = sxe->nodep();
if (node) {
switch (sxe->iter.type) {
case SXE_ITER_ELEMENT:
case SXE_ITER_CHILD:
case SXE_ITER_NONE:
node = node->children;
break;
case SXE_ITER_ATTRLIST:
node = (xmlNodePtr)node->properties;
}
return php_sxe_iterator_fetch(sxe, node, use_data);
}
return nullptr;
}
static int64_t php_sxe_count_elements_helper(SimpleXMLElement* sxe) {
Object data = sxe->iter.data;
sxe->iter.data.reset();
xmlNodePtr node = php_sxe_reset_iterator(sxe, false);
int64_t count = 0;
while (node) {
count++;
node = php_sxe_iterator_fetch(sxe, node->next, 0);
}
sxe->iter.data = data;
return count;
}
static xmlNodePtr php_sxe_get_first_node(SimpleXMLElement* sxe,
xmlNodePtr node) {
if (sxe && sxe->iter.type != SXE_ITER_NONE) {
php_sxe_reset_iterator(sxe, true);
xmlNodePtr retnode = nullptr;
if (!sxe->iter.data.isNull()) {
assert(sxe->iter.data->instanceof(SimpleXMLElement_classof()));
retnode = Native::data<SimpleXMLElement>(sxe->iter.data.get())->nodep();
}
return retnode;
} else {
return node;
}
}
xmlNodePtr SimpleXMLElement_exportNode(const Object& sxe) {
if (!sxe->instanceof(SimpleXMLElement_classof())) return nullptr;
auto data = Native::data<SimpleXMLElement>(sxe.get());
return php_sxe_get_first_node(data, data->nodep());
}
static Object sxe_prop_dim_read(SimpleXMLElement* sxe, const Variant& member,
bool elements, bool attribs) {
xmlNodePtr node = sxe->nodep();
String name = "";
if (member.isNull() || member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
} else if (member.isNull()) {
/* This happens when the user did: $sxe[]->foo = $value */
raise_error("Cannot create unnamed attribute");
return Object{};
}
} else {
name = member.toString();
}
xmlAttrPtr attr = nullptr;
bool test = false;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
if (member.isNull() && node && node->parent &&
node->parent->type == XML_DOCUMENT_NODE) {
/* This happens when the user did: $sxe[]->foo = $value */
raise_error("Cannot create unnamed attribute");
return Object{};
}
}
Object return_value;
if (node) {
if (attribs) {
if (!member.isInteger() || sxe->iter.type == SXE_ITER_ATTRLIST) {
if (member.isInteger()) {
int64_t nodendx = 0;
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
return_value = _node_as_zval(sxe, (xmlNodePtr) attr,
SXE_ITER_NONE, nullptr,
sxe->iter.nsprefix,
sxe->iter.isprefix);
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)name.data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
return_value = _node_as_zval(sxe, (xmlNodePtr) attr,
SXE_ITER_NONE,
nullptr,
sxe->iter.nsprefix,
sxe->iter.isprefix);
break;
}
attr = attr->next;
}
}
}
}
if (elements) {
if (!sxe->nodep()) {
sxe->node = libxml_register_node(node);
}
if (member.isNull() || member.isInteger()) {
long cnt = 0;
xmlNodePtr mynode = node;
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
if (sxe->iter.type == SXE_ITER_NONE) {
if (!member.isNull() && member.toInt64() > 0) {
raise_warning("Cannot add element %s number %" PRId64 " when "
"only 0 such elements exist", mynode->name,
member.toInt64());
}
} else if (!member.isNull()) {
node = sxe_get_element_by_offset(sxe, member.toInt64(), node, &cnt);
} else {
node = nullptr;
}
if (node) {
return_value = _node_as_zval(sxe, node, SXE_ITER_NONE, nullptr,
sxe->iter.nsprefix, sxe->iter.isprefix);
}
// Zend would check here if this is a write operation, but HHVM always
// handles that with offsetSet so we just want to return nullptr here.
} else {
#if SXE_ELEMENT_BY_NAME
int newtype;
node = sxe->nodep();
node = sxe_get_element_by_name(sxe, node, &name.data(), &newtype);
if (node) {
return_value = _node_as_zval(sxe, node, newtype, name.data(),
sxe->iter.nsprefix, sxe->iter.isprefix);
}
#else
return_value = _node_as_zval(sxe, node, SXE_ITER_ELEMENT, name.data(),
sxe->iter.nsprefix, sxe->iter.isprefix);
#endif
}
}
}
return return_value;
}
static void change_node_zval(xmlNodePtr node, const Variant& value) {
if (value.isNull()) {
xmlNodeSetContentLen(node, (xmlChar*)"", 0);
return;
}
if (value.isInteger() || value.isBoolean() || value.isDouble() ||
value.isNull() || value.isString()) {
xmlChar* buffer =
xmlEncodeEntitiesReentrant(node->doc,
(xmlChar*)value.toString().data());
int64_t buffer_len = xmlStrlen(buffer);
/* check for nullptr buffer in case of
* memory error in xmlEncodeEntitiesReentrant */
if (buffer) {
xmlNodeSetContentLen(node, buffer, buffer_len);
xmlFree(buffer);
}
} else {
raise_warning("It is not possible to assign complex types to nodes");
}
}
static void sxe_prop_dim_delete(SimpleXMLElement* sxe, const Variant& member,
bool elements, bool attribs) {
xmlNodePtr node = sxe->nodep();
if (member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
}
}
xmlAttrPtr attr = nullptr;
bool test = 0;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
}
if (node) {
if (attribs) {
if (member.isInteger()) {
int64_t nodendx = 0;
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
libxml_register_node((xmlNodePtr) attr)->unlink();
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
xmlAttrPtr anext;
while (attr) {
anext = attr->next;
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)member.toString().data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
libxml_register_node((xmlNodePtr) attr)->unlink();
break;
}
attr = anext;
}
}
}
if (elements) {
if (member.isInteger()) {
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
node = sxe_get_element_by_offset(sxe, member.toInt64(), node, nullptr);
if (node) {
libxml_register_node(node)->unlink();
}
} else {
node = node->children;
xmlNodePtr nnext;
while (node) {
nnext = node->next;
SKIP_TEXT(node);
if (!xmlStrcmp(node->name, (xmlChar*)member.toString().data())) {
libxml_register_node(node)->unlink();
}
next_iter:
node = nnext;
}
}
}
}
}
static bool sxe_prop_dim_exists(SimpleXMLElement* sxe, const Variant& member,
bool check_empty, bool elements, bool attribs) {
xmlNodePtr node = sxe->nodep();
if (member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
}
}
xmlAttrPtr attr = nullptr;
bool test = false;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
}
bool exists = false;
if (node) {
if (attribs) {
if (member.isInteger()) {
int64_t nodendx = 0;
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
exists = true;
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)member.toString().data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
exists = true;
break;
}
attr = attr->next;
}
}
if (exists && check_empty == 1 &&
(!attr->children || !attr->children->content ||
!attr->children->content[0] ||
!xmlStrcmp(attr->children->content, (const xmlChar*)"0")) ) {
/* Attribute with no content in it's text node */
exists = false;
}
}
if (elements) {
if (member.isInteger()) {
if (sxe->iter.type == SXE_ITER_CHILD) {
node = php_sxe_get_first_node(sxe, node);
}
node = sxe_get_element_by_offset(sxe, member.toInt64(), node, nullptr);
}
else {
node = node->children;
while (node) {
xmlNodePtr nnext;
nnext = node->next;
if ((node->type == XML_ELEMENT_NODE) &&
!xmlStrcmp(node->name, (xmlChar*)member.toString().data())) {
break;
}
node = nnext;
}
}
if (node) {
exists = true;
if (check_empty == true &&
(!node->children || (node->children->type == XML_TEXT_NODE &&
!node->children->next &&
(!node->children->content ||
!node->children->content[0] ||
!xmlStrcmp(node->children->content,
(const xmlChar*)"0"))))) {
exists = false;
}
}
}
}
return exists;
}
static inline String sxe_xmlNodeListGetString(xmlDocPtr doc, xmlNodePtr list,
bool inLine) {
xmlChar* tmp = xmlNodeListGetString(doc, list, inLine);
if (tmp) {
String ret = String((char*)tmp);
xmlFree(tmp);
return ret;
} else {
return empty_string();
}
}
static Variant _get_base_node_value(SimpleXMLElement* sxe_ref,
xmlNodePtr node, xmlChar* nsprefix,
bool isprefix) {
if (node->children &&
node->children->type == XML_TEXT_NODE &&
!xmlIsBlankNode(node->children)) {
xmlChar* contents = xmlNodeListGetString(node->doc, node->children, 1);
if (contents) {
String obj = String((char*)contents);
xmlFree(contents);
return obj;
}
} else {
auto sxeRefObj = Native::object<SimpleXMLElement>(sxe_ref);
Object obj = create_object(sxeRefObj->getClassName(), Array(), false);
auto subnode = Native::data<SimpleXMLElement>(obj.get());
if (nsprefix && *nsprefix) {
subnode->iter.nsprefix = xmlStrdup((xmlChar*)nsprefix);
subnode->iter.isprefix = isprefix;
}
subnode->node = libxml_register_node(node);
return obj;
}
return init_null();
}
static void sxe_properties_add(Array& rv, char* name, const Variant& value) {
String sName = String(name);
if (rv.exists(sName)) {
Variant existVal = rv[sName];
if (existVal.isArray()) {
Array arr = existVal.toArray();
arr.append(value);
rv.set(sName, arr);
} else {
Array arr = Array::Create();
arr.append(existVal);
arr.append(value);
rv.set(sName, arr);
}
} else {
rv.set(sName, value);
}
}
static void sxe_get_prop_hash(SimpleXMLElement* sxe, bool is_debug,
Array& rv, bool isBoolCast = false) {
rv.clear();
Object iter_data;
bool use_iter = false;
xmlNodePtr node = sxe->nodep();
if (!node) {
return;
}
if (is_debug || sxe->iter.type != SXE_ITER_CHILD) {
if (sxe->iter.type == SXE_ITER_ELEMENT) {
node = php_sxe_get_first_node(sxe, node);
}
if (!node || node->type != XML_ENTITY_DECL) {
xmlAttrPtr attr = node ? (xmlAttrPtr)node->properties : nullptr;
Array zattr = Array::Create();
bool test = sxe->iter.name && sxe->iter.type == SXE_ITER_ATTRLIST;
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr)attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
zattr.set(String((char*)attr->name),
sxe_xmlNodeListGetString(
sxe->docp(),
attr->children,
1));
}
attr = attr->next;
}
if (zattr.size()) {
rv.set(String("@attributes"), zattr);
}
}
}
node = sxe->nodep();
node = php_sxe_get_first_node(sxe, node);
if (node && sxe->iter.type != SXE_ITER_ATTRLIST) {
if (node->type == XML_ATTRIBUTE_NODE) {
rv.append(sxe_xmlNodeListGetString(node->doc, node->children, 1));
node = nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
if (sxe->iter.type == SXE_ITER_NONE || !node->children ||
!node->parent ||
node->children->next ||
node->children->children ||
node->parent->children == node->parent->last) {
node = node->children;
} else {
iter_data = sxe->iter.data;
sxe->iter.data.reset();
node = php_sxe_reset_iterator(sxe, false);
use_iter = true;
}
}
char *name = nullptr;
Variant value;
while (node) {
if (node->children != nullptr || node->prev != nullptr ||
node->next != nullptr) {
SKIP_TEXT(node);
} else {
if (node->type == XML_TEXT_NODE) {
const xmlChar* cur = node->content;
if (*cur != 0) {
rv.append(sxe_xmlNodeListGetString(node->doc, node, 1));
}
goto next_iter;
}
}
if (node->type == XML_ELEMENT_NODE &&
(!match_ns(sxe, node, sxe->iter.nsprefix, sxe->iter.isprefix))) {
goto next_iter;
}
name = (char*)node->name;
if (!name) {
goto next_iter;
}
value = _get_base_node_value(sxe, node, sxe->iter.nsprefix,
sxe->iter.isprefix);
if (use_iter) {
rv.append(value);
} else {
sxe_properties_add(rv, name, value);
}
if (isBoolCast) break;
next_iter:
if (use_iter) {
node = php_sxe_iterator_fetch(sxe, node->next, 0);
} else {
node = node->next;
}
}
}
if (use_iter) {
sxe->iter.data = iter_data;
}
}
Variant SimpleXMLElement_objectCast(const ObjectData* obj, int8_t type) {
assert(obj->instanceof(SimpleXMLElement_classof()));
auto sxe = Native::data<SimpleXMLElement>(const_cast<ObjectData*>(obj));
if (type == KindOfBoolean) {
xmlNodePtr node = php_sxe_get_first_node(sxe, nullptr);
if (node) return true;
Array properties = Array::Create();
sxe_get_prop_hash(sxe, true, properties, true);
return properties.size() != 0;
}
if (isArrayType((DataType)type)) {
Array properties = Array::Create();
sxe_get_prop_hash(sxe, true, properties);
return properties;
}
xmlChar* contents = nullptr;
if (sxe->iter.type != SXE_ITER_NONE) {
xmlNodePtr node = php_sxe_get_first_node(sxe, nullptr);
if (node) {
contents = xmlNodeListGetString(sxe->docp(), node->children, 1);
}
} else {
xmlDocPtr doc = sxe->docp();
if (!sxe->nodep()) {
if (doc) {
sxe->node = libxml_register_node(xmlDocGetRootElement(doc));
}
}
if (sxe->nodep()) {
if (sxe->nodep()->children) {
contents = xmlNodeListGetString(doc, sxe->nodep()->children, 1);
}
}
}
String ret = String((char*)contents);
if (contents) {
xmlFree(contents);
}
switch (type) {
case KindOfString: return ret;
case KindOfInt64: return toInt64(ret);
case KindOfDouble: return toDouble(ret);
default: return init_null();
}
}
static bool sxe_prop_dim_write(SimpleXMLElement* sxe, const Variant& member,
const Variant& value, bool elements, bool attribs,
xmlNodePtr* pnewnode) {
xmlNodePtr node = sxe->nodep();
if (member.isNull() || member.isInteger()) {
if (sxe->iter.type != SXE_ITER_ATTRLIST) {
attribs = false;
elements = true;
} else if (member.isNull()) {
/* This happens when the user did: $sxe[] = $value
* and could also be E_PARSE, but we use this only during parsing
* and this is during runtime.
*/
raise_error("Cannot create unnamed attribute");
return false;
}
} else {
if (member.toString().empty()) {
raise_warning("Cannot write or create unnamed %s",
attribs ? "attribute" : "element");
return false;
}
}
bool retval = true;
xmlAttrPtr attr = nullptr;
xmlNodePtr mynode = nullptr;
bool test = false;
if (sxe->iter.type == SXE_ITER_ATTRLIST) {
attribs = true;
elements = false;
node = php_sxe_get_first_node(sxe, node);
attr = (xmlAttrPtr)node;
test = sxe->iter.name != nullptr;
} else if (sxe->iter.type != SXE_ITER_CHILD) {
mynode = node;
node = php_sxe_get_first_node(sxe, node);
attr = node ? node->properties : nullptr;
test = false;
if (member.isNull() && node && node->parent &&
node->parent->type == XML_DOCUMENT_NODE) {
/* This happens when the user did: $sxe[] = $value
* and could also be E_PARSE, but we use this only during parsing
* and this is during runtime.
*/
raise_error("Cannot create unnamed attribute");
return false;
}
if (attribs && !node && sxe->iter.type == SXE_ITER_ELEMENT) {
node = xmlNewChild(mynode, mynode->ns, sxe->iter.name, nullptr);
attr = node->properties;
}
}
mynode = node;
if (!(value.isString() || value.isInteger() || value.isBoolean() ||
value.isDouble() || value.isNull() || value.isObject())) {
raise_warning("It is not yet possible to assign complex types to %s",
attribs ? "attributes" : "properties");
return false;
}
xmlNodePtr newnode = nullptr;
if (node) {
int64_t nodendx = 0;
int64_t counter = 0;
bool is_attr = false;
if (attribs) {
if (member.isInteger()) {
while (attr && nodendx <= member.toInt64()) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
if (nodendx == member.toInt64()) {
is_attr = true;
++counter;
break;
}
nodendx++;
}
attr = attr->next;
}
} else {
while (attr) {
if ((!test || !xmlStrcmp(attr->name, sxe->iter.name)) &&
!xmlStrcmp(attr->name, (xmlChar*)member.toString().data()) &&
match_ns(sxe, (xmlNodePtr) attr, sxe->iter.nsprefix,
sxe->iter.isprefix)) {
is_attr = true;
++counter;
break;
}
attr = attr->next;
}
}
}
long cnt = 0;
if (elements) {
if (member.isNull() || member.isInteger()) {
if (node->type == XML_ATTRIBUTE_NODE) {
raise_error("Cannot create duplicate attribute");
return false;
}
if (sxe->iter.type == SXE_ITER_NONE) {
newnode = node;
++counter;
if (!member.isNull() && member.toInt64() > 0) {
raise_warning("Cannot add element %s number %" PRId64 " when "
"only 0 such elements exist", mynode->name,
member.toInt64());
retval = false;
}
} else if (!member.isNull()) {
newnode =
sxe_get_element_by_offset(sxe, member.toInt64(), node, &cnt);
if (newnode) {
++counter;
}
}
} else {
node = node->children;
while (node) {
SKIP_TEXT(node)
if (!xmlStrcmp(node->name, (xmlChar*)member.toString().data())) {
newnode = node;
++counter;
}
next_iter:
node = node->next;
}
}
}
if (counter == 1) {
if (is_attr) {
newnode = (xmlNodePtr) attr;
}
if (!value.isNull()) {
xmlNodePtr tempnode;
while ((tempnode = (xmlNodePtr) newnode->children)) {
libxml_register_node(tempnode)->unlink();
}
change_node_zval(newnode, value);
}
} else if (counter > 1) {
raise_warning("Cannot assign to an array of nodes "
"(duplicate subnodes or attr detected)");
retval = false;
} else if (elements) {
if (!node) {
if (member.isNull() || member.isInteger()) {
newnode =
xmlNewTextChild(
mynode->parent, mynode->ns, mynode->name,
!value.isNull() ? (xmlChar*)value.toString().data() : nullptr);
} else {
newnode =
xmlNewTextChild(
mynode, mynode->ns, (xmlChar*)member.toString().data(),
!value.isNull() ? (xmlChar*)value.toString().data() : nullptr);
}
} else if (member.isNull() || member.isInteger()) {
if (!member.isNull() && cnt < member.toInt64()) {
raise_warning("Cannot add element %s number %" PRId64 " when "
"only %ld such elements exist", mynode->name,
member.toInt64(), cnt);
retval = false;
}
newnode = xmlNewTextChild(mynode->parent, mynode->ns, mynode->name,
!value.isNull() ?
(xmlChar*)value.toString().data() : nullptr);
}
} else if (attribs) {
if (member.isInteger()) {
raise_warning("Cannot change attribute number %" PRId64 " when "
"only %" PRId64 " attributes exist", member.toInt64(),
nodendx);
retval = false;
} else {
newnode = (xmlNodePtr)xmlNewProp(node,
(xmlChar*)member.toString().data(),
!value.isNull() ?
(xmlChar*)value.toString().data() :
nullptr);
}
}
}
if (pnewnode) {
*pnewnode = newnode;
}
return retval;
}
///////////////////////////////////////////////////////////////////////////////
// SimpleXML
static const Class* class_from_name(const String& class_name,
const char* callee) {
const Class* cls;
if (!class_name.empty()) {
cls = Unit::loadClass(class_name.get());
if (!cls) {
throw_invalid_argument("class not found: %s", class_name.data());
return nullptr;
}
if (!cls->classof(SimpleXMLElement_classof())) {
throw_invalid_argument(
"%s() expects parameter 2 to be a class name "
"derived from SimpleXMLElement, '%s' given",
callee,
class_name.data());
return nullptr;
}
} else {
cls = SimpleXMLElement_classof();
}
return cls;
}
const StaticString s_DOMNode("DOMNode");
static Variant HHVM_FUNCTION(simplexml_import_dom,
const Object& node,
const String& class_name) {
if (!node->instanceof(s_DOMNode)) {
raise_warning("Invalid Nodetype to import");
return init_null();
}
auto domnode = Native::data<DOMNode>(node);
xmlNodePtr nodep = domnode->nodep();
if (nodep) {
if (nodep->doc == nullptr) {
raise_warning("Imported Node must have associated Document");
return init_null();
}
if (nodep->type == XML_DOCUMENT_NODE ||
nodep->type == XML_HTML_DOCUMENT_NODE) {
nodep = xmlDocGetRootElement((xmlDocPtr) nodep);
}
}
if (nodep && nodep->type == XML_ELEMENT_NODE) {
auto cls = class_from_name(class_name, "simplexml_import_dom");
if (!cls) {
return init_null();
}
Object obj = create_object(cls->nameStr(), Array(), false);
auto sxe = Native::data<SimpleXMLElement>(obj.get());
sxe->node = libxml_register_node(nodep);
return obj;
} else {
raise_warning("Invalid Nodetype to import");
return init_null();
}
return false;
}
static Variant HHVM_FUNCTION(simplexml_load_string,
const String& data,
const String& class_name /* = "SimpleXMLElement" */,
int64_t options /* = 0 */,
const String& ns /* = "" */,
bool is_prefix /* = false */) {
SYNC_VM_REGS_SCOPED();
auto cls = class_from_name(class_name, "simplexml_load_string");
if (!cls) {
return init_null();
}
xmlDocPtr doc = xmlReadMemory(data.data(), data.size(), nullptr,
nullptr, options);
if (!doc) {
return false;
}
Object obj = create_object(cls->nameStr(), Array(), false);
auto sxe = Native::data<SimpleXMLElement>(obj.get());
sxe->node = libxml_register_node(xmlDocGetRootElement(doc));
sxe->iter.nsprefix = ns.size() ? xmlStrdup((xmlChar*)ns.data()) : nullptr;
sxe->iter.isprefix = is_prefix;
return obj;
}
static Variant HHVM_FUNCTION(simplexml_load_file,
const String& filename,
const String& class_name /* = "SimpleXMLElement" */,
int64_t options /* = 0 */, const String& ns /* = "" */,
bool is_prefix /* = false */) {
SYNC_VM_REGS_SCOPED();
auto cls = class_from_name(class_name, "simplexml_load_file");
if (!cls) {
return init_null();
}
auto stream = File::Open(filename, "rb");
if (!stream || stream->isInvalid()) return false;
xmlDocPtr doc = nullptr;
// The XML context is also deleted in this function, so the ownership
// of the File is kept locally in 'stream'. The libxml_streams_IO_nop_close
// callback does nothing.
xmlParserCtxtPtr ctxt = xmlCreateIOParserCtxt(nullptr, nullptr,
libxml_streams_IO_read,
libxml_streams_IO_nop_close,
&stream,
XML_CHAR_ENCODING_NONE);
if (ctxt == nullptr) return false;
SCOPE_EXIT { xmlFreeParserCtxt(ctxt); };
if (ctxt->directory == nullptr) {
ctxt->directory = xmlParserGetDirectory(filename.c_str());
}
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
doc = ctxt->myDoc;
} else {
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = nullptr;
return false;
}
Object obj = create_object(cls->nameStr(), Array(), false);
auto sxe = Native::data<SimpleXMLElement>(obj.get());
sxe->node = libxml_register_node(xmlDocGetRootElement(doc));
sxe->iter.nsprefix = ns.size() ? xmlStrdup((xmlChar*)ns.data()) : nullptr;
sxe->iter.isprefix = is_prefix;
return obj;
}
///////////////////////////////////////////////////////////////////////////////
// SimpleXMLElement
static void HHVM_METHOD(SimpleXMLElement, __construct,
const String& data,
int64_t options /* = 0 */,
bool data_is_url /* = false */,
const String& ns /* = "" */,
bool is_prefix /* = false */) {
SYNC_VM_REGS_SCOPED();
xmlDocPtr docp = data_is_url ?
xmlReadFile(data.data(), nullptr, options) :
xmlReadMemory(data.data(), data.size(), nullptr, nullptr, options);
if (!docp) {
SystemLib::throwExceptionObject("String could not be parsed as XML");
}
auto sxe = Native::data<SimpleXMLElement>(this_);
sxe->iter.nsprefix = !ns.empty() ? xmlStrdup((xmlChar*)ns.data()) : nullptr;
sxe->iter.isprefix = is_prefix;
sxe->node = libxml_register_node(xmlDocGetRootElement(docp));
}
static Variant HHVM_METHOD(SimpleXMLElement, xpath, const String& path) {
auto data = Native::data<SimpleXMLElement>(this_);
if (data->iter.type == SXE_ITER_ATTRLIST) {
return init_null(); // attributes don't have attributes
}
if (!data->xpath) {
data->xpath = xmlXPathNewContext(data->docp());
}
if (!data->nodep()) {
data->node = libxml_register_node(xmlDocGetRootElement(data->docp()));
}
auto nodeptr = php_sxe_get_first_node(data, data->nodep());
data->xpath->node = nodeptr;
xmlNsPtr* ns = xmlGetNsList(data->docp(), nodeptr);
int64_t nsnbr = 0;
if (ns != nullptr) {
while (ns[nsnbr] != nullptr) {
nsnbr++;
}
}
auto& xpath = data->xpath;
xpath->namespaces = ns;
xpath->nsNr = nsnbr;
xmlXPathObjectPtr retval = xmlXPathEval((xmlChar*)path.data(), xpath);
if (ns != nullptr) {
xmlFree(ns);
xpath->namespaces = nullptr;
xpath->nsNr = 0;
}
if (!retval) {
return false;
}
xmlNodeSetPtr result = retval->nodesetval;
Array ret = Array::Create();
if (result != nullptr) {
for (int64_t i = 0; i < result->nodeNr; ++i) {
nodeptr = result->nodeTab[i];
if (nodeptr->type == XML_TEXT_NODE ||
nodeptr->type == XML_ELEMENT_NODE ||
nodeptr->type == XML_ATTRIBUTE_NODE) {
/**
* Detect the case where the last selector is text(), simplexml
* always accesses the text() child by default, therefore we assign
* to the parent node.
*/
Object obj;
if (nodeptr->type == XML_TEXT_NODE) {
obj = _node_as_zval(data, nodeptr->parent, SXE_ITER_NONE, nullptr,
nullptr, false);
} else if (nodeptr->type == XML_ATTRIBUTE_NODE) {
obj = _node_as_zval(data, nodeptr->parent, SXE_ITER_ATTRLIST,
(char*)nodeptr->name, nodeptr->ns ?
(xmlChar*)nodeptr->ns->href : nullptr, false);
} else {
obj = _node_as_zval(data, nodeptr, SXE_ITER_NONE, nullptr, nullptr,
false);
}
if (!obj.isNull()) {
ret.append(obj);
}
}
}
}
xmlXPathFreeObject(retval);
return ret;
}
static bool HHVM_METHOD(SimpleXMLElement, registerXPathNamespace,
const String& prefix, const String& ns) {
auto data = Native::data<SimpleXMLElement>(this_);
if (!data->xpath) {
data->xpath = xmlXPathNewContext(data->docp());
}
if (xmlXPathRegisterNs(data->xpath,
(xmlChar*)prefix.data(),
(xmlChar*)ns.data()) != 0) {
return false;
}
return true;
}
static Variant HHVM_METHOD(SimpleXMLElement, asXML,
const String& filename /* = "" */) {
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
xmlOutputBufferPtr outbuf = nullptr;
if (filename.size()) {
node = php_sxe_get_first_node(data, node);
if (node) {
xmlDocPtr doc = data->docp();
if (node->parent && (XML_DOCUMENT_NODE == node->parent->type)) {
int bytes;
bytes = xmlSaveFile(filename.data(), doc);
if (bytes == -1) {
return false;
} else {
return true;
}
} else {
outbuf = xmlOutputBufferCreateFilename(filename.data(), nullptr, 0);
if (outbuf == nullptr) {
return false;
}
xmlNodeDumpOutput(outbuf, doc, node, 0, 0, nullptr);
xmlOutputBufferClose(outbuf);
return true;
}
} else {
return false;
}
}
node = php_sxe_get_first_node(data, node);
if (node) {
xmlDocPtr doc = data->docp();
if (node->parent && (XML_DOCUMENT_NODE == node->parent->type)) {
xmlChar* strval;
int strval_len;
xmlDocDumpMemoryEnc(doc, &strval, &strval_len,
(const char*)doc->encoding);
String ret = String((char*)strval);
xmlFree(strval);
return ret;
} else {
/* Should we be passing encoding information instead of nullptr? */
outbuf = xmlAllocOutputBuffer(nullptr);
if (outbuf == nullptr) {
return false;
}
xmlNodeDumpOutput(outbuf, doc, node, 0, 0,
(const char*)doc->encoding);
xmlOutputBufferFlush(outbuf);
char* str = nullptr;
#ifdef LIBXML2_NEW_BUFFER
str = (char*)xmlOutputBufferGetContent(outbuf);
#else
str = (char*)outbuf->buffer->content;
#endif
String ret = String(str);
xmlOutputBufferClose(outbuf);
return ret;
}
} else {
return false;
}
return false;
}
static Array HHVM_METHOD(SimpleXMLElement, getNamespaces,
bool recursive /* = false */) {
auto data = Native::data<SimpleXMLElement>(this_);
Array ret = Array::Create();
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
if (node) {
if (node->type == XML_ELEMENT_NODE) {
sxe_add_namespaces(data, node, recursive, ret);
} else if (node->type == XML_ATTRIBUTE_NODE && node->ns) {
sxe_add_namespace_name(ret, node->ns);
}
}
return ret;
}
static Array HHVM_METHOD(SimpleXMLElement, getDocNamespaces,
bool recursive /* = false */,
bool from_root /* = true */) {
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node =
from_root ? xmlDocGetRootElement(data->docp())
: data->nodep();
Array ret = Array::Create();
sxe_add_registered_namespaces(data, node, recursive, ret);
return ret;
}
static Variant HHVM_METHOD(SimpleXMLElement, children,
const String& ns = empty_string(),
bool is_prefix = false) {
auto data = Native::data<SimpleXMLElement>(this_);
if (data->iter.type == SXE_ITER_ATTRLIST) {
return init_null(); /* attributes don't have attributes */
}
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
return _node_as_zval(data, node, SXE_ITER_CHILD, nullptr,
(xmlChar*)ns.data(), is_prefix);
}
static String HHVM_METHOD(SimpleXMLElement, getName) {
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
if (node) {
return String((char*)node->name);
}
return empty_string();
}
static Object HHVM_METHOD(SimpleXMLElement, attributes,
const String& ns /* = "" */,
bool is_prefix /* = false */) {
auto data = Native::data<SimpleXMLElement>(this_);
if (data->iter.type == SXE_ITER_ATTRLIST) {
return Object(); /* attributes don't have attributes */
}
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
return _node_as_zval(data, node, SXE_ITER_ATTRLIST, nullptr,
(xmlChar*)ns.data(), is_prefix);
}
static Variant HHVM_METHOD(SimpleXMLElement, addChild,
const String& qname,
const String& value /* = null_string */,
const Variant& ns /* = null */) {
if (qname.empty()) {
raise_warning("Element name is required");
return init_null();
}
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
if (data->iter.type == SXE_ITER_ATTRLIST) {
raise_warning("Cannot add element to attributes");
return init_null();
}
node = php_sxe_get_first_node(data, node);
if (node == nullptr) {
raise_warning("Cannot add child. "
"Parent is not a permanent member of the XML tree");
return init_null();
}
xmlChar* prefix = nullptr;
xmlChar* localname = xmlSplitQName2((xmlChar*)qname.data(), &prefix);
if (localname == nullptr) {
localname = xmlStrdup((xmlChar*)qname.data());
}
xmlNodePtr newnode = xmlNewChild(node, nullptr, localname,
(xmlChar*)value.data());
xmlNsPtr nsptr = nullptr;
if (!ns.isNull()) {
const String& ns_ = ns.toString();
if (ns_.empty()) {
newnode->ns = nullptr;
nsptr = xmlNewNs(newnode, (xmlChar*)ns_.data(), prefix);
} else {
nsptr = xmlSearchNsByHref(node->doc, node, (xmlChar*)ns_.data());
if (nsptr == nullptr) {
nsptr = xmlNewNs(newnode, (xmlChar*)ns_.data(), prefix);
}
newnode->ns = nsptr;
}
}
Object ret = _node_as_zval(data, newnode, SXE_ITER_NONE, (char*)localname,
prefix, false);
xmlFree(localname);
if (prefix != nullptr) {
xmlFree(prefix);
}
return ret;
}
static void HHVM_METHOD(SimpleXMLElement, addAttribute,
const String& qname,
const String& value /* = null_string */,
const String& ns /* = null_string */) {
if (qname.size() == 0) {
raise_warning("Attribute name is required");
return;
}
auto data = Native::data<SimpleXMLElement>(this_);
xmlNodePtr node = data->nodep();
node = php_sxe_get_first_node(data, node);
if (node && node->type != XML_ELEMENT_NODE) {
node = node->parent;
}
if (node == nullptr) {
raise_warning("Unable to locate parent Element");
return;
}
xmlChar* prefix = nullptr;
xmlChar* localname = xmlSplitQName2((xmlChar*)qname.data(), &prefix);
if (localname == nullptr) {
if (ns.size() > 0) {
if (prefix != nullptr) {
xmlFree(prefix);
}
raise_warning("Attribute requires prefix for namespace");
return;
}
localname = xmlStrdup((xmlChar*)qname.data());
}
xmlAttrPtr attrp = xmlHasNsProp(node, localname, (xmlChar*)ns.data());
if (attrp != nullptr && attrp->type != XML_ATTRIBUTE_DECL) {
xmlFree(localname);
if (prefix != nullptr) {
xmlFree(prefix);
}
raise_warning("Attribute already exists");
return;
}
xmlNsPtr nsptr = nullptr;
if (ns.size()) {
nsptr = xmlSearchNsByHref(node->doc, node, (xmlChar*)ns.data());
if (nsptr == nullptr) {
nsptr = xmlNewNs(node, (xmlChar*)ns.data(), prefix);
}
}
attrp = xmlNewNsProp(node, nsptr, localname, (xmlChar*)value.data());
xmlFree(localname);
if (prefix != nullptr) {
xmlFree(prefix);
}
}
static String HHVM_METHOD(SimpleXMLElement, __toString) {
return SimpleXMLElement_objectCast(this_, KindOfString).toString();
}
static Variant HHVM_METHOD(SimpleXMLElement, __get, const Variant& name) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_read(data, name, true, false);
}
static Variant HHVM_METHOD(SimpleXMLElement, __unset, const Variant& name) {
auto data = Native::data<SimpleXMLElement>(this_);
sxe_prop_dim_delete(data, name, true, false);
return init_null();
}
static bool HHVM_METHOD(SimpleXMLElement, __isset, const Variant& name) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_exists(data, name, false, true, false);
}
static Variant HHVM_METHOD(SimpleXMLElement, __set,
const Variant& name, const Variant& value) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_write(data, name, value, true, false, nullptr);
}
bool SimpleXMLElement_propEmpty(const ObjectData* this_,
const StringData* key) {
auto data = Native::data<SimpleXMLElement>(const_cast<ObjectData*>(this_));
return !sxe_prop_dim_exists(data, Variant(key->toCppString()),
true, true, false);
}
static int64_t HHVM_METHOD(SimpleXMLElement, count) {
auto data = Native::data<SimpleXMLElement>(this_);
return php_sxe_count_elements_helper(data);
}
///////////////////////////////////////////////////////////////////////////////
// ArrayAccess
static bool HHVM_METHOD(SimpleXMLElement, offsetExists,
const Variant& index) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_exists(data, index, false, false, true);
}
static Variant HHVM_METHOD(SimpleXMLElement, offsetGet,
const Variant& index) {
auto data = Native::data<SimpleXMLElement>(this_);
return sxe_prop_dim_read(data, index, false, true);
}
static void HHVM_METHOD(SimpleXMLElement, offsetSet,
const Variant& index, const Variant& newvalue) {
auto data = Native::data<SimpleXMLElement>(this_);
sxe_prop_dim_write(data, index, newvalue, false, true, nullptr);
}
static void HHVM_METHOD(SimpleXMLElement, offsetUnset,
const Variant& index) {
auto data = Native::data<SimpleXMLElement>(this_);
sxe_prop_dim_delete(data, index, false, true);
}
///////////////////////////////////////////////////////////////////////////////
// Iterator
static void HHVM_METHOD(SimpleXMLElementIterator, __construct,
const Variant& sxe) {
if (sxe.isObject()) {
Native::data<SimpleXMLElementIterator>(this_)->setSxe(sxe.toObject());
}
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, current) {
return Native::data<SimpleXMLElementIterator>(this_)->sxe()->iter.data;
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, key) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
Object curobj = sxe->iter.data;
xmlNodePtr curnode = curobj.isNull()
? nullptr
: Native::data<SimpleXMLElement>(curobj.get())->nodep();
if (curnode) {
return String((char*)curnode->name);
} else {
return init_null();
}
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, next) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
php_sxe_move_forward_iterator(sxe);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, rewind) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
php_sxe_reset_iterator(sxe, true);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLElementIterator, valid) {
auto sxe = Native::data<SimpleXMLElementIterator>(this_)->sxe();
return !sxe->iter.data.isNull();
}
///////////////////////////////////////////////////////////////////////////////
// SimpleXMLIterator
static Variant HHVM_METHOD(SimpleXMLIterator, current) {
auto data = Native::data<SimpleXMLIterator>(this_);
return data->iter.data;
}
static Variant HHVM_METHOD(SimpleXMLIterator, key) {
auto data = Native::data<SimpleXMLIterator>(this_);
Object curobj = data->iter.data;
if (curobj.isNull()) {
return init_null();
}
assert(curobj->instanceof(SimpleXMLElement_classof()));
auto curnode = Native::data<SimpleXMLElement>(curobj.get())->nodep();
return String((char*)curnode->name);
}
static Variant HHVM_METHOD(SimpleXMLIterator, next) {
auto data = Native::data<SimpleXMLIterator>(this_);
php_sxe_move_forward_iterator(data);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLIterator, rewind) {
auto data = Native::data<SimpleXMLIterator>(this_);
php_sxe_reset_iterator(data, true);
return init_null();
}
static Variant HHVM_METHOD(SimpleXMLIterator, valid) {
auto data = Native::data<SimpleXMLIterator>(this_);
return !data->iter.data.isNull();
}
static Variant HHVM_METHOD(SimpleXMLIterator, getChildren) {
auto data = Native::data<SimpleXMLIterator>(this_);
auto current = data->iter.data;
if (current.isNull()) {
return init_null();
}
assert(current->instanceof(SimpleXMLElement_classof()));
return HHVM_MN(SimpleXMLElement, children)(current.get());
}
static bool HHVM_METHOD(SimpleXMLIterator, hasChildren) {
auto children = HHVM_MN(SimpleXMLIterator, getChildren)(this_);
if (!children.isObject()) {
return false;
}
auto od = children.toObject().get();
assert(od->instanceof(SimpleXMLElement_classof()));
return HHVM_MN(SimpleXMLElement, count)(od) > 0;
}
///////////////////////////////////////////////////////////////////////////////
static struct SimpleXMLExtension : Extension {
SimpleXMLExtension(): Extension("simplexml", "1.0") {}
void moduleInit() override {
HHVM_FE(simplexml_import_dom);
HHVM_FE(simplexml_load_string);
HHVM_FE(simplexml_load_file);
/* SimpleXMLElement */
HHVM_ME(SimpleXMLElement, __construct);
HHVM_ME(SimpleXMLElement, xpath);
HHVM_ME(SimpleXMLElement, registerXPathNamespace);
HHVM_ME(SimpleXMLElement, asXML);
HHVM_ME(SimpleXMLElement, getNamespaces);
HHVM_ME(SimpleXMLElement, getDocNamespaces);
HHVM_ME(SimpleXMLElement, children);
HHVM_ME(SimpleXMLElement, getName);
HHVM_ME(SimpleXMLElement, attributes);
HHVM_ME(SimpleXMLElement, addChild);
HHVM_ME(SimpleXMLElement, addAttribute);
HHVM_ME(SimpleXMLElement, __toString);
HHVM_ME(SimpleXMLElement, __get);
HHVM_ME(SimpleXMLElement, __unset);
HHVM_ME(SimpleXMLElement, __isset);
HHVM_ME(SimpleXMLElement, __set);
HHVM_ME(SimpleXMLElement, count);
HHVM_ME(SimpleXMLElement, offsetExists);
HHVM_ME(SimpleXMLElement, offsetGet);
HHVM_ME(SimpleXMLElement, offsetSet);
HHVM_ME(SimpleXMLElement, offsetUnset);
Native::registerNativeDataInfo<SimpleXMLElement>(
s_SimpleXMLElement.get()
);
/* SimpleXMLElementIterator */
HHVM_ME(SimpleXMLElementIterator, __construct);
HHVM_ME(SimpleXMLElementIterator, current);
HHVM_ME(SimpleXMLElementIterator, key);
HHVM_ME(SimpleXMLElementIterator, next);
HHVM_ME(SimpleXMLElementIterator, rewind);
HHVM_ME(SimpleXMLElementIterator, valid);
Native::registerNativeDataInfo<SimpleXMLElementIterator>(
s_SimpleXMLElementIterator.get(),
Native::NDIFlags::NO_SWEEP
);
/* SimpleXMLIterator */
HHVM_ME(SimpleXMLIterator, current);
HHVM_ME(SimpleXMLIterator, key);
HHVM_ME(SimpleXMLIterator, next);
HHVM_ME(SimpleXMLIterator, rewind);
HHVM_ME(SimpleXMLIterator, valid);
HHVM_ME(SimpleXMLIterator, getChildren);
HHVM_ME(SimpleXMLIterator, hasChildren);
Native::registerNativeDataInfo<SimpleXMLIterator>(
s_SimpleXMLIterator.get()
);
loadSystemlib();
}
} s_simplexml_extension;
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-345/cpp/good_4748_0 |
crossvul-cpp_data_bad_1023_0 | /*
* Copyright (c) 2002 - 2003
* NetGroup, Politecnico di Torino (Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "ftmacros.h"
#include "varattrs.h"
#include <errno.h> // for the errno variable
#include <stdlib.h> // for malloc(), free(), ...
#include <string.h> // for strlen(), ...
#ifdef _WIN32
#include <process.h> // for threads
#else
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h> // for select() and such
#include <pwd.h> // for password management
#endif
#ifdef HAVE_GETSPNAM
#include <shadow.h> // for password management
#endif
#include <pcap.h> // for libpcap/WinPcap calls
#include "fmtutils.h"
#include "sockutils.h" // for socket calls
#include "portability.h"
#include "rpcap-protocol.h"
#include "daemon.h"
#include "log.h"
//
// Timeout, in seconds, when we're waiting for a client to send us an
// authentication request; if they don't send us a request within that
// interval, we drop the connection, so we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_INIT 90
//
// Timeout, in seconds, when we're waiting for an authenticated client
// to send us a request, if a capture isn't in progress; if they don't
// send us a request within that interval, we drop the connection, so
// we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_RUNTIME 180
//
// Time, in seconds, that we wait after a failed authentication attempt
// before processing the next request; this prevents a client from
// rapidly trying different accounts or passwords.
//
#define RPCAP_SUSPEND_WRONGAUTH 1
// Parameters for the service loop.
struct daemon_slpars
{
SOCKET sockctrl; //!< SOCKET ID of the control connection
int isactive; //!< Not null if the daemon has to run in active mode
int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
};
//
// Data for a session managed by a thread.
// It includes both a Boolean indicating whether we *have* a thread,
// and a platform-dependent (UN*X vs. Windows) identifier for the
// thread; on Windows, we could use an invalid handle to indicate
// that we don't have a thread, but there *is* no portable "no thread"
// value for a pthread_t on UN*X.
//
struct session {
SOCKET sockctrl;
SOCKET sockdata;
uint8 protocol_version;
pcap_t *fp;
unsigned int TotCapt;
int have_thread;
#ifdef _WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
};
// Locally defined functions
static int daemon_msg_err(SOCKET sockctrl, uint32 plen);
static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen);
static int daemon_AuthUserPwd(char *username, char *password, char *errbuf);
static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen);
static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, size_t sourcelen);
static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, struct session **sessionp,
struct rpcap_sampling *samp_param);
static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session);
static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen);
static int daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errbuf);
static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt);
static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, struct rpcap_sampling *samp_param);
static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout);
#ifdef _WIN32
static unsigned __stdcall daemon_thrdatamain(void *ptr);
#else
static void *daemon_thrdatamain(void *ptr);
static void noop_handler(int sign);
#endif
static int rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp);
static int rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf);
static int rpcapd_discard(SOCKET sock, uint32 len);
static void session_close(struct session *);
int
daemon_serviceloop(SOCKET sockctrl, int isactive, char *passiveClients,
int nullAuthAllowed)
{
struct daemon_slpars pars; // service loop parameters
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client
int host_port_check_status;
int nrecv;
struct rpcap_header header; // RPCAP message general header
uint32 plen; // payload length from header
int authenticated = 0; // 1 if the client has successfully authenticated
char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open
int got_source = 0; // 1 if we've gotten the source from an open request
#ifndef _WIN32
struct sigaction action;
#endif
struct session *session = NULL; // struct session main variable
const char *msg_type_string; // string for message type
int client_told_us_to_close = 0; // 1 if the client told us to close the capture
// needed to save the values of the statistics
struct pcap_stat stats;
unsigned int svrcapt;
struct rpcap_sampling samp_param; // in case sampling has been requested
// Structures needed for the select() call
fd_set rfds; // set of socket descriptors we have to check
struct timeval tv; // maximum time the select() can block waiting for data
int retval; // select() return value
*errbuf = 0; // Initialize errbuf
// Set parameters structure
pars.sockctrl = sockctrl;
pars.isactive = isactive; // active mode
pars.nullAuthAllowed = nullAuthAllowed;
//
// We have a connection.
//
// If it's a passive mode connection, check whether the connecting
// host is among the ones allowed.
//
// In either case, we were handed a copy of the host list; free it
// as soon as we're done with it.
//
if (pars.isactive)
{
// Nothing to do.
free(passiveClients);
passiveClients = NULL;
}
else
{
struct sockaddr_storage from;
socklen_t fromlen;
//
// Get the address of the other end of the connection.
//
fromlen = sizeof(struct sockaddr_storage);
if (getpeername(pars.sockctrl, (struct sockaddr *)&from,
&fromlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
//
// Are they in the list of host/port combinations we allow?
//
host_port_check_status = sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE);
free(passiveClients);
passiveClients = NULL;
if (host_port_check_status < 0)
{
if (host_port_check_status == -2) {
//
// We got an error; log it.
//
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
//
// Sorry, we can't let you in.
//
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
#ifndef _WIN32
//
// Catch SIGUSR1, but do nothing. We use it to interrupt the
// capture thread to break it out of a loop in which it's
// blocked waiting for packets to arrive.
//
// We don't want interrupted system calls to restart, so that
// the read routine for the pcap_t gets EINTR rather than
// restarting if it's blocked in a system call.
//
memset(&action, 0, sizeof (action));
action.sa_handler = noop_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
#endif
//
// The client must first authenticate; loop until they send us a
// message with a version we support and credentials we accept,
// they send us a close message indicating that they're giving up,
// or we get a network error or other fatal error.
//
while (!authenticated)
{
//
// If we're not in active mode, we use select(), with a
// timeout, to wait for an authentication request; if
// the timeout expires, we drop the connection, so that
// a client can't just connect to us and leave us
// waiting forever.
//
if (!pars.isactive)
{
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_INIT;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// While we're in the authentication pharse, all requests
// must use version 0.
//
if (header.ver != 0)
{
//
// Send it back to them with their version.
//
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGVER,
"RPCAP version in requests in the authentication phase must be 0",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message and drop the
// connection.
(void)rpcapd_discard(pars.sockctrl, plen);
goto end;
}
switch (header.type)
{
case RPCAP_MSG_AUTH_REQ:
retval = daemon_msg_auth_req(&pars, plen);
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
if (retval == -2)
{
// Non-fatal error; we sent back
// an error message, so let them
// try again.
continue;
}
// OK, we're authenticated; we sent back
// a reply, so start serving requests.
authenticated = 1;
break;
case RPCAP_MSG_CLOSE:
//
// The client is giving up.
// Discard the rest of the message, if
// there is anything more.
//
(void)rpcapd_discard(pars.sockctrl, plen);
// We're done with this client.
goto end;
case RPCAP_MSG_ERROR:
// Log this and close the connection?
// XXX - is this what happens in active
// mode, where *we* initiate the
// connection, and the client gives us
// an error message rather than a "let
// me log in" message, indicating that
// we're not allowed to connect to them?
(void)daemon_msg_err(pars.sockctrl, plen);
goto end;
case RPCAP_MSG_FINDALLIF_REQ:
case RPCAP_MSG_OPEN_REQ:
case RPCAP_MSG_STARTCAP_REQ:
case RPCAP_MSG_UPDATEFILTER_REQ:
case RPCAP_MSG_STATS_REQ:
case RPCAP_MSG_ENDCAP_REQ:
case RPCAP_MSG_SETSAMPLING_REQ:
//
// These requests can't be sent until
// the client is authenticated.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Network error.
goto end;
}
break;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
default:
//
// Unknown message type.
//
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
}
}
//
// OK, the client has authenticated itself, and we can start
// processing regular requests from it.
//
//
// We don't have any statistics yet.
//
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
//
// Service requests.
//
for (;;)
{
errbuf[0] = 0; // clear errbuf
// Avoid zombies connections; check if the connection is opens but no commands are performed
// from more than RPCAP_TIMEOUT_RUNTIME
// Conditions:
// - I have to be in normal mode (no active mode)
// - if the device is open, I don't have to be in the middle of a capture (session->sockdata)
// - if the device is closed, I have always to check if a new command arrives
//
// Be carefully: the capture can have been started, but an error occurred (so session != NULL, but
// sockdata is 0
if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0))))
{
// Check for the initial timeout
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_RUNTIME;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_INITTIMEOUT,
"The RPCAP initial timeout has expired",
errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// Did the client specify a protocol version that we
// support?
//
if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
{
//
// Tell them it's not a supported version.
// Send the error message with their version,
// so they don't reject it as having the wrong
// version.
//
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_WRONGVER,
"RPCAP version in message isn't supported by the server",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
(void)rpcapd_discard(pars.sockctrl, plen);
// Give up on them.
goto end;
}
switch (header.type)
{
case RPCAP_MSG_ERROR: // The other endpoint reported an error
{
(void)daemon_msg_err(pars.sockctrl, plen);
// Do nothing; just exit; the error code is already into the errbuf
// XXX - actually exit....
break;
}
case RPCAP_MSG_FINDALLIF_REQ:
{
if (daemon_msg_findallif_req(header.ver, &pars, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_OPEN_REQ:
{
//
// Process the open request, and keep
// the source from it, for use later
// when the capture is started.
//
// XXX - we don't care if the client sends
// us multiple open requests, the last
// one wins.
//
retval = daemon_msg_open_req(header.ver, &pars,
plen, source, sizeof(source));
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
got_source = 1;
break;
}
case RPCAP_MSG_STARTCAP_REQ:
{
if (!got_source)
{
// They never told us what device
// to capture on!
if (rpcap_senderror(pars.sockctrl,
header.ver,
PCAP_ERR_STARTCAPTURE,
"No capture device was specified",
errbuf) == -1)
{
// Fatal error; log an
// error and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
goto end;
}
break;
}
if (daemon_msg_startcap_req(header.ver, &pars,
plen, source, &session, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_UPDATEFILTER_REQ:
{
if (session)
{
if (daemon_msg_updatefilter_req(header.ver,
&pars, session, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
}
else
{
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_UPDATEFILTER,
"Device not opened. Cannot update filter",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
break;
}
case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session
{
//
// Indicate to our caller that the client
// closed the control connection.
// This is used only in case of active mode.
//
client_told_us_to_close = 1;
rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection.");
goto end;
}
case RPCAP_MSG_STATS_REQ:
{
if (daemon_msg_stats_req(header.ver, &pars,
session, plen, &stats, svrcapt) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session
{
if (session)
{
// Save statistics (we can need them in the future)
if (pcap_stats(session->fp, &stats))
{
svrcapt = session->TotCapt;
}
else
{
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
}
if (daemon_msg_endcap_req(header.ver,
&pars, session) == -1)
{
free(session);
session = NULL;
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
free(session);
session = NULL;
}
else
{
rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_ENDCAPTURE,
"Device not opened. Cannot close the capture",
errbuf);
}
break;
}
case RPCAP_MSG_SETSAMPLING_REQ:
{
if (daemon_msg_setsampling_req(header.ver,
&pars, plen, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_AUTH_REQ:
{
//
// We're already authenticated; you don't
// get to reauthenticate.
//
rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed");
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG,
"RPCAP_MSG_AUTH_REQ request sent after authentication was completed",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
default:
//
// Unknown message type.
//
rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errbuf, errmsgbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
}
}
}
end:
// The service loop is finishing up.
// If we have a capture session running, close it.
if (session)
{
session_close(session);
free(session);
session = NULL;
}
sock_close(sockctrl, NULL, 0);
// Print message and return
rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop");
return client_told_us_to_close;
}
/*
* This handles the RPCAP_MSG_ERR message.
*/
static int
daemon_msg_err(SOCKET sockctrl, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char remote_errbuf[PCAP_ERRBUF_SIZE];
if (plen >= PCAP_ERRBUF_SIZE)
{
/*
* Message is too long; just read as much of it as we
* can into the buffer provided, and discard the rest.
*/
if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1)
{
// Network error.
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
}
else if (plen == 0)
{
/* Empty error string. */
remote_errbuf[0] = '\0';
}
else
{
if (sock_recv(sockctrl, remote_errbuf, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[plen] = '\0';
}
// Log the message
rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf);
return 0;
}
/*
* This handles the RPCAP_MSG_AUTH_REQ message.
* It checks if the authentication credentials supplied by the user are valid.
*
* This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ
* message in its authentication loop. It reads the body of the
* authentication message from the network and checks whether the
* credentials are valid.
*
* \param sockctrl: the socket for the control connection.
*
* \param nullAuthAllowed: '1' if the NULL authentication is allowed.
*
* \param errbuf: a user-allocated buffer in which the error message
* (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE
* bytes long.
*
* \return '0' if everything is fine, '-1' if an unrecoverable error occurred,
* or '-2' if the authentication failed. For errors, an error message is
* returned in the 'errbuf' variable; this gives a message for the
* unrecoverable error or for the authentication failure.
*/
static int
daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int status;
struct rpcap_auth auth; // RPCAP authentication header
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_authreply *authreply; // authentication reply message
status = rpcapd_recv(pars->sockctrl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
switch (ntohs(auth.type))
{
case RPCAP_RMTAUTH_NULL:
{
if (!pars->nullAuthAllowed)
{
// Send the client an error reply.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication failed; NULL authentication not permitted.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
break;
}
case RPCAP_RMTAUTH_PWD:
{
char *username, *passwd;
uint32 usernamelen, passwdlen;
usernamelen = ntohs(auth.slen1);
username = (char *) malloc (usernamelen + 1);
if (username == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
goto error;
}
status = rpcapd_recv(pars->sockctrl, username, usernamelen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
return -1;
}
if (status == -2)
{
free(username);
goto error;
}
username[usernamelen] = '\0';
passwdlen = ntohs(auth.slen2);
passwd = (char *) malloc (passwdlen + 1);
if (passwd == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
free(username);
goto error;
}
status = rpcapd_recv(pars->sockctrl, passwd, passwdlen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
free(passwd);
return -1;
}
if (status == -2)
{
free(username);
free(passwd);
goto error;
}
passwd[passwdlen] = '\0';
if (daemon_AuthUserPwd(username, passwd, errmsgbuf))
{
//
// Authentication failed. Let the client
// know.
//
free(username);
free(passwd);
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
//
// Suspend for 1 second, so that they can't
// hammer us with repeated tries with an
// attack such as a dictionary attack.
//
// WARNING: this delay is inserted only
// at this point; if the client closes the
// connection and reconnects, the suspension
// time does not have any effect.
//
sleep_secs(RPCAP_SUSPEND_WRONGAUTH);
goto error_noreply;
}
free(username);
free(passwd);
break;
}
default:
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication type not recognized.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_TYPE_NOTSUP, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
// The authentication succeeded; let the client know.
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
RPCAP_MSG_AUTH_REPLY, 0, sizeof(struct rpcap_authreply));
authreply = (struct rpcap_authreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_authreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
//
// Indicate to our peer what versions we support.
//
memset(authreply, 0, sizeof(struct rpcap_authreply));
authreply->minvers = RPCAP_MIN_VERSION;
authreply->maxvers = RPCAP_MAX_VERSION;
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH, errmsgbuf,
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
error_noreply:
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return -2;
}
static int
daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
HANDLE Token;
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "LogonUser() failed");
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
if (setuid(user->pw_uid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setuid");
return -1;
}
/* if (setgid(user->pw_gid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
return -1;
}
*/
return 0;
#endif
}
static int
daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint16 nif = 0; // counts the number of interface listed
// Discard the rest of the message; there shouldn't be any payload.
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// Retrieve the device list
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
// checks the number of interfaces and it computes the total length of the payload
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
plen+= strlen(d->description);
if (d->name)
plen+= strlen(d->name);
plen+= sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
plen+= (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
// RPCAP findalldevs command
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
// send the interface list
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
// send all addresses
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
// We no longer need the device list. Free it.
pcap_freealldevs(alldevs);
// Send a final command that says "now send it!"
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, size_t sourcelen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
pcap_t *fp; // pcap_t main variable
int nread;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_openreply *openreply; // open reply message
if (plen > sourcelen - 1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
goto error;
}
nread = sock_recv(pars->sockctrl, source, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
source[nread] = '\0';
plen -= nread;
// XXX - make sure it's *not* a URL; we don't support opening
// remote devices here.
// Open the selected device
// This is a fake open, since we do that only to get the needed parameters, then we close the device again
if ((fp = pcap_open_live(source,
1500 /* fake snaplen */,
0 /* no promis */,
1000 /* fake timeout */,
errmsgbuf)) == NULL)
goto error;
// Now, I can send a RPCAP open reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(openreply, 0, sizeof(struct rpcap_openreply));
openreply->linktype = htonl(pcap_datalink(fp));
openreply->tzoff = 0; /* This is always 0 for live captures */
// We're done with the pcap_t.
pcap_close(fp);
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, struct session **sessionp,
struct rpcap_sampling *samp_param _U_)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
struct session *session = NULL; // saves state of session
int status;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
// socket-related variables
struct addrinfo hints; // temp, needed to open a socket connection
struct addrinfo *addrinfo; // temp, needed to open a socket connection
struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
int ret; // return value from functions
// RPCAP-related variables
struct rpcap_startcapreq startcapreq; // start capture request message
struct rpcap_startcapreply *startcapreply; // start capture reply message
int serveropen_dp; // keeps who is going to open the data connection
addrinfo = NULL;
status = rpcapd_recv(pars->sockctrl, (char *) &startcapreq,
sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
if (status == -1)
{
goto fatal_error;
}
if (status == -2)
{
goto error;
}
startcapreq.flags = ntohs(startcapreq.flags);
// Create a session structure
session = malloc(sizeof(struct session));
if (session == NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
goto error;
}
session->sockdata = INVALID_SOCKET;
// We don't have a thread yet.
session->have_thread = 0;
//
// We *shouldn't* have to initialize the thread indicator
// itself, because the compiler *should* realize that we
// only use this if have_thread isn't 0, but we *do* have
// to do it, because not all compilers *do* realize that.
//
// There is no "invalid thread handle" value for a UN*X
// pthread_t, so we just zero it out.
//
#ifdef _WIN32
session->thread = INVALID_HANDLE_VALUE;
#else
memset(&session->thread, 0, sizeof(session->thread));
#endif
// Open the selected device
if ((session->fp = pcap_open_live(source,
ntohl(startcapreq.snaplen),
(startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
ntohl(startcapreq.read_timeout),
errmsgbuf)) == NULL)
goto error;
#if 0
// Apply sampling parameters
fp->rmt_samp.method = samp_param->method;
fp->rmt_samp.value = samp_param->value;
#endif
/*
We're in active mode if:
- we're using TCP, and the user wants us to be in active mode
- we're using UDP
*/
serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
/*
Gets the sockaddr structure referred to the other peer in the ctrl connection
We need that because:
- if we're in passive mode, we need to know the address family we want to use
(the same used for the ctrl socket)
- if we're in active mode, we need to know the network address of the other host
we want to connect to
*/
saddrlen = sizeof(struct sockaddr_storage);
if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_family = saddr.ss_family;
// Now we have to create a new socket to send packets
if (serveropen_dp) // Data connection is opened by the server toward the client
{
pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
// Get the name of the other peer (needed to connect to that specific network address)
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
}
else // Data connection is opened by the client toward the server
{
hints.ai_flags = AI_PASSIVE;
// Let's the server socket pick up a free network port for us
if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
// get the complete sockaddr structure used in the data connection
saddrlen = sizeof(struct sockaddr_storage);
if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getsockname()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
// Get the local port the system picked up
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
0, portdata, sizeof(portdata), NI_NUMERICSERV))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
}
// addrinfo is no longer used
freeaddrinfo(addrinfo);
addrinfo = NULL;
// Needed to send an error on the ctrl connection
session->sockctrl = pars->sockctrl;
session->protocol_version = ver;
// Now I can set the filter
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
goto fatal_error;
}
if (ret == -2)
{
// Non-fatal error. Send an error message to the client.
goto error;
}
// Now, I can send a RPCAP start capture reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
if (!serveropen_dp)
{
unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
startcapreply->portdata = htons(port);
}
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto fatal_error;
}
if (!serveropen_dp)
{
SOCKET socktemp; // We need another socket, since we're going to accept() a connection
// Connection creation
saddrlen = sizeof(struct sockaddr_storage);
socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen);
if (socktemp == INVALID_SOCKET)
{
sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
errbuf);
goto error;
}
// Now that I accepted the connection, the server socket is no longer needed
sock_close(session->sockdata, NULL, 0);
session->sockdata = socktemp;
}
// Now we have to create a new thread to receive packets
#ifdef _WIN32
session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
(void *) session, 0, NULL);
if (session->thread == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
goto error;
}
#else
ret = pthread_create(&session->thread, NULL, daemon_thrdatamain,
(void *) session);
if (ret != 0)
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
ret, "Error creating the data thread");
goto error;
}
#endif
session->have_thread = 1;
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
goto fatal_error;
*sessionp = session;
return 0;
error:
//
// Not a fatal error, so send the client an error message and
// keep serving client requests.
//
*sessionp = NULL;
if (addrinfo)
freeaddrinfo(addrinfo);
if (session)
{
session_close(session);
free(session);
}
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_STARTCAPTURE,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
return 0;
fatal_error:
//
// Fatal network error, so don't try to communicate with
// the client, just give up.
//
*sessionp = NULL;
if (session)
{
session_close(session);
free(session);
}
return -1;
}
static int
daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
struct rpcap_header header;
session_close(session);
rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
static int
daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errmsgbuf)
{
int status;
struct rpcap_filter filter;
struct rpcap_filterbpf_insn insn;
struct bpf_insn *bf_insn;
struct bpf_program bf_prog;
unsigned int i;
status = rpcapd_recv(sockctrl, (char *) &filter,
sizeof(struct rpcap_filter), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_prog.bf_len = ntohl(filter.nitems);
if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
return -2;
}
bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
if (bf_insn == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
errno, "malloc() failed");
return -2;
}
bf_prog.bf_insns = bf_insn;
for (i = 0; i < bf_prog.bf_len; i++)
{
status = rpcapd_recv(sockctrl, (char *) &insn,
sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_insn->code = ntohs(insn.code);
bf_insn->jf = insn.jf;
bf_insn->jt = insn.jt;
bf_insn->k = ntohl(insn.k);
bf_insn++;
}
if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
return -2;
}
if (pcap_setfilter(session->fp, &bf_prog))
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
return -2;
}
return 0;
}
static int
daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int ret; // status of daemon_unpackapplyfilter()
struct rpcap_header header; // keeps the answer to the updatefilter command
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
return -1;
}
if (ret == -2)
{
// Non-fatal error. Send an error reply to the client.
goto error;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_UPDATEFILTER,
errmsgbuf, NULL);
return 0;
}
/*!
\brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
*/
static int
daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
struct rpcap_sampling *samp_param)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE];
struct rpcap_header header;
struct rpcap_sampling rpcap_samp;
int status;
status = rpcapd_recv(pars->sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
// Save these settings in the pcap_t
samp_param->method = rpcap_samp.method;
samp_param->value = ntohl(rpcap_samp.value);
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_SETSAMPLING,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
static int
daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_stats *netstats; // statistics sent on the network
// Checks that the header does not contain other data; if so, discard it
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if (session && session->fp)
{
if (pcap_stats(session->fp, stats) == -1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
goto error;
}
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(session->TotCapt);
}
else
{
// We have to keep compatibility with old applications,
// which ask for statistics also when the capture has
// already stopped.
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(svrcapt);
}
// Send the packet
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_GETSTATS,
errmsgbuf, NULL);
return 0;
}
#ifdef _WIN32
static unsigned __stdcall
#else
static void *
#endif
daemon_thrdatamain(void *ptr)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
struct session *session; // pointer to the struct session for this session
int retval; // general variable used to keep the return value of other functions
struct rpcap_pkthdr *net_pkt_header;// header of the packet
struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
u_char *pkt_data; // pointer to the buffer that contains the current packet
size_t sendbufsize; // size for the send buffer
char *sendbuf; // temporary buffer in which data to be sent is buffered
int sendbufidx; // index which keeps the number of bytes currently buffered
int status;
#ifndef _WIN32
sigset_t sigusr1; // signal set with just SIGUSR1
#endif
session = (struct session *) ptr;
session->TotCapt = 0; // counter which is incremented each time a packet is received
// Initialize errbuf
memset(errbuf, 0, sizeof(errbuf));
//
// We need a buffer large enough to hold a buffer large enough
// for a maximum-size packet for this pcap_t.
//
if (pcap_snapshot(session->fp) < 0)
{
//
// The snapshot length is negative.
// This "should not happen".
//
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
pcap_snapshot(session->fp));
sendbuf = NULL; // we can't allocate a buffer, so nothing to free
goto error;
}
//
// size_t is unsigned, and the result of pcap_snapshot() is signed;
// on no platform that we support is int larger than size_t.
// This means that, unless the extra information we prepend to
// a maximum-sized packet is impossibly large, the sum of the
// snapshot length and the size of that extra information will
// fit in a size_t.
//
// So we don't need to make sure that sendbufsize will overflow.
//
sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
sendbuf = (char *) malloc (sendbufsize);
if (sendbuf == NULL)
{
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread");
goto error;
}
#ifndef _WIN32
//
// Set the signal set to include just SIGUSR1, and block that
// signal; we only want it unblocked when we're reading
// packets - we dn't want any other system calls, such as
// ones being used to send to the client or to log messages,
// to be interrupted.
//
sigemptyset(&sigusr1);
sigaddset(&sigusr1, SIGUSR1);
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
// Retrieve the packets
for (;;)
{
#ifndef _WIN32
//
// Unblock SIGUSR1 while we might be waiting for packets.
//
pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL);
#endif
retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning
#ifndef _WIN32
//
// Now block it again.
//
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
if (retval < 0)
break; // error
if (retval == 0) // Read timeout elapsed
continue;
sendbufidx = 0;
// Bufferize the general header
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
rpcap_createhdr((struct rpcap_header *) sendbuf,
session->protocol_version, RPCAP_MSG_PACKET, 0,
(uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
// Bufferize the pkt header
if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
net_pkt_header->caplen = htonl(pkt_header->caplen);
net_pkt_header->len = htonl(pkt_header->len);
net_pkt_header->npkt = htonl(++(session->TotCapt));
net_pkt_header->timestamp_sec = htonl(pkt_header->ts.tv_sec);
net_pkt_header->timestamp_usec = htonl(pkt_header->ts.tv_usec);
// Bufferize the pkt data
if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
sendbuf, &sendbufidx, sendbufsize, SOCKBUF_BUFFERIZE,
errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
// Send the packet
// If the client dropped the connection, don't report an
// error, just quit.
status = sock_send(session->sockdata, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
if (status < 0)
{
if (status == -1)
{
//
// Error other than "client closed the
// connection out from under us"; report
// it.
//
rpcapd_log(LOGPRIO_ERROR,
"Send of packet to client failed: %s",
errbuf);
}
//
// Give up in either case.
//
goto error;
}
}
if (retval < 0 && retval != PCAP_ERROR_BREAK)
{
//
// Failed with an error other than "we were told to break
// out of the loop".
//
// The latter just means that the client told us to stop
// capturing, so there's no error to report.
//
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
rpcap_senderror(session->sockctrl, session->protocol_version,
PCAP_ERR_READEX, errbuf, NULL);
}
error:
//
// The main thread will clean up the session structure.
//
free(sendbuf);
return 0;
}
#ifndef _WIN32
//
// Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to
// interrupt the data thread if it's blocked in a system call waiting
// for packets to arrive.
//
static void noop_handler(int sign _U_)
{
}
#endif
/*!
\brief It serializes a network address.
It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
that can be used to be sent on the network. Basically, it applies all the hton()
conversion required to the input variable.
\param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
\param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
the serialized data. This variable has to be allocated by the user.
\warning This function supports only AF_INET and AF_INET6 address families.
*/
static void
daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
{
memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
// There can be the case in which the sockaddrin is not available
if (sockaddrin == NULL) return;
// Warning: we support only AF_INET and AF_INET6
switch (sockaddrin->ss_family)
{
case AF_INET:
{
struct sockaddr_in *sockaddrin_ipv4;
struct rpcap_sockaddr_in *sockaddrout_ipv4;
sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
break;
}
#ifdef AF_INET6
case AF_INET6:
{
struct sockaddr_in6 *sockaddrin_ipv6;
struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
break;
}
#endif
}
}
/*!
\brief Suspends a thread for secs seconds.
*/
void sleep_secs(int secs)
{
#ifdef _WIN32
Sleep(secs*1000);
#else
unsigned secs_remaining;
if (secs <= 0)
return;
secs_remaining = secs;
while (secs_remaining != 0)
secs_remaining = sleep(secs_remaining);
#endif
}
/*
* Read the header of a message.
*/
static int
rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
nread = sock_recv(sock, (char *) headerp, sizeof(struct rpcap_header),
SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (nread == 0)
{
// Immediate EOF; that's treated like a close message.
return -2;
}
headerp->plen = ntohl(headerp->plen);
return 0;
}
/*
* Read data from a message.
* If we're trying to read more data that remains, puts an error
* message into errmsgbuf and returns -2. Otherwise, tries to read
* the data and, if that succeeds, subtracts the amount read from
* the number of bytes of data that remains.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
if (toread > *plen)
{
// Tell the client and continue.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
return -2;
}
nread = sock_recv(sock, buffer, toread,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
*plen -= nread;
return 0;
}
/*
* Discard data from a connection.
* Mostly used to discard wrong-sized messages.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_discard(SOCKET sock, uint32 len)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
if (len != 0)
{
if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
}
return 0;
}
//
// Shut down any packet-capture thread associated with the session,
// close the SSL handle for the data socket if we have one, close
// the data socket if we have one, and close the underlying packet
// capture handle if we have one.
//
// We do not, of course, touch the controlling socket that's also
// copied into the session, as the service loop might still use it.
//
static void session_close(struct session *session)
{
if (session->have_thread)
{
//
// Tell the data connection thread main capture loop to
// break out of that loop.
//
// This may be sufficient to wake up a blocked thread,
// but it's not guaranteed to be sufficient.
//
pcap_breakloop(session->fp);
#ifdef _WIN32
//
// Set the event on which a read would block, so that,
// if it's currently blocked waiting for packets to
// arrive, it'll wake up, so it can see the "break
// out of the loop" indication. (pcap_breakloop()
// might do this, but older versions don't. Setting
// it twice should, at worst, cause an extra wakeup,
// which shouldn't be a problem.)
//
// XXX - what about modules other than NPF?
//
SetEvent(pcap_getevent(session->fp));
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
WaitForSingleObject(session->thread, INFINITE);
//
// Release the thread handle, as we're done with
// it.
//
CloseHandle(session->thread);
session->have_thread = 0;
session->thread = INVALID_HANDLE_VALUE;
#else
//
// Send a SIGUSR1 signal to the thread, so that, if
// it's currently blocked waiting for packets to arrive,
// it'll wake up (we've turned off SA_RESTART for
// SIGUSR1, so that the system call in which it's blocked
// should return EINTR rather than restarting).
//
pthread_kill(session->thread, SIGUSR1);
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
pthread_join(session->thread, NULL);
session->have_thread = 0;
memset(&session->thread, 0, sizeof(session->thread));
#endif
}
if (session->sockdata != INVALID_SOCKET)
{
sock_close(session->sockdata, NULL, 0);
session->sockdata = INVALID_SOCKET;
}
if (session->fp)
{
pcap_close(session->fp);
session->fp = NULL;
}
}
| ./CrossVul/dataset_final_sorted/CWE-345/c/bad_1023_0 |
crossvul-cpp_data_good_1023_0 | /*
* Copyright (c) 2002 - 2003
* NetGroup, Politecnico di Torino (Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "ftmacros.h"
#include "varattrs.h"
#include <errno.h> // for the errno variable
#include <stdlib.h> // for malloc(), free(), ...
#include <string.h> // for strlen(), ...
#ifdef _WIN32
#include <process.h> // for threads
#else
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h> // for select() and such
#include <pwd.h> // for password management
#endif
#ifdef HAVE_GETSPNAM
#include <shadow.h> // for password management
#endif
#include <pcap.h> // for libpcap/WinPcap calls
#include "fmtutils.h"
#include "sockutils.h" // for socket calls
#include "portability.h"
#include "rpcap-protocol.h"
#include "daemon.h"
#include "log.h"
//
// Timeout, in seconds, when we're waiting for a client to send us an
// authentication request; if they don't send us a request within that
// interval, we drop the connection, so we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_INIT 90
//
// Timeout, in seconds, when we're waiting for an authenticated client
// to send us a request, if a capture isn't in progress; if they don't
// send us a request within that interval, we drop the connection, so
// we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_RUNTIME 180
//
// Time, in seconds, that we wait after a failed authentication attempt
// before processing the next request; this prevents a client from
// rapidly trying different accounts or passwords.
//
#define RPCAP_SUSPEND_WRONGAUTH 1
// Parameters for the service loop.
struct daemon_slpars
{
SOCKET sockctrl; //!< SOCKET ID of the control connection
int isactive; //!< Not null if the daemon has to run in active mode
int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
};
//
// Data for a session managed by a thread.
// It includes both a Boolean indicating whether we *have* a thread,
// and a platform-dependent (UN*X vs. Windows) identifier for the
// thread; on Windows, we could use an invalid handle to indicate
// that we don't have a thread, but there *is* no portable "no thread"
// value for a pthread_t on UN*X.
//
struct session {
SOCKET sockctrl;
SOCKET sockdata;
uint8 protocol_version;
pcap_t *fp;
unsigned int TotCapt;
int have_thread;
#ifdef _WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
};
// Locally defined functions
static int daemon_msg_err(SOCKET sockctrl, uint32 plen);
static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen);
static int daemon_AuthUserPwd(char *username, char *password, char *errbuf);
static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen);
static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, size_t sourcelen);
static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, struct session **sessionp,
struct rpcap_sampling *samp_param);
static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session);
static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen);
static int daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errbuf);
static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt);
static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, struct rpcap_sampling *samp_param);
static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout);
#ifdef _WIN32
static unsigned __stdcall daemon_thrdatamain(void *ptr);
#else
static void *daemon_thrdatamain(void *ptr);
static void noop_handler(int sign);
#endif
static int rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp);
static int rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf);
static int rpcapd_discard(SOCKET sock, uint32 len);
static void session_close(struct session *);
int
daemon_serviceloop(SOCKET sockctrl, int isactive, char *passiveClients,
int nullAuthAllowed)
{
struct daemon_slpars pars; // service loop parameters
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client
int host_port_check_status;
int nrecv;
struct rpcap_header header; // RPCAP message general header
uint32 plen; // payload length from header
int authenticated = 0; // 1 if the client has successfully authenticated
char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open
int got_source = 0; // 1 if we've gotten the source from an open request
#ifndef _WIN32
struct sigaction action;
#endif
struct session *session = NULL; // struct session main variable
const char *msg_type_string; // string for message type
int client_told_us_to_close = 0; // 1 if the client told us to close the capture
// needed to save the values of the statistics
struct pcap_stat stats;
unsigned int svrcapt;
struct rpcap_sampling samp_param; // in case sampling has been requested
// Structures needed for the select() call
fd_set rfds; // set of socket descriptors we have to check
struct timeval tv; // maximum time the select() can block waiting for data
int retval; // select() return value
*errbuf = 0; // Initialize errbuf
// Set parameters structure
pars.sockctrl = sockctrl;
pars.isactive = isactive; // active mode
pars.nullAuthAllowed = nullAuthAllowed;
//
// We have a connection.
//
// If it's a passive mode connection, check whether the connecting
// host is among the ones allowed.
//
// In either case, we were handed a copy of the host list; free it
// as soon as we're done with it.
//
if (pars.isactive)
{
// Nothing to do.
free(passiveClients);
passiveClients = NULL;
}
else
{
struct sockaddr_storage from;
socklen_t fromlen;
//
// Get the address of the other end of the connection.
//
fromlen = sizeof(struct sockaddr_storage);
if (getpeername(pars.sockctrl, (struct sockaddr *)&from,
&fromlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
//
// Are they in the list of host/port combinations we allow?
//
host_port_check_status = sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE);
free(passiveClients);
passiveClients = NULL;
if (host_port_check_status < 0)
{
if (host_port_check_status == -2) {
//
// We got an error; log it.
//
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
//
// Sorry, we can't let you in.
//
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
#ifndef _WIN32
//
// Catch SIGUSR1, but do nothing. We use it to interrupt the
// capture thread to break it out of a loop in which it's
// blocked waiting for packets to arrive.
//
// We don't want interrupted system calls to restart, so that
// the read routine for the pcap_t gets EINTR rather than
// restarting if it's blocked in a system call.
//
memset(&action, 0, sizeof (action));
action.sa_handler = noop_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
#endif
//
// The client must first authenticate; loop until they send us a
// message with a version we support and credentials we accept,
// they send us a close message indicating that they're giving up,
// or we get a network error or other fatal error.
//
while (!authenticated)
{
//
// If we're not in active mode, we use select(), with a
// timeout, to wait for an authentication request; if
// the timeout expires, we drop the connection, so that
// a client can't just connect to us and leave us
// waiting forever.
//
if (!pars.isactive)
{
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_INIT;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// While we're in the authentication pharse, all requests
// must use version 0.
//
if (header.ver != 0)
{
//
// Send it back to them with their version.
//
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGVER,
"RPCAP version in requests in the authentication phase must be 0",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message and drop the
// connection.
(void)rpcapd_discard(pars.sockctrl, plen);
goto end;
}
switch (header.type)
{
case RPCAP_MSG_AUTH_REQ:
retval = daemon_msg_auth_req(&pars, plen);
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
if (retval == -2)
{
// Non-fatal error; we sent back
// an error message, so let them
// try again.
continue;
}
// OK, we're authenticated; we sent back
// a reply, so start serving requests.
authenticated = 1;
break;
case RPCAP_MSG_CLOSE:
//
// The client is giving up.
// Discard the rest of the message, if
// there is anything more.
//
(void)rpcapd_discard(pars.sockctrl, plen);
// We're done with this client.
goto end;
case RPCAP_MSG_ERROR:
// Log this and close the connection?
// XXX - is this what happens in active
// mode, where *we* initiate the
// connection, and the client gives us
// an error message rather than a "let
// me log in" message, indicating that
// we're not allowed to connect to them?
(void)daemon_msg_err(pars.sockctrl, plen);
goto end;
case RPCAP_MSG_FINDALLIF_REQ:
case RPCAP_MSG_OPEN_REQ:
case RPCAP_MSG_STARTCAP_REQ:
case RPCAP_MSG_UPDATEFILTER_REQ:
case RPCAP_MSG_STATS_REQ:
case RPCAP_MSG_ENDCAP_REQ:
case RPCAP_MSG_SETSAMPLING_REQ:
//
// These requests can't be sent until
// the client is authenticated.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Network error.
goto end;
}
break;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
default:
//
// Unknown message type.
//
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
}
}
//
// OK, the client has authenticated itself, and we can start
// processing regular requests from it.
//
//
// We don't have any statistics yet.
//
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
//
// Service requests.
//
for (;;)
{
errbuf[0] = 0; // clear errbuf
// Avoid zombies connections; check if the connection is opens but no commands are performed
// from more than RPCAP_TIMEOUT_RUNTIME
// Conditions:
// - I have to be in normal mode (no active mode)
// - if the device is open, I don't have to be in the middle of a capture (session->sockdata)
// - if the device is closed, I have always to check if a new command arrives
//
// Be carefully: the capture can have been started, but an error occurred (so session != NULL, but
// sockdata is 0
if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0))))
{
// Check for the initial timeout
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_RUNTIME;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_INITTIMEOUT,
"The RPCAP initial timeout has expired",
errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// Did the client specify a protocol version that we
// support?
//
if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
{
//
// Tell them it's not a supported version.
// Send the error message with their version,
// so they don't reject it as having the wrong
// version.
//
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_WRONGVER,
"RPCAP version in message isn't supported by the server",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
(void)rpcapd_discard(pars.sockctrl, plen);
// Give up on them.
goto end;
}
switch (header.type)
{
case RPCAP_MSG_ERROR: // The other endpoint reported an error
{
(void)daemon_msg_err(pars.sockctrl, plen);
// Do nothing; just exit; the error code is already into the errbuf
// XXX - actually exit....
break;
}
case RPCAP_MSG_FINDALLIF_REQ:
{
if (daemon_msg_findallif_req(header.ver, &pars, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_OPEN_REQ:
{
//
// Process the open request, and keep
// the source from it, for use later
// when the capture is started.
//
// XXX - we don't care if the client sends
// us multiple open requests, the last
// one wins.
//
retval = daemon_msg_open_req(header.ver, &pars,
plen, source, sizeof(source));
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
got_source = 1;
break;
}
case RPCAP_MSG_STARTCAP_REQ:
{
if (!got_source)
{
// They never told us what device
// to capture on!
if (rpcap_senderror(pars.sockctrl,
header.ver,
PCAP_ERR_STARTCAPTURE,
"No capture device was specified",
errbuf) == -1)
{
// Fatal error; log an
// error and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
goto end;
}
break;
}
if (daemon_msg_startcap_req(header.ver, &pars,
plen, source, &session, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_UPDATEFILTER_REQ:
{
if (session)
{
if (daemon_msg_updatefilter_req(header.ver,
&pars, session, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
}
else
{
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_UPDATEFILTER,
"Device not opened. Cannot update filter",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
break;
}
case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session
{
//
// Indicate to our caller that the client
// closed the control connection.
// This is used only in case of active mode.
//
client_told_us_to_close = 1;
rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection.");
goto end;
}
case RPCAP_MSG_STATS_REQ:
{
if (daemon_msg_stats_req(header.ver, &pars,
session, plen, &stats, svrcapt) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session
{
if (session)
{
// Save statistics (we can need them in the future)
if (pcap_stats(session->fp, &stats))
{
svrcapt = session->TotCapt;
}
else
{
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
}
if (daemon_msg_endcap_req(header.ver,
&pars, session) == -1)
{
free(session);
session = NULL;
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
free(session);
session = NULL;
}
else
{
rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_ENDCAPTURE,
"Device not opened. Cannot close the capture",
errbuf);
}
break;
}
case RPCAP_MSG_SETSAMPLING_REQ:
{
if (daemon_msg_setsampling_req(header.ver,
&pars, plen, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_AUTH_REQ:
{
//
// We're already authenticated; you don't
// get to reauthenticate.
//
rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed");
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG,
"RPCAP_MSG_AUTH_REQ request sent after authentication was completed",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
default:
//
// Unknown message type.
//
rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errbuf, errmsgbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
}
}
}
end:
// The service loop is finishing up.
// If we have a capture session running, close it.
if (session)
{
session_close(session);
free(session);
session = NULL;
}
sock_close(sockctrl, NULL, 0);
// Print message and return
rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop");
return client_told_us_to_close;
}
/*
* This handles the RPCAP_MSG_ERR message.
*/
static int
daemon_msg_err(SOCKET sockctrl, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char remote_errbuf[PCAP_ERRBUF_SIZE];
if (plen >= PCAP_ERRBUF_SIZE)
{
/*
* Message is too long; just read as much of it as we
* can into the buffer provided, and discard the rest.
*/
if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1)
{
// Network error.
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
}
else if (plen == 0)
{
/* Empty error string. */
remote_errbuf[0] = '\0';
}
else
{
if (sock_recv(sockctrl, remote_errbuf, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[plen] = '\0';
}
// Log the message
rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf);
return 0;
}
/*
* This handles the RPCAP_MSG_AUTH_REQ message.
* It checks if the authentication credentials supplied by the user are valid.
*
* This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ
* message in its authentication loop. It reads the body of the
* authentication message from the network and checks whether the
* credentials are valid.
*
* \param sockctrl: the socket for the control connection.
*
* \param nullAuthAllowed: '1' if the NULL authentication is allowed.
*
* \param errbuf: a user-allocated buffer in which the error message
* (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE
* bytes long.
*
* \return '0' if everything is fine, '-1' if an unrecoverable error occurred,
* or '-2' if the authentication failed. For errors, an error message is
* returned in the 'errbuf' variable; this gives a message for the
* unrecoverable error or for the authentication failure.
*/
static int
daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int status;
struct rpcap_auth auth; // RPCAP authentication header
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_authreply *authreply; // authentication reply message
status = rpcapd_recv(pars->sockctrl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
switch (ntohs(auth.type))
{
case RPCAP_RMTAUTH_NULL:
{
if (!pars->nullAuthAllowed)
{
// Send the client an error reply.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication failed; NULL authentication not permitted.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
break;
}
case RPCAP_RMTAUTH_PWD:
{
char *username, *passwd;
uint32 usernamelen, passwdlen;
usernamelen = ntohs(auth.slen1);
username = (char *) malloc (usernamelen + 1);
if (username == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
goto error;
}
status = rpcapd_recv(pars->sockctrl, username, usernamelen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
return -1;
}
if (status == -2)
{
free(username);
goto error;
}
username[usernamelen] = '\0';
passwdlen = ntohs(auth.slen2);
passwd = (char *) malloc (passwdlen + 1);
if (passwd == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
free(username);
goto error;
}
status = rpcapd_recv(pars->sockctrl, passwd, passwdlen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
free(passwd);
return -1;
}
if (status == -2)
{
free(username);
free(passwd);
goto error;
}
passwd[passwdlen] = '\0';
if (daemon_AuthUserPwd(username, passwd, errmsgbuf))
{
//
// Authentication failed. Let the client
// know.
//
free(username);
free(passwd);
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
//
// Suspend for 1 second, so that they can't
// hammer us with repeated tries with an
// attack such as a dictionary attack.
//
// WARNING: this delay is inserted only
// at this point; if the client closes the
// connection and reconnects, the suspension
// time does not have any effect.
//
sleep_secs(RPCAP_SUSPEND_WRONGAUTH);
goto error_noreply;
}
free(username);
free(passwd);
break;
}
default:
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication type not recognized.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_TYPE_NOTSUP, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
// The authentication succeeded; let the client know.
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
RPCAP_MSG_AUTH_REPLY, 0, sizeof(struct rpcap_authreply));
authreply = (struct rpcap_authreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_authreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
//
// Indicate to our peer what versions we support.
//
memset(authreply, 0, sizeof(struct rpcap_authreply));
authreply->minvers = RPCAP_MIN_VERSION;
authreply->maxvers = RPCAP_MAX_VERSION;
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH, errmsgbuf,
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
error_noreply:
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return -2;
}
static int
daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
DWORD error;
HANDLE Token;
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to log
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
error = GetLastError();
if (error != ERROR_LOGON_FAILURE)
{
// Some error other than an authentication error;
// log it.
pcap_fmt_errmsg_for_win32_err(errmsgbuf,
PCAP_ERRBUF_SIZE, error, "LogonUser() failed");
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
pcap_fmt_errmsg_for_win32_err(errmsgbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
int error;
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
//
// The Single UNIX Specification says that if crypt() fails it
// sets errno, but some implementatons that haven't been run
// through the SUS test suite might not do so.
//
errno = 0;
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
error = errno;
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
if (error == 0)
{
// It didn't set errno.
rpcapd_log(LOGPRIO_ERROR, "crypt() failed");
}
else
{
rpcapd_log(LOGPRIO_ERROR, "crypt() failed: %s",
strerror(error));
}
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (setuid(user->pw_uid))
{
error = errno;
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
error, "setuid");
rpcapd_log(LOGPRIO_ERROR, "setuid() failed: %s",
strerror(error));
return -1;
}
/* if (setgid(user->pw_gid))
{
error = errno;
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
rpcapd_log(LOGPRIO_ERROR, "setgid() failed: %s",
strerror(error));
return -1;
}
*/
return 0;
#endif
}
static int
daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint16 nif = 0; // counts the number of interface listed
// Discard the rest of the message; there shouldn't be any payload.
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// Retrieve the device list
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
// checks the number of interfaces and it computes the total length of the payload
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
plen+= strlen(d->description);
if (d->name)
plen+= strlen(d->name);
plen+= sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
plen+= (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
// RPCAP findalldevs command
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
// send the interface list
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
// send all addresses
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
// We no longer need the device list. Free it.
pcap_freealldevs(alldevs);
// Send a final command that says "now send it!"
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, size_t sourcelen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
pcap_t *fp; // pcap_t main variable
int nread;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_openreply *openreply; // open reply message
if (plen > sourcelen - 1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
goto error;
}
nread = sock_recv(pars->sockctrl, source, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
source[nread] = '\0';
plen -= nread;
// XXX - make sure it's *not* a URL; we don't support opening
// remote devices here.
// Open the selected device
// This is a fake open, since we do that only to get the needed parameters, then we close the device again
if ((fp = pcap_open_live(source,
1500 /* fake snaplen */,
0 /* no promis */,
1000 /* fake timeout */,
errmsgbuf)) == NULL)
goto error;
// Now, I can send a RPCAP open reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(openreply, 0, sizeof(struct rpcap_openreply));
openreply->linktype = htonl(pcap_datalink(fp));
openreply->tzoff = 0; /* This is always 0 for live captures */
// We're done with the pcap_t.
pcap_close(fp);
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, struct session **sessionp,
struct rpcap_sampling *samp_param _U_)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
struct session *session = NULL; // saves state of session
int status;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
// socket-related variables
struct addrinfo hints; // temp, needed to open a socket connection
struct addrinfo *addrinfo; // temp, needed to open a socket connection
struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
int ret; // return value from functions
// RPCAP-related variables
struct rpcap_startcapreq startcapreq; // start capture request message
struct rpcap_startcapreply *startcapreply; // start capture reply message
int serveropen_dp; // keeps who is going to open the data connection
addrinfo = NULL;
status = rpcapd_recv(pars->sockctrl, (char *) &startcapreq,
sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
if (status == -1)
{
goto fatal_error;
}
if (status == -2)
{
goto error;
}
startcapreq.flags = ntohs(startcapreq.flags);
// Create a session structure
session = malloc(sizeof(struct session));
if (session == NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
goto error;
}
session->sockdata = INVALID_SOCKET;
// We don't have a thread yet.
session->have_thread = 0;
//
// We *shouldn't* have to initialize the thread indicator
// itself, because the compiler *should* realize that we
// only use this if have_thread isn't 0, but we *do* have
// to do it, because not all compilers *do* realize that.
//
// There is no "invalid thread handle" value for a UN*X
// pthread_t, so we just zero it out.
//
#ifdef _WIN32
session->thread = INVALID_HANDLE_VALUE;
#else
memset(&session->thread, 0, sizeof(session->thread));
#endif
// Open the selected device
if ((session->fp = pcap_open_live(source,
ntohl(startcapreq.snaplen),
(startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
ntohl(startcapreq.read_timeout),
errmsgbuf)) == NULL)
goto error;
#if 0
// Apply sampling parameters
fp->rmt_samp.method = samp_param->method;
fp->rmt_samp.value = samp_param->value;
#endif
/*
We're in active mode if:
- we're using TCP, and the user wants us to be in active mode
- we're using UDP
*/
serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
/*
Gets the sockaddr structure referred to the other peer in the ctrl connection
We need that because:
- if we're in passive mode, we need to know the address family we want to use
(the same used for the ctrl socket)
- if we're in active mode, we need to know the network address of the other host
we want to connect to
*/
saddrlen = sizeof(struct sockaddr_storage);
if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_family = saddr.ss_family;
// Now we have to create a new socket to send packets
if (serveropen_dp) // Data connection is opened by the server toward the client
{
pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
// Get the name of the other peer (needed to connect to that specific network address)
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
}
else // Data connection is opened by the client toward the server
{
hints.ai_flags = AI_PASSIVE;
// Let's the server socket pick up a free network port for us
if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
// get the complete sockaddr structure used in the data connection
saddrlen = sizeof(struct sockaddr_storage);
if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getsockname()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
// Get the local port the system picked up
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
0, portdata, sizeof(portdata), NI_NUMERICSERV))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
}
// addrinfo is no longer used
freeaddrinfo(addrinfo);
addrinfo = NULL;
// Needed to send an error on the ctrl connection
session->sockctrl = pars->sockctrl;
session->protocol_version = ver;
// Now I can set the filter
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
goto fatal_error;
}
if (ret == -2)
{
// Non-fatal error. Send an error message to the client.
goto error;
}
// Now, I can send a RPCAP start capture reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
if (!serveropen_dp)
{
unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
startcapreply->portdata = htons(port);
}
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto fatal_error;
}
if (!serveropen_dp)
{
SOCKET socktemp; // We need another socket, since we're going to accept() a connection
// Connection creation
saddrlen = sizeof(struct sockaddr_storage);
socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen);
if (socktemp == INVALID_SOCKET)
{
sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
errbuf);
goto error;
}
// Now that I accepted the connection, the server socket is no longer needed
sock_close(session->sockdata, NULL, 0);
session->sockdata = socktemp;
}
// Now we have to create a new thread to receive packets
#ifdef _WIN32
session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
(void *) session, 0, NULL);
if (session->thread == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
goto error;
}
#else
ret = pthread_create(&session->thread, NULL, daemon_thrdatamain,
(void *) session);
if (ret != 0)
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
ret, "Error creating the data thread");
goto error;
}
#endif
session->have_thread = 1;
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
goto fatal_error;
*sessionp = session;
return 0;
error:
//
// Not a fatal error, so send the client an error message and
// keep serving client requests.
//
*sessionp = NULL;
if (addrinfo)
freeaddrinfo(addrinfo);
if (session)
{
session_close(session);
free(session);
}
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_STARTCAPTURE,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
return 0;
fatal_error:
//
// Fatal network error, so don't try to communicate with
// the client, just give up.
//
*sessionp = NULL;
if (session)
{
session_close(session);
free(session);
}
return -1;
}
static int
daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
struct rpcap_header header;
session_close(session);
rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
static int
daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errmsgbuf)
{
int status;
struct rpcap_filter filter;
struct rpcap_filterbpf_insn insn;
struct bpf_insn *bf_insn;
struct bpf_program bf_prog;
unsigned int i;
status = rpcapd_recv(sockctrl, (char *) &filter,
sizeof(struct rpcap_filter), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_prog.bf_len = ntohl(filter.nitems);
if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
return -2;
}
bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
if (bf_insn == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
errno, "malloc() failed");
return -2;
}
bf_prog.bf_insns = bf_insn;
for (i = 0; i < bf_prog.bf_len; i++)
{
status = rpcapd_recv(sockctrl, (char *) &insn,
sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_insn->code = ntohs(insn.code);
bf_insn->jf = insn.jf;
bf_insn->jt = insn.jt;
bf_insn->k = ntohl(insn.k);
bf_insn++;
}
if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
return -2;
}
if (pcap_setfilter(session->fp, &bf_prog))
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
return -2;
}
return 0;
}
static int
daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int ret; // status of daemon_unpackapplyfilter()
struct rpcap_header header; // keeps the answer to the updatefilter command
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
return -1;
}
if (ret == -2)
{
// Non-fatal error. Send an error reply to the client.
goto error;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_UPDATEFILTER,
errmsgbuf, NULL);
return 0;
}
/*!
\brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
*/
static int
daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
struct rpcap_sampling *samp_param)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE];
struct rpcap_header header;
struct rpcap_sampling rpcap_samp;
int status;
status = rpcapd_recv(pars->sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
// Save these settings in the pcap_t
samp_param->method = rpcap_samp.method;
samp_param->value = ntohl(rpcap_samp.value);
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_SETSAMPLING,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
static int
daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_stats *netstats; // statistics sent on the network
// Checks that the header does not contain other data; if so, discard it
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if (session && session->fp)
{
if (pcap_stats(session->fp, stats) == -1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
goto error;
}
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(session->TotCapt);
}
else
{
// We have to keep compatibility with old applications,
// which ask for statistics also when the capture has
// already stopped.
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(svrcapt);
}
// Send the packet
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_GETSTATS,
errmsgbuf, NULL);
return 0;
}
#ifdef _WIN32
static unsigned __stdcall
#else
static void *
#endif
daemon_thrdatamain(void *ptr)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
struct session *session; // pointer to the struct session for this session
int retval; // general variable used to keep the return value of other functions
struct rpcap_pkthdr *net_pkt_header;// header of the packet
struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
u_char *pkt_data; // pointer to the buffer that contains the current packet
size_t sendbufsize; // size for the send buffer
char *sendbuf; // temporary buffer in which data to be sent is buffered
int sendbufidx; // index which keeps the number of bytes currently buffered
int status;
#ifndef _WIN32
sigset_t sigusr1; // signal set with just SIGUSR1
#endif
session = (struct session *) ptr;
session->TotCapt = 0; // counter which is incremented each time a packet is received
// Initialize errbuf
memset(errbuf, 0, sizeof(errbuf));
//
// We need a buffer large enough to hold a buffer large enough
// for a maximum-size packet for this pcap_t.
//
if (pcap_snapshot(session->fp) < 0)
{
//
// The snapshot length is negative.
// This "should not happen".
//
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
pcap_snapshot(session->fp));
sendbuf = NULL; // we can't allocate a buffer, so nothing to free
goto error;
}
//
// size_t is unsigned, and the result of pcap_snapshot() is signed;
// on no platform that we support is int larger than size_t.
// This means that, unless the extra information we prepend to
// a maximum-sized packet is impossibly large, the sum of the
// snapshot length and the size of that extra information will
// fit in a size_t.
//
// So we don't need to make sure that sendbufsize will overflow.
//
sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
sendbuf = (char *) malloc (sendbufsize);
if (sendbuf == NULL)
{
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread");
goto error;
}
#ifndef _WIN32
//
// Set the signal set to include just SIGUSR1, and block that
// signal; we only want it unblocked when we're reading
// packets - we dn't want any other system calls, such as
// ones being used to send to the client or to log messages,
// to be interrupted.
//
sigemptyset(&sigusr1);
sigaddset(&sigusr1, SIGUSR1);
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
// Retrieve the packets
for (;;)
{
#ifndef _WIN32
//
// Unblock SIGUSR1 while we might be waiting for packets.
//
pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL);
#endif
retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning
#ifndef _WIN32
//
// Now block it again.
//
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
if (retval < 0)
break; // error
if (retval == 0) // Read timeout elapsed
continue;
sendbufidx = 0;
// Bufferize the general header
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
rpcap_createhdr((struct rpcap_header *) sendbuf,
session->protocol_version, RPCAP_MSG_PACKET, 0,
(uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
// Bufferize the pkt header
if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
net_pkt_header->caplen = htonl(pkt_header->caplen);
net_pkt_header->len = htonl(pkt_header->len);
net_pkt_header->npkt = htonl(++(session->TotCapt));
net_pkt_header->timestamp_sec = htonl(pkt_header->ts.tv_sec);
net_pkt_header->timestamp_usec = htonl(pkt_header->ts.tv_usec);
// Bufferize the pkt data
if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
sendbuf, &sendbufidx, sendbufsize, SOCKBUF_BUFFERIZE,
errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
// Send the packet
// If the client dropped the connection, don't report an
// error, just quit.
status = sock_send(session->sockdata, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
if (status < 0)
{
if (status == -1)
{
//
// Error other than "client closed the
// connection out from under us"; report
// it.
//
rpcapd_log(LOGPRIO_ERROR,
"Send of packet to client failed: %s",
errbuf);
}
//
// Give up in either case.
//
goto error;
}
}
if (retval < 0 && retval != PCAP_ERROR_BREAK)
{
//
// Failed with an error other than "we were told to break
// out of the loop".
//
// The latter just means that the client told us to stop
// capturing, so there's no error to report.
//
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
rpcap_senderror(session->sockctrl, session->protocol_version,
PCAP_ERR_READEX, errbuf, NULL);
}
error:
//
// The main thread will clean up the session structure.
//
free(sendbuf);
return 0;
}
#ifndef _WIN32
//
// Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to
// interrupt the data thread if it's blocked in a system call waiting
// for packets to arrive.
//
static void noop_handler(int sign _U_)
{
}
#endif
/*!
\brief It serializes a network address.
It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
that can be used to be sent on the network. Basically, it applies all the hton()
conversion required to the input variable.
\param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
\param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
the serialized data. This variable has to be allocated by the user.
\warning This function supports only AF_INET and AF_INET6 address families.
*/
static void
daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
{
memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
// There can be the case in which the sockaddrin is not available
if (sockaddrin == NULL) return;
// Warning: we support only AF_INET and AF_INET6
switch (sockaddrin->ss_family)
{
case AF_INET:
{
struct sockaddr_in *sockaddrin_ipv4;
struct rpcap_sockaddr_in *sockaddrout_ipv4;
sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
break;
}
#ifdef AF_INET6
case AF_INET6:
{
struct sockaddr_in6 *sockaddrin_ipv6;
struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
break;
}
#endif
}
}
/*!
\brief Suspends a thread for secs seconds.
*/
void sleep_secs(int secs)
{
#ifdef _WIN32
Sleep(secs*1000);
#else
unsigned secs_remaining;
if (secs <= 0)
return;
secs_remaining = secs;
while (secs_remaining != 0)
secs_remaining = sleep(secs_remaining);
#endif
}
/*
* Read the header of a message.
*/
static int
rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
nread = sock_recv(sock, (char *) headerp, sizeof(struct rpcap_header),
SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (nread == 0)
{
// Immediate EOF; that's treated like a close message.
return -2;
}
headerp->plen = ntohl(headerp->plen);
return 0;
}
/*
* Read data from a message.
* If we're trying to read more data that remains, puts an error
* message into errmsgbuf and returns -2. Otherwise, tries to read
* the data and, if that succeeds, subtracts the amount read from
* the number of bytes of data that remains.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
if (toread > *plen)
{
// Tell the client and continue.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
return -2;
}
nread = sock_recv(sock, buffer, toread,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
*plen -= nread;
return 0;
}
/*
* Discard data from a connection.
* Mostly used to discard wrong-sized messages.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_discard(SOCKET sock, uint32 len)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
if (len != 0)
{
if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
}
return 0;
}
//
// Shut down any packet-capture thread associated with the session,
// close the SSL handle for the data socket if we have one, close
// the data socket if we have one, and close the underlying packet
// capture handle if we have one.
//
// We do not, of course, touch the controlling socket that's also
// copied into the session, as the service loop might still use it.
//
static void session_close(struct session *session)
{
if (session->have_thread)
{
//
// Tell the data connection thread main capture loop to
// break out of that loop.
//
// This may be sufficient to wake up a blocked thread,
// but it's not guaranteed to be sufficient.
//
pcap_breakloop(session->fp);
#ifdef _WIN32
//
// Set the event on which a read would block, so that,
// if it's currently blocked waiting for packets to
// arrive, it'll wake up, so it can see the "break
// out of the loop" indication. (pcap_breakloop()
// might do this, but older versions don't. Setting
// it twice should, at worst, cause an extra wakeup,
// which shouldn't be a problem.)
//
// XXX - what about modules other than NPF?
//
SetEvent(pcap_getevent(session->fp));
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
WaitForSingleObject(session->thread, INFINITE);
//
// Release the thread handle, as we're done with
// it.
//
CloseHandle(session->thread);
session->have_thread = 0;
session->thread = INVALID_HANDLE_VALUE;
#else
//
// Send a SIGUSR1 signal to the thread, so that, if
// it's currently blocked waiting for packets to arrive,
// it'll wake up (we've turned off SA_RESTART for
// SIGUSR1, so that the system call in which it's blocked
// should return EINTR rather than restarting).
//
pthread_kill(session->thread, SIGUSR1);
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
pthread_join(session->thread, NULL);
session->have_thread = 0;
memset(&session->thread, 0, sizeof(session->thread));
#endif
}
if (session->sockdata != INVALID_SOCKET)
{
sock_close(session->sockdata, NULL, 0);
session->sockdata = INVALID_SOCKET;
}
if (session->fp)
{
pcap_close(session->fp);
session->fp = NULL;
}
}
| ./CrossVul/dataset_final_sorted/CWE-345/c/good_1023_0 |
crossvul-cpp_data_bad_2369_0 | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/math.h>
#include <base/system.h>
#include <engine/config.h>
#include <engine/console.h>
#include <engine/engine.h>
#include <engine/map.h>
#include <engine/masterserver.h>
#include <engine/server.h>
#include <engine/storage.h>
#include <engine/shared/compression.h>
#include <engine/shared/config.h>
#include <engine/shared/datafile.h>
#include <engine/shared/demo.h>
#include <engine/shared/econ.h>
#include <engine/shared/filecollection.h>
#include <engine/shared/mapchecker.h>
#include <engine/shared/netban.h>
#include <engine/shared/network.h>
#include <engine/shared/packer.h>
#include <engine/shared/protocol.h>
#include <engine/shared/snapshot.h>
#include <mastersrv/mastersrv.h>
#include "register.h"
#include "server.h"
#if defined(CONF_FAMILY_WINDOWS)
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
static const char *StrLtrim(const char *pStr)
{
while(*pStr && *pStr >= 0 && *pStr <= 32)
pStr++;
return pStr;
}
static void StrRtrim(char *pStr)
{
int i = str_length(pStr);
while(i >= 0)
{
if(pStr[i] < 0 || pStr[i] > 32)
break;
pStr[i] = 0;
i--;
}
}
CSnapIDPool::CSnapIDPool()
{
Reset();
}
void CSnapIDPool::Reset()
{
for(int i = 0; i < MAX_IDS; i++)
{
m_aIDs[i].m_Next = i+1;
m_aIDs[i].m_State = 0;
}
m_aIDs[MAX_IDS-1].m_Next = -1;
m_FirstFree = 0;
m_FirstTimed = -1;
m_LastTimed = -1;
m_Usage = 0;
m_InUsage = 0;
}
void CSnapIDPool::RemoveFirstTimeout()
{
int NextTimed = m_aIDs[m_FirstTimed].m_Next;
// add it to the free list
m_aIDs[m_FirstTimed].m_Next = m_FirstFree;
m_aIDs[m_FirstTimed].m_State = 0;
m_FirstFree = m_FirstTimed;
// remove it from the timed list
m_FirstTimed = NextTimed;
if(m_FirstTimed == -1)
m_LastTimed = -1;
m_Usage--;
}
int CSnapIDPool::NewID()
{
int64 Now = time_get();
// process timed ids
while(m_FirstTimed != -1 && m_aIDs[m_FirstTimed].m_Timeout < Now)
RemoveFirstTimeout();
int ID = m_FirstFree;
dbg_assert(ID != -1, "id error");
if(ID == -1)
return ID;
m_FirstFree = m_aIDs[m_FirstFree].m_Next;
m_aIDs[ID].m_State = 1;
m_Usage++;
m_InUsage++;
return ID;
}
void CSnapIDPool::TimeoutIDs()
{
// process timed ids
while(m_FirstTimed != -1)
RemoveFirstTimeout();
}
void CSnapIDPool::FreeID(int ID)
{
if(ID < 0)
return;
dbg_assert(m_aIDs[ID].m_State == 1, "id is not alloced");
m_InUsage--;
m_aIDs[ID].m_State = 2;
m_aIDs[ID].m_Timeout = time_get()+time_freq()*5;
m_aIDs[ID].m_Next = -1;
if(m_LastTimed != -1)
{
m_aIDs[m_LastTimed].m_Next = ID;
m_LastTimed = ID;
}
else
{
m_FirstTimed = ID;
m_LastTimed = ID;
}
}
void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer* pServer)
{
CNetBan::Init(pConsole, pStorage);
m_pServer = pServer;
// overwrites base command, todo: improve this
Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason");
}
template<class T>
int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)
{
// validate address
if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS &&
Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
{
if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID)))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)");
return -1;
}
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
continue;
if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
return -1;
}
}
}
else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE)
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
continue;
if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
return -1;
}
}
}
int Result = Ban(pBanPool, pData, Seconds, pReason);
if(Result != 0)
return Result;
// drop banned clients
typename T::CDataType Data = *pData;
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
continue;
if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i)))
{
CNetHash NetHash(&Data);
char aBuf[256];
MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER);
Server()->m_NetServer.Drop(i, aBuf);
}
}
return Result;
}
int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)
{
return BanExt(&m_BanAddrPool, pAddr, Seconds, pReason);
}
int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
{
if(pRange->IsValid())
return BanExt(&m_BanRangePool, pRange, Seconds, pReason);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
return -1;
}
void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser)
{
CServerBan *pThis = static_cast<CServerBan *>(pUser);
const char *pStr = pResult->GetString(0);
int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30;
const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given";
if(StrAllnum(pStr))
{
int ClientID = str_toint(pStr);
if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)");
else
pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason);
}
else
ConBan(pResult, pUser);
}
void CServer::CClient::Reset()
{
// reset input
for(int i = 0; i < 200; i++)
m_aInputs[i].m_GameTick = -1;
m_CurrentInput = 0;
mem_zero(&m_LatestInput, sizeof(m_LatestInput));
m_Snapshots.PurgeAll();
m_LastAckedSnapshot = -1;
m_LastInputTick = -1;
m_SnapRate = CClient::SNAPRATE_INIT;
m_Score = 0;
}
CServer::CServer() : m_DemoRecorder(&m_SnapshotDelta)
{
m_TickSpeed = SERVER_TICK_SPEED;
m_pGameServer = 0;
m_CurrentGameTick = 0;
m_RunServer = 1;
m_pCurrentMapData = 0;
m_CurrentMapSize = 0;
m_MapReload = 0;
m_RconClientID = IServer::RCON_CID_SERV;
m_RconAuthLevel = AUTHED_ADMIN;
Init();
}
int CServer::TrySetClientName(int ClientID, const char *pName)
{
char aTrimmedName[64];
// trim the name
str_copy(aTrimmedName, StrLtrim(pName), sizeof(aTrimmedName));
StrRtrim(aTrimmedName);
// check for empty names
if(!aTrimmedName[0])
return -1;
// check if new and old name are the same
if(m_aClients[ClientID].m_aName[0] && str_comp(m_aClients[ClientID].m_aName, aTrimmedName) == 0)
return 0;
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "'%s' -> '%s'", pName, aTrimmedName);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
pName = aTrimmedName;
// make sure that two clients doesn't have the same name
for(int i = 0; i < MAX_CLIENTS; i++)
if(i != ClientID && m_aClients[i].m_State >= CClient::STATE_READY)
{
if(str_comp(pName, m_aClients[i].m_aName) == 0)
return -1;
}
// set the client name
str_copy(m_aClients[ClientID].m_aName, pName, MAX_NAME_LENGTH);
return 0;
}
void CServer::SetClientName(int ClientID, const char *pName)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)
return;
if(!pName)
return;
char aCleanName[MAX_NAME_LENGTH];
str_copy(aCleanName, pName, sizeof(aCleanName));
// clear name
for(char *p = aCleanName; *p; ++p)
{
if(*p < 32)
*p = ' ';
}
if(TrySetClientName(ClientID, aCleanName))
{
// auto rename
for(int i = 1;; i++)
{
char aNameTry[MAX_NAME_LENGTH];
str_format(aNameTry, sizeof(aCleanName), "(%d)%s", i, aCleanName);
if(TrySetClientName(ClientID, aNameTry) == 0)
break;
}
}
}
void CServer::SetClientClan(int ClientID, const char *pClan)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pClan)
return;
str_copy(m_aClients[ClientID].m_aClan, pClan, MAX_CLAN_LENGTH);
}
void CServer::SetClientCountry(int ClientID, int Country)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)
return;
m_aClients[ClientID].m_Country = Country;
}
void CServer::SetClientScore(int ClientID, int Score)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)
return;
m_aClients[ClientID].m_Score = Score;
}
void CServer::Kick(int ClientID, const char *pReason)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY)
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client id to kick");
return;
}
else if(m_RconClientID == ClientID)
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't kick yourself");
return;
}
else if(m_aClients[ClientID].m_Authed > m_RconAuthLevel)
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "kick command denied");
return;
}
m_NetServer.Drop(ClientID, pReason);
}
/*int CServer::Tick()
{
return m_CurrentGameTick;
}*/
int64 CServer::TickStartTime(int Tick)
{
return m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED;
}
/*int CServer::TickSpeed()
{
return SERVER_TICK_SPEED;
}*/
int CServer::Init()
{
for(int i = 0; i < MAX_CLIENTS; i++)
{
m_aClients[i].m_State = CClient::STATE_EMPTY;
m_aClients[i].m_aName[0] = 0;
m_aClients[i].m_aClan[0] = 0;
m_aClients[i].m_Country = -1;
m_aClients[i].m_Snapshots.Init();
}
m_CurrentGameTick = 0;
return 0;
}
void CServer::SetRconCID(int ClientID)
{
m_RconClientID = ClientID;
}
bool CServer::IsAuthed(int ClientID)
{
return m_aClients[ClientID].m_Authed;
}
int CServer::GetClientInfo(int ClientID, CClientInfo *pInfo)
{
dbg_assert(ClientID >= 0 && ClientID < MAX_CLIENTS, "client_id is not valid");
dbg_assert(pInfo != 0, "info can not be null");
if(m_aClients[ClientID].m_State == CClient::STATE_INGAME)
{
pInfo->m_pName = m_aClients[ClientID].m_aName;
pInfo->m_Latency = m_aClients[ClientID].m_Latency;
return 1;
}
return 0;
}
void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size)
{
if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME)
net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false);
}
const char *CServer::ClientName(int ClientID)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
return "(invalid)";
if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)
return m_aClients[ClientID].m_aName;
else
return "(connecting)";
}
const char *CServer::ClientClan(int ClientID)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
return "";
if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)
return m_aClients[ClientID].m_aClan;
else
return "";
}
int CServer::ClientCountry(int ClientID)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
return -1;
if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)
return m_aClients[ClientID].m_Country;
else
return -1;
}
bool CServer::ClientIngame(int ClientID)
{
return ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME;
}
int CServer::MaxClients() const
{
return m_NetServer.MaxClients();
}
int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)
{
return SendMsgEx(pMsg, Flags, ClientID, false);
}
int CServer::SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System)
{
CNetChunk Packet;
if(!pMsg)
return -1;
mem_zero(&Packet, sizeof(CNetChunk));
Packet.m_ClientID = ClientID;
Packet.m_pData = pMsg->Data();
Packet.m_DataSize = pMsg->Size();
// HACK: modify the message id in the packet and store the system flag
*((unsigned char*)Packet.m_pData) <<= 1;
if(System)
*((unsigned char*)Packet.m_pData) |= 1;
if(Flags&MSGFLAG_VITAL)
Packet.m_Flags |= NETSENDFLAG_VITAL;
if(Flags&MSGFLAG_FLUSH)
Packet.m_Flags |= NETSENDFLAG_FLUSH;
// write message to demo recorder
if(!(Flags&MSGFLAG_NORECORD))
m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());
if(!(Flags&MSGFLAG_NOSEND))
{
if(ClientID == -1)
{
// broadcast
int i;
for(i = 0; i < MAX_CLIENTS; i++)
if(m_aClients[i].m_State == CClient::STATE_INGAME)
{
Packet.m_ClientID = i;
m_NetServer.Send(&Packet);
}
}
else
m_NetServer.Send(&Packet);
}
return 0;
}
void CServer::DoSnapshot()
{
GameServer()->OnPreSnap();
// create snapshot for demo recording
if(m_DemoRecorder.IsRecording())
{
char aData[CSnapshot::MAX_SIZE];
int SnapshotSize;
// build snap and possibly add some messages
m_SnapshotBuilder.Init();
GameServer()->OnSnap(-1);
SnapshotSize = m_SnapshotBuilder.Finish(aData);
// write snapshot
m_DemoRecorder.RecordSnapshot(Tick(), aData, SnapshotSize);
}
// create snapshots for all clients
for(int i = 0; i < MAX_CLIENTS; i++)
{
// client must be ingame to recive snapshots
if(m_aClients[i].m_State != CClient::STATE_INGAME)
continue;
// this client is trying to recover, don't spam snapshots
if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick()%50) != 0)
continue;
// this client is trying to recover, don't spam snapshots
if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0)
continue;
{
char aData[CSnapshot::MAX_SIZE];
CSnapshot *pData = (CSnapshot*)aData; // Fix compiler warning for strict-aliasing
char aDeltaData[CSnapshot::MAX_SIZE];
char aCompData[CSnapshot::MAX_SIZE];
int SnapshotSize;
int Crc;
static CSnapshot EmptySnap;
CSnapshot *pDeltashot = &EmptySnap;
int DeltashotSize;
int DeltaTick = -1;
int DeltaSize;
m_SnapshotBuilder.Init();
GameServer()->OnSnap(i);
// finish snapshot
SnapshotSize = m_SnapshotBuilder.Finish(pData);
Crc = pData->Crc();
// remove old snapshos
// keep 3 seconds worth of snapshots
m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3);
// save it the snapshot
m_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0);
// find snapshot that we can preform delta against
EmptySnap.Clear();
{
DeltashotSize = m_aClients[i].m_Snapshots.Get(m_aClients[i].m_LastAckedSnapshot, 0, &pDeltashot, 0);
if(DeltashotSize >= 0)
DeltaTick = m_aClients[i].m_LastAckedSnapshot;
else
{
// no acked package found, force client to recover rate
if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL)
m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER;
}
}
// create delta
DeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData);
if(DeltaSize)
{
// compress it
int SnapshotSize;
const int MaxSize = MAX_SNAPSHOT_PACKSIZE;
int NumPackets;
SnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData);
NumPackets = (SnapshotSize+MaxSize-1)/MaxSize;
for(int n = 0, Left = SnapshotSize; Left; n++)
{
int Chunk = Left < MaxSize ? Left : MaxSize;
Left -= Chunk;
if(NumPackets == 1)
{
CMsgPacker Msg(NETMSG_SNAPSINGLE);
Msg.AddInt(m_CurrentGameTick);
Msg.AddInt(m_CurrentGameTick-DeltaTick);
Msg.AddInt(Crc);
Msg.AddInt(Chunk);
Msg.AddRaw(&aCompData[n*MaxSize], Chunk);
SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true);
}
else
{
CMsgPacker Msg(NETMSG_SNAP);
Msg.AddInt(m_CurrentGameTick);
Msg.AddInt(m_CurrentGameTick-DeltaTick);
Msg.AddInt(NumPackets);
Msg.AddInt(n);
Msg.AddInt(Crc);
Msg.AddInt(Chunk);
Msg.AddRaw(&aCompData[n*MaxSize], Chunk);
SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true);
}
}
}
else
{
CMsgPacker Msg(NETMSG_SNAPEMPTY);
Msg.AddInt(m_CurrentGameTick);
Msg.AddInt(m_CurrentGameTick-DeltaTick);
SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true);
}
}
}
GameServer()->OnPostSnap();
}
int CServer::NewClientCallback(int ClientID, void *pUser)
{
CServer *pThis = (CServer *)pUser;
pThis->m_aClients[ClientID].m_State = CClient::STATE_AUTH;
pThis->m_aClients[ClientID].m_aName[0] = 0;
pThis->m_aClients[ClientID].m_aClan[0] = 0;
pThis->m_aClients[ClientID].m_Country = -1;
pThis->m_aClients[ClientID].m_Authed = AUTHED_NO;
pThis->m_aClients[ClientID].m_AuthTries = 0;
pThis->m_aClients[ClientID].m_pRconCmdToSend = 0;
pThis->m_aClients[ClientID].Reset();
return 0;
}
int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser)
{
CServer *pThis = (CServer *)pUser;
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason);
pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
// notify the mod about the drop
if(pThis->m_aClients[ClientID].m_State >= CClient::STATE_READY)
pThis->GameServer()->OnClientDrop(ClientID, pReason);
pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY;
pThis->m_aClients[ClientID].m_aName[0] = 0;
pThis->m_aClients[ClientID].m_aClan[0] = 0;
pThis->m_aClients[ClientID].m_Country = -1;
pThis->m_aClients[ClientID].m_Authed = AUTHED_NO;
pThis->m_aClients[ClientID].m_AuthTries = 0;
pThis->m_aClients[ClientID].m_pRconCmdToSend = 0;
pThis->m_aClients[ClientID].m_Snapshots.PurgeAll();
return 0;
}
void CServer::SendMap(int ClientID)
{
CMsgPacker Msg(NETMSG_MAP_CHANGE);
Msg.AddString(GetMapName(), 0);
Msg.AddInt(m_CurrentMapCrc);
Msg.AddInt(m_CurrentMapSize);
SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true);
}
void CServer::SendConnectionReady(int ClientID)
{
CMsgPacker Msg(NETMSG_CON_READY);
SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true);
}
void CServer::SendRconLine(int ClientID, const char *pLine)
{
CMsgPacker Msg(NETMSG_RCON_LINE);
Msg.AddString(pLine, 512);
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
}
void CServer::SendRconLineAuthed(const char *pLine, void *pUser)
{
CServer *pThis = (CServer *)pUser;
static volatile int ReentryGuard = 0;
int i;
if(ReentryGuard) return;
ReentryGuard++;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY && pThis->m_aClients[i].m_Authed >= pThis->m_RconAuthLevel)
pThis->SendRconLine(i, pLine);
}
ReentryGuard--;
}
void CServer::SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID)
{
CMsgPacker Msg(NETMSG_RCON_CMD_ADD);
Msg.AddString(pCommandInfo->m_pName, IConsole::TEMPCMD_NAME_LENGTH);
Msg.AddString(pCommandInfo->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH);
Msg.AddString(pCommandInfo->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH);
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
}
void CServer::SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID)
{
CMsgPacker Msg(NETMSG_RCON_CMD_REM);
Msg.AddString(pCommandInfo->m_pName, 256);
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
}
void CServer::UpdateClientRconCommands()
{
int ClientID = Tick() % MAX_CLIENTS;
if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed)
{
int ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD;
for(int i = 0; i < MAX_RCONCMD_SEND && m_aClients[ClientID].m_pRconCmdToSend; ++i)
{
SendRconCmdAdd(m_aClients[ClientID].m_pRconCmdToSend, ClientID);
m_aClients[ClientID].m_pRconCmdToSend = m_aClients[ClientID].m_pRconCmdToSend->NextCommandInfo(ConsoleAccessLevel, CFGFLAG_SERVER);
}
}
}
void CServer::ProcessClientPacket(CNetChunk *pPacket)
{
int ClientID = pPacket->m_ClientID;
CUnpacker Unpacker;
Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize);
// unpack msgid and system flag
int Msg = Unpacker.GetInt();
int Sys = Msg&1;
Msg >>= 1;
if(Unpacker.Error())
return;
if(Sys)
{
// system message
if(Msg == NETMSG_INFO)
{
if(m_aClients[ClientID].m_State == CClient::STATE_AUTH)
{
const char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC);
if(str_comp(pVersion, GameServer()->NetVersion()) != 0)
{
// wrong version
char aReason[256];
str_format(aReason, sizeof(aReason), "Wrong version. Server is running '%s' and client '%s'", GameServer()->NetVersion(), pVersion);
m_NetServer.Drop(ClientID, aReason);
return;
}
const char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC);
if(g_Config.m_Password[0] != 0 && str_comp(g_Config.m_Password, pPassword) != 0)
{
// wrong password
m_NetServer.Drop(ClientID, "Wrong password");
return;
}
m_aClients[ClientID].m_State = CClient::STATE_CONNECTING;
SendMap(ClientID);
}
}
else if(Msg == NETMSG_REQUEST_MAP_DATA)
{
if(m_aClients[ClientID].m_State < CClient::STATE_CONNECTING)
return;
int Chunk = Unpacker.GetInt();
int ChunkSize = 1024-128;
int Offset = Chunk * ChunkSize;
int Last = 0;
// drop faulty map data requests
if(Chunk < 0 || Offset > m_CurrentMapSize)
return;
if(Offset+ChunkSize >= m_CurrentMapSize)
{
ChunkSize = m_CurrentMapSize-Offset;
if(ChunkSize < 0)
ChunkSize = 0;
Last = 1;
}
CMsgPacker Msg(NETMSG_MAP_DATA);
Msg.AddInt(Last);
Msg.AddInt(m_CurrentMapCrc);
Msg.AddInt(Chunk);
Msg.AddInt(ChunkSize);
Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize);
SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true);
if(g_Config.m_Debug)
{
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "sending chunk %d with size %d", Chunk, ChunkSize);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf);
}
}
else if(Msg == NETMSG_READY)
{
if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING)
{
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%x addr=%s", ClientID, aAddrStr);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
m_aClients[ClientID].m_State = CClient::STATE_READY;
GameServer()->OnClientConnected(ClientID);
SendConnectionReady(ClientID);
}
}
else if(Msg == NETMSG_ENTERGAME)
{
if(m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID))
{
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%x addr=%s", ClientID, aAddrStr);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
m_aClients[ClientID].m_State = CClient::STATE_INGAME;
GameServer()->OnClientEnter(ClientID);
}
}
else if(Msg == NETMSG_INPUT)
{
CClient::CInput *pInput;
int64 TagTime;
m_aClients[ClientID].m_LastAckedSnapshot = Unpacker.GetInt();
int IntendedTick = Unpacker.GetInt();
int Size = Unpacker.GetInt();
// check for errors
if(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE)
return;
if(m_aClients[ClientID].m_LastAckedSnapshot > 0)
m_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL;
if(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0)
m_aClients[ClientID].m_Latency = (int)(((time_get()-TagTime)*1000)/time_freq());
// add message to report the input timing
// skip packets that are old
if(IntendedTick > m_aClients[ClientID].m_LastInputTick)
{
int TimeLeft = ((TickStartTime(IntendedTick)-time_get())*1000) / time_freq();
CMsgPacker Msg(NETMSG_INPUTTIMING);
Msg.AddInt(IntendedTick);
Msg.AddInt(TimeLeft);
SendMsgEx(&Msg, 0, ClientID, true);
}
m_aClients[ClientID].m_LastInputTick = IntendedTick;
pInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput];
if(IntendedTick <= Tick())
IntendedTick = Tick()+1;
pInput->m_GameTick = IntendedTick;
for(int i = 0; i < Size/4; i++)
pInput->m_aData[i] = Unpacker.GetInt();
mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int));
m_aClients[ClientID].m_CurrentInput++;
m_aClients[ClientID].m_CurrentInput %= 200;
// call the mod with the fresh input data
if(m_aClients[ClientID].m_State == CClient::STATE_INGAME)
GameServer()->OnClientDirectInput(ClientID, m_aClients[ClientID].m_LatestInput.m_aData);
}
else if(Msg == NETMSG_RCON_CMD)
{
const char *pCmd = Unpacker.GetString();
if(Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed)
{
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "ClientID=%d rcon='%s'", ClientID, pCmd);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
m_RconClientID = ClientID;
m_RconAuthLevel = m_aClients[ClientID].m_Authed;
Console()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD);
Console()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER);
Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN);
m_RconClientID = IServer::RCON_CID_SERV;
m_RconAuthLevel = AUTHED_ADMIN;
}
}
else if(Msg == NETMSG_RCON_AUTH)
{
const char *pPw;
Unpacker.GetString(); // login name, not used
pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC);
if(Unpacker.Error() == 0)
{
if(g_Config.m_SvRconPassword[0] == 0 && g_Config.m_SvRconModPassword[0] == 0)
{
SendRconLine(ClientID, "No rcon password set on server. Set sv_rcon_password and/or sv_rcon_mod_password to enable the remote console.");
}
else if(g_Config.m_SvRconPassword[0] && str_comp(pPw, g_Config.m_SvRconPassword) == 0)
{
CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
Msg.AddInt(1); //authed
Msg.AddInt(1); //cmdlist
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
m_aClients[ClientID].m_Authed = AUTHED_ADMIN;
int SendRconCmds = Unpacker.GetInt();
if(Unpacker.Error() == 0 && SendRconCmds)
m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_ADMIN, CFGFLAG_SERVER);
SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted.");
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (admin)", ClientID);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
else if(g_Config.m_SvRconModPassword[0] && str_comp(pPw, g_Config.m_SvRconModPassword) == 0)
{
CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
Msg.AddInt(1); //authed
Msg.AddInt(1); //cmdlist
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
m_aClients[ClientID].m_Authed = AUTHED_MOD;
int SendRconCmds = Unpacker.GetInt();
if(Unpacker.Error() == 0 && SendRconCmds)
m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_MOD, CFGFLAG_SERVER);
SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted.");
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (moderator)", ClientID);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
else if(g_Config.m_SvRconMaxTries)
{
m_aClients[ClientID].m_AuthTries++;
char aBuf[128];
str_format(aBuf, sizeof(aBuf), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, g_Config.m_SvRconMaxTries);
SendRconLine(ClientID, aBuf);
if(m_aClients[ClientID].m_AuthTries >= g_Config.m_SvRconMaxTries)
{
if(!g_Config.m_SvRconBantime)
m_NetServer.Drop(ClientID, "Too many remote console authentication tries");
else
m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, "Too many remote console authentication tries");
}
}
else
{
SendRconLine(ClientID, "Wrong password.");
}
}
}
else if(Msg == NETMSG_PING)
{
CMsgPacker Msg(NETMSG_PING_REPLY);
SendMsgEx(&Msg, 0, ClientID, true);
}
else
{
if(g_Config.m_Debug)
{
char aHex[] = "0123456789ABCDEF";
char aBuf[512];
for(int b = 0; b < pPacket->m_DataSize && b < 32; b++)
{
aBuf[b*3] = aHex[((const unsigned char *)pPacket->m_pData)[b]>>4];
aBuf[b*3+1] = aHex[((const unsigned char *)pPacket->m_pData)[b]&0xf];
aBuf[b*3+2] = ' ';
aBuf[b*3+3] = 0;
}
char aBufMsg[256];
str_format(aBufMsg, sizeof(aBufMsg), "strange message ClientID=%d msg=%d data_size=%d", ClientID, Msg, pPacket->m_DataSize);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBufMsg);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf);
}
}
}
else
{
// game message
if(m_aClients[ClientID].m_State >= CClient::STATE_READY)
GameServer()->OnMessage(Msg, &Unpacker, ClientID);
}
}
void CServer::SendServerInfo(const NETADDR *pAddr, int Token)
{
CNetChunk Packet;
CPacker p;
char aBuf[128];
// count the players
int PlayerCount = 0, ClientCount = 0;
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
{
if(GameServer()->IsClientPlayer(i))
PlayerCount++;
ClientCount++;
}
}
p.Reset();
p.AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO));
str_format(aBuf, sizeof(aBuf), "%d", Token);
p.AddString(aBuf, 6);
p.AddString(GameServer()->Version(), 32);
p.AddString(g_Config.m_SvName, 64);
p.AddString(GetMapName(), 32);
// gametype
p.AddString(GameServer()->GameType(), 16);
// flags
int i = 0;
if(g_Config.m_Password[0]) // password set
i |= SERVER_FLAG_PASSWORD;
str_format(aBuf, sizeof(aBuf), "%d", i);
p.AddString(aBuf, 2);
str_format(aBuf, sizeof(aBuf), "%d", PlayerCount); p.AddString(aBuf, 3); // num players
str_format(aBuf, sizeof(aBuf), "%d", m_NetServer.MaxClients()-g_Config.m_SvSpectatorSlots); p.AddString(aBuf, 3); // max players
str_format(aBuf, sizeof(aBuf), "%d", ClientCount); p.AddString(aBuf, 3); // num clients
str_format(aBuf, sizeof(aBuf), "%d", m_NetServer.MaxClients()); p.AddString(aBuf, 3); // max clients
for(i = 0; i < MAX_CLIENTS; i++)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
{
p.AddString(ClientName(i), MAX_NAME_LENGTH); // client name
p.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan
str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Country); p.AddString(aBuf, 6); // client country
str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Score); p.AddString(aBuf, 6); // client score
str_format(aBuf, sizeof(aBuf), "%d", GameServer()->IsClientPlayer(i)?1:0); p.AddString(aBuf, 2); // is player?
}
}
Packet.m_ClientID = -1;
Packet.m_Address = *pAddr;
Packet.m_Flags = NETSENDFLAG_CONNLESS;
Packet.m_DataSize = p.Size();
Packet.m_pData = p.Data();
m_NetServer.Send(&Packet);
}
void CServer::UpdateServerInfo()
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
SendServerInfo(m_NetServer.ClientAddr(i), -1);
}
}
void CServer::PumpNetwork()
{
CNetChunk Packet;
m_NetServer.Update();
// process packets
while(m_NetServer.Recv(&Packet))
{
if(Packet.m_ClientID == -1)
{
// stateless
if(!m_Register.RegisterProcessPacket(&Packet))
{
if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETINFO)+1 &&
mem_comp(Packet.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0)
{
SendServerInfo(&Packet.m_Address, ((unsigned char *)Packet.m_pData)[sizeof(SERVERBROWSE_GETINFO)]);
}
}
}
else
ProcessClientPacket(&Packet);
}
m_ServerBan.Update();
m_Econ.Update();
}
char *CServer::GetMapName()
{
// get the name of the map without his path
char *pMapShortName = &g_Config.m_SvMap[0];
for(int i = 0; i < str_length(g_Config.m_SvMap)-1; i++)
{
if(g_Config.m_SvMap[i] == '/' || g_Config.m_SvMap[i] == '\\')
pMapShortName = &g_Config.m_SvMap[i+1];
}
return pMapShortName;
}
int CServer::LoadMap(const char *pMapName)
{
//DATAFILE *df;
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName);
/*df = datafile_load(buf);
if(!df)
return 0;*/
// check for valid standard map
if(!m_MapChecker.ReadAndValidateMap(Storage(), aBuf, IStorage::TYPE_ALL))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapchecker", "invalid standard map");
return 0;
}
if(!m_pMap->Load(aBuf))
return 0;
// stop recording when we change map
m_DemoRecorder.Stop();
// reinit snapshot ids
m_IDPool.TimeoutIDs();
// get the crc of the map
m_CurrentMapCrc = m_pMap->Crc();
char aBufMsg[256];
str_format(aBufMsg, sizeof(aBufMsg), "%s crc is %08x", aBuf, m_CurrentMapCrc);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg);
str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap));
//map_set(df);
// load complete map into memory for download
{
IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);
m_CurrentMapSize = (int)io_length(File);
if(m_pCurrentMapData)
mem_free(m_pCurrentMapData);
m_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize, 1);
io_read(File, m_pCurrentMapData, m_CurrentMapSize);
io_close(File);
}
return 1;
}
void CServer::InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole)
{
m_Register.Init(pNetServer, pMasterServer, pConsole);
}
int CServer::Run()
{
//
m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, SendRconLineAuthed, this);
// load map
if(!LoadMap(g_Config.m_SvMap))
{
dbg_msg("server", "failed to load map. mapname='%s'", g_Config.m_SvMap);
return -1;
}
// start server
NETADDR BindAddr;
if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)
{
// sweet!
BindAddr.type = NETTYPE_ALL;
BindAddr.port = g_Config.m_SvPort;
}
else
{
mem_zero(&BindAddr, sizeof(BindAddr));
BindAddr.type = NETTYPE_ALL;
BindAddr.port = g_Config.m_SvPort;
}
if(!m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0))
{
dbg_msg("server", "couldn't open socket. port %d might already be in use", g_Config.m_SvPort);
return -1;
}
m_NetServer.SetCallbacks(NewClientCallback, DelClientCallback, this);
m_Econ.Init(Console(), &m_ServerBan);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "server name is '%s'", g_Config.m_SvName);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
GameServer()->OnInit();
str_format(aBuf, sizeof(aBuf), "version %s", GameServer()->NetVersion());
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
// process pending commands
m_pConsole->StoreCommands(false);
// start game
{
int64 ReportTime = time_get();
int ReportInterval = 3;
m_Lastheartbeat = 0;
m_GameStartTime = time_get();
if(g_Config.m_Debug)
{
str_format(aBuf, sizeof(aBuf), "baseline memory usage %dk", mem_stats()->allocated/1024);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf);
}
while(m_RunServer)
{
int64 t = time_get();
int NewTicks = 0;
// load new map TODO: don't poll this
if(str_comp(g_Config.m_SvMap, m_aCurrentMap) != 0 || m_MapReload)
{
m_MapReload = 0;
// load map
if(LoadMap(g_Config.m_SvMap))
{
// new map loaded
GameServer()->OnShutdown();
for(int c = 0; c < MAX_CLIENTS; c++)
{
if(m_aClients[c].m_State <= CClient::STATE_AUTH)
continue;
SendMap(c);
m_aClients[c].Reset();
m_aClients[c].m_State = CClient::STATE_CONNECTING;
}
m_GameStartTime = time_get();
m_CurrentGameTick = 0;
Kernel()->ReregisterInterface(GameServer());
GameServer()->OnInit();
UpdateServerInfo();
}
else
{
str_format(aBuf, sizeof(aBuf), "failed to load map. mapname='%s'", g_Config.m_SvMap);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
str_copy(g_Config.m_SvMap, m_aCurrentMap, sizeof(g_Config.m_SvMap));
}
}
while(t > TickStartTime(m_CurrentGameTick+1))
{
m_CurrentGameTick++;
NewTicks++;
// apply new input
for(int c = 0; c < MAX_CLIENTS; c++)
{
if(m_aClients[c].m_State == CClient::STATE_EMPTY)
continue;
for(int i = 0; i < 200; i++)
{
if(m_aClients[c].m_aInputs[i].m_GameTick == Tick())
{
if(m_aClients[c].m_State == CClient::STATE_INGAME)
GameServer()->OnClientPredictedInput(c, m_aClients[c].m_aInputs[i].m_aData);
break;
}
}
}
GameServer()->OnTick();
}
// snap game
if(NewTicks)
{
if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0)
DoSnapshot();
UpdateClientRconCommands();
}
// master server stuff
m_Register.RegisterUpdate(m_NetServer.NetType());
PumpNetwork();
if(ReportTime < time_get())
{
if(g_Config.m_Debug)
{
/*
static NETSTATS prev_stats;
NETSTATS stats;
netserver_stats(net, &stats);
perf_next();
if(config.dbg_pref)
perf_dump(&rootscope);
dbg_msg("server", "send=%8d recv=%8d",
(stats.send_bytes - prev_stats.send_bytes)/reportinterval,
(stats.recv_bytes - prev_stats.recv_bytes)/reportinterval);
prev_stats = stats;
*/
}
ReportTime += time_freq()*ReportInterval;
}
// wait for incomming data
net_socket_read_wait(m_NetServer.Socket(), 5);
}
}
// disconnect all clients on shutdown
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
m_NetServer.Drop(i, "Server shutdown");
m_Econ.Shutdown();
}
GameServer()->OnShutdown();
m_pMap->Unload();
if(m_pCurrentMapData)
mem_free(m_pCurrentMapData);
return 0;
}
void CServer::ConKick(IConsole::IResult *pResult, void *pUser)
{
if(pResult->NumArguments() > 1)
{
char aBuf[128];
str_format(aBuf, sizeof(aBuf), "Kicked (%s)", pResult->GetString(1));
((CServer *)pUser)->Kick(pResult->GetInteger(0), aBuf);
}
else
((CServer *)pUser)->Kick(pResult->GetInteger(0), "Kicked by console");
}
void CServer::ConStatus(IConsole::IResult *pResult, void *pUser)
{
char aBuf[1024];
char aAddrStr[NETADDR_MAXSTRSIZE];
CServer* pThis = static_cast<CServer *>(pUser);
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY)
{
net_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true);
if(pThis->m_aClients[i].m_State == CClient::STATE_INGAME)
{
const char *pAuthStr = pThis->m_aClients[i].m_Authed == CServer::AUTHED_ADMIN ? "(Admin)" :
pThis->m_aClients[i].m_Authed == CServer::AUTHED_MOD ? "(Mod)" : "";
str_format(aBuf, sizeof(aBuf), "id=%d addr=%s name='%s' score=%d %s", i, aAddrStr,
pThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score, pAuthStr);
}
else
str_format(aBuf, sizeof(aBuf), "id=%d addr=%s connecting", i, aAddrStr);
pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf);
}
}
}
void CServer::ConShutdown(IConsole::IResult *pResult, void *pUser)
{
((CServer *)pUser)->m_RunServer = 0;
}
void CServer::DemoRecorder_HandleAutoStart()
{
if(g_Config.m_SvAutoDemoRecord)
{
m_DemoRecorder.Stop();
char aFilename[128];
char aDate[20];
str_timestamp(aDate, sizeof(aDate));
str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", "auto/autorecord", aDate);
m_DemoRecorder.Start(Storage(), m_pConsole, aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "server");
if(g_Config.m_SvAutoDemoMax)
{
// clean up auto recorded demos
CFileCollection AutoDemos;
AutoDemos.Init(Storage(), "demos/server", "autorecord", ".demo", g_Config.m_SvAutoDemoMax);
}
}
}
bool CServer::DemoRecorder_IsRecording()
{
return m_DemoRecorder.IsRecording();
}
void CServer::ConRecord(IConsole::IResult *pResult, void *pUser)
{
CServer* pServer = (CServer *)pUser;
char aFilename[128];
if(pResult->NumArguments())
str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pResult->GetString(0));
else
{
char aDate[20];
str_timestamp(aDate, sizeof(aDate));
str_format(aFilename, sizeof(aFilename), "demos/demo_%s.demo", aDate);
}
pServer->m_DemoRecorder.Start(pServer->Storage(), pServer->Console(), aFilename, pServer->GameServer()->NetVersion(), pServer->m_aCurrentMap, pServer->m_CurrentMapCrc, "server");
}
void CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser)
{
((CServer *)pUser)->m_DemoRecorder.Stop();
}
void CServer::ConMapReload(IConsole::IResult *pResult, void *pUser)
{
((CServer *)pUser)->m_MapReload = 1;
}
void CServer::ConLogout(IConsole::IResult *pResult, void *pUser)
{
CServer *pServer = (CServer *)pUser;
if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS &&
pServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
{
CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
Msg.AddInt(0); //authed
Msg.AddInt(0); //cmdlist
pServer->SendMsgEx(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID, true);
pServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO;
pServer->m_aClients[pServer->m_RconClientID].m_AuthTries = 0;
pServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0;
pServer->SendRconLine(pServer->m_RconClientID, "Logout successful.");
char aBuf[32];
str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out", pServer->m_RconClientID);
pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
}
void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments())
((CServer *)pUserData)->UpdateServerInfo();
}
void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments())
((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIP(pResult->GetInteger(0));
}
void CServer::ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
if(pResult->NumArguments() == 2)
{
CServer *pThis = static_cast<CServer *>(pUserData);
const IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false);
int OldAccessLevel = 0;
if(pInfo)
OldAccessLevel = pInfo->GetAccessLevel();
pfnCallback(pResult, pCallbackUserData);
if(pInfo && OldAccessLevel != pInfo->GetAccessLevel())
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || pThis->m_aClients[i].m_Authed != CServer::AUTHED_MOD ||
(pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0))
continue;
if(OldAccessLevel == IConsole::ACCESS_LEVEL_ADMIN)
pThis->SendRconCmdAdd(pInfo, i);
else
pThis->SendRconCmdRem(pInfo, i);
}
}
}
else
pfnCallback(pResult, pCallbackUserData);
}
void CServer::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments() == 1)
{
CServer *pThis = static_cast<CServer *>(pUserData);
pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0));
}
}
void CServer::RegisterCommands()
{
m_pConsole = Kernel()->RequestInterface<IConsole>();
m_pGameServer = Kernel()->RequestInterface<IGameServer>();
m_pMap = Kernel()->RequestInterface<IEngineMap>();
m_pStorage = Kernel()->RequestInterface<IStorage>();
// register console commands
Console()->Register("kick", "i?r", CFGFLAG_SERVER, ConKick, this, "Kick player with specified id for any reason");
Console()->Register("status", "", CFGFLAG_SERVER, ConStatus, this, "List players");
Console()->Register("shutdown", "", CFGFLAG_SERVER, ConShutdown, this, "Shut down");
Console()->Register("logout", "", CFGFLAG_SERVER, ConLogout, this, "Logout of rcon");
Console()->Register("record", "?s", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file");
Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording");
Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, "Reload the map");
Console()->Chain("sv_name", ConchainSpecialInfoupdate, this);
Console()->Chain("password", ConchainSpecialInfoupdate, this);
Console()->Chain("sv_max_clients_per_ip", ConchainMaxclientsperipUpdate, this);
Console()->Chain("mod_command", ConchainModCommandUpdate, this);
Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this);
// register console commands in sub parts
m_ServerBan.InitServerBan(Console(), Storage(), this);
m_pGameServer->OnConsoleInit();
}
int CServer::SnapNewID()
{
return m_IDPool.NewID();
}
void CServer::SnapFreeID(int ID)
{
m_IDPool.FreeID(ID);
}
void *CServer::SnapNewItem(int Type, int ID, int Size)
{
dbg_assert(Type >= 0 && Type <=0xffff, "incorrect type");
dbg_assert(ID >= 0 && ID <=0xffff, "incorrect id");
return ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size);
}
void CServer::SnapSetStaticsize(int ItemType, int Size)
{
m_SnapshotDelta.SetStaticsize(ItemType, Size);
}
static CServer *CreateServer() { return new CServer(); }
int main(int argc, const char **argv) // ignore_convention
{
#if defined(CONF_FAMILY_WINDOWS)
for(int i = 1; i < argc; i++) // ignore_convention
{
if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
break;
}
}
#endif
CServer *pServer = CreateServer();
IKernel *pKernel = IKernel::Create();
// create the components
IEngine *pEngine = CreateEngine("Teeworlds");
IEngineMap *pEngineMap = CreateEngineMap();
IGameServer *pGameServer = CreateGameServer();
IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON);
IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer();
IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention
IConfig *pConfig = CreateConfig();
pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole);
{
bool RegisterFail = false;
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap));
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer));
if(RegisterFail)
return -1;
}
pEngine->Init();
pConfig->Init();
pEngineMasterServer->Init();
pEngineMasterServer->Load();
// register all console commands
pServer->RegisterCommands();
// execute autoexec file
pConsole->ExecuteFile("autoexec.cfg");
// parse the command line arguments
if(argc > 1) // ignore_convention
pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention
// restore empty config strings to their defaults
pConfig->RestoreStrings();
pEngine->InitLogfile();
// run the server
dbg_msg("server", "starting...");
pServer->Run();
// free
delete pServer;
delete pKernel;
delete pEngineMap;
delete pGameServer;
delete pConsole;
delete pEngineMasterServer;
delete pStorage;
delete pConfig;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_2369_0 |
crossvul-cpp_data_good_1442_3 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/znc.h>
#include <znc/FileUtils.h>
#include <znc/IRCSock.h>
#include <znc/Server.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Config.h>
#include <time.h>
#include <tuple>
#include <algorithm>
using std::endl;
using std::cout;
using std::map;
using std::set;
using std::vector;
using std::list;
using std::tuple;
using std::make_tuple;
CZNC::CZNC()
: m_TimeStarted(time(nullptr)),
m_eConfigState(ECONFIG_NOTHING),
m_vpListeners(),
m_msUsers(),
m_msDelUsers(),
m_Manager(),
m_sCurPath(""),
m_sZNCPath(""),
m_sConfigFile(""),
m_sSkinName(""),
m_sStatusPrefix(""),
m_sPidFile(""),
m_sSSLCertFile(""),
m_sSSLKeyFile(""),
m_sSSLDHParamFile(""),
m_sSSLCiphers(""),
m_sSSLProtocols(""),
m_vsBindHosts(),
m_vsTrustedProxies(),
m_vsMotd(),
m_pLockFile(nullptr),
m_uiConnectDelay(5),
m_uiAnonIPLimit(10),
m_uiMaxBufferSize(500),
m_uDisabledSSLProtocols(Csock::EDP_SSL),
m_pModules(new CModules),
m_uBytesRead(0),
m_uBytesWritten(0),
m_lpConnectQueue(),
m_pConnectQueueTimer(nullptr),
m_uiConnectPaused(0),
m_uiForceEncoding(0),
m_sConnectThrottle(),
m_bProtectWebSessions(true),
m_bHideVersion(false),
m_bAuthOnlyViaModule(false),
m_Translation("znc"),
m_uiConfigWriteDelay(0),
m_pConfigTimer(nullptr) {
if (!InitCsocket()) {
CUtils::PrintError("Could not initialize Csocket!");
exit(-1);
}
m_sConnectThrottle.SetTTL(30000);
}
CZNC::~CZNC() {
m_pModules->UnloadAll();
for (const auto& it : m_msUsers) {
it.second->GetModules().UnloadAll();
const vector<CIRCNetwork*>& networks = it.second->GetNetworks();
for (CIRCNetwork* pNetwork : networks) {
pNetwork->GetModules().UnloadAll();
}
}
for (CListener* pListener : m_vpListeners) {
delete pListener;
}
for (const auto& it : m_msUsers) {
it.second->SetBeingDeleted(true);
}
m_pConnectQueueTimer = nullptr;
// This deletes m_pConnectQueueTimer
m_Manager.Cleanup();
DeleteUsers();
delete m_pModules;
delete m_pLockFile;
ShutdownCsocket();
DeletePidFile();
}
CString CZNC::GetVersion() {
return CString(VERSION_STR) + CString(ZNC_VERSION_EXTRA);
}
CString CZNC::GetTag(bool bIncludeVersion, bool bHTML) {
if (!Get().m_bHideVersion) {
bIncludeVersion = true;
}
CString sAddress = bHTML ? "<a href=\"https://znc.in\">https://znc.in</a>"
: "https://znc.in";
if (!bIncludeVersion) {
return "ZNC - " + sAddress;
}
CString sVersion = GetVersion();
return "ZNC " + sVersion + " - " + sAddress;
}
CString CZNC::GetCompileOptionsString() {
// Build system doesn't affect ABI
return ZNC_COMPILE_OPTIONS_STRING + CString(
", build: "
#ifdef BUILD_WITH_CMAKE
"cmake"
#else
"autoconf"
#endif
);
}
CString CZNC::GetUptime() const {
time_t now = time(nullptr);
return CString::ToTimeStr(now - TimeStarted());
}
bool CZNC::OnBoot() {
bool bFail = false;
ALLMODULECALL(OnBoot(), &bFail);
if (bFail) return false;
return true;
}
bool CZNC::HandleUserDeletion() {
if (m_msDelUsers.empty()) return false;
for (const auto& it : m_msDelUsers) {
CUser* pUser = it.second;
pUser->SetBeingDeleted(true);
if (GetModules().OnDeleteUser(*pUser)) {
pUser->SetBeingDeleted(false);
continue;
}
m_msUsers.erase(pUser->GetUserName());
CWebSock::FinishUserSessions(*pUser);
delete pUser;
}
m_msDelUsers.clear();
return true;
}
class CConfigWriteTimer : public CCron {
public:
CConfigWriteTimer(int iSecs) : CCron() {
SetName("Config write timer");
Start(iSecs);
}
protected:
void RunJob() override {
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_WRITE);
CZNC::Get().DisableConfigTimer();
}
};
void CZNC::Loop() {
while (true) {
CString sError;
ConfigState eState = GetConfigState();
switch (eState) {
case ECONFIG_NEED_REHASH:
SetConfigState(ECONFIG_NOTHING);
if (RehashConfig(sError)) {
Broadcast("Rehashing succeeded", true);
} else {
Broadcast("Rehashing failed: " + sError, true);
Broadcast("ZNC is in some possibly inconsistent state!",
true);
}
break;
case ECONFIG_DELAYED_WRITE:
SetConfigState(ECONFIG_NOTHING);
if (GetConfigWriteDelay() > 0) {
if (m_pConfigTimer == nullptr) {
m_pConfigTimer = new CConfigWriteTimer(GetConfigWriteDelay());
GetManager().AddCron(m_pConfigTimer);
}
break;
}
/* Fall through */
case ECONFIG_NEED_WRITE:
case ECONFIG_NEED_VERBOSE_WRITE:
SetConfigState(ECONFIG_NOTHING);
// stop pending configuration timer
DisableConfigTimer();
if (!WriteConfig()) {
Broadcast("Writing the config file failed", true);
} else if (eState == ECONFIG_NEED_VERBOSE_WRITE) {
Broadcast("Writing the config succeeded", true);
}
break;
case ECONFIG_NOTHING:
break;
case ECONFIG_NEED_QUIT:
return;
}
// Check for users that need to be deleted
if (HandleUserDeletion()) {
// Also remove those user(s) from the config file
WriteConfig();
}
// Csocket wants micro seconds
// 100 msec to 5 min
m_Manager.DynamicSelectLoop(100 * 1000, 5 * 60 * 1000 * 1000);
}
}
CFile* CZNC::InitPidFile() {
if (!m_sPidFile.empty()) {
CString sFile;
// absolute path or relative to the data dir?
if (m_sPidFile[0] != '/')
sFile = GetZNCPath() + "/" + m_sPidFile;
else
sFile = m_sPidFile;
return new CFile(sFile);
}
return nullptr;
}
bool CZNC::WritePidFile(int iPid) {
CFile* File = InitPidFile();
if (File == nullptr) return false;
CUtils::PrintAction("Writing pid file [" + File->GetLongName() + "]");
bool bRet = false;
if (File->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
File->Write(CString(iPid) + "\n");
File->Close();
bRet = true;
}
delete File;
CUtils::PrintStatus(bRet);
return bRet;
}
bool CZNC::DeletePidFile() {
CFile* File = InitPidFile();
if (File == nullptr) return false;
CUtils::PrintAction("Deleting pid file [" + File->GetLongName() + "]");
bool bRet = File->Delete();
delete File;
CUtils::PrintStatus(bRet);
return bRet;
}
bool CZNC::WritePemFile() {
#ifndef HAVE_LIBSSL
CUtils::PrintError("ZNC was not compiled with ssl support.");
return false;
#else
CString sPemFile = GetPemLocation();
CUtils::PrintAction("Writing Pem file [" + sPemFile + "]");
#ifndef _WIN32
int fd = creat(sPemFile.c_str(), 0600);
if (fd == -1) {
CUtils::PrintStatus(false, "Unable to open");
return false;
}
FILE* f = fdopen(fd, "w");
#else
FILE* f = fopen(sPemFile.c_str(), "w");
#endif
if (!f) {
CUtils::PrintStatus(false, "Unable to open");
return false;
}
CUtils::GenerateCert(f, "");
fclose(f);
CUtils::PrintStatus(true);
return true;
#endif
}
void CZNC::DeleteUsers() {
for (const auto& it : m_msUsers) {
it.second->SetBeingDeleted(true);
delete it.second;
}
m_msUsers.clear();
DisableConnectQueue();
}
bool CZNC::IsHostAllowed(const CString& sHostMask) const {
for (const auto& it : m_msUsers) {
if (it.second->IsHostAllowed(sHostMask)) {
return true;
}
}
return false;
}
bool CZNC::AllowConnectionFrom(const CString& sIP) const {
if (m_uiAnonIPLimit == 0) return true;
return (GetManager().GetAnonConnectionCount(sIP) < m_uiAnonIPLimit);
}
void CZNC::InitDirs(const CString& sArgvPath, const CString& sDataDir) {
// If the bin was not ran from the current directory, we need to add that
// dir onto our cwd
CString::size_type uPos = sArgvPath.rfind('/');
if (uPos == CString::npos)
m_sCurPath = "./";
else
m_sCurPath = CDir::ChangeDir("./", sArgvPath.Left(uPos), "");
// Try to set the user's home dir, default to binpath on failure
CFile::InitHomePath(m_sCurPath);
if (sDataDir.empty()) {
m_sZNCPath = CFile::GetHomePath() + "/.znc";
} else {
m_sZNCPath = sDataDir;
}
m_sSSLCertFile = m_sZNCPath + "/znc.pem";
}
CString CZNC::GetConfPath(bool bAllowMkDir) const {
CString sConfPath = m_sZNCPath + "/configs";
if (bAllowMkDir && !CFile::Exists(sConfPath)) {
CDir::MakeDir(sConfPath);
}
return sConfPath;
}
CString CZNC::GetUserPath() const {
CString sUserPath = m_sZNCPath + "/users";
if (!CFile::Exists(sUserPath)) {
CDir::MakeDir(sUserPath);
}
return sUserPath;
}
CString CZNC::GetModPath() const {
CString sModPath = m_sZNCPath + "/modules";
return sModPath;
}
const CString& CZNC::GetCurPath() const {
if (!CFile::Exists(m_sCurPath)) {
CDir::MakeDir(m_sCurPath);
}
return m_sCurPath;
}
const CString& CZNC::GetHomePath() const { return CFile::GetHomePath(); }
const CString& CZNC::GetZNCPath() const {
if (!CFile::Exists(m_sZNCPath)) {
CDir::MakeDir(m_sZNCPath);
}
return m_sZNCPath;
}
CString CZNC::GetPemLocation() const {
return CDir::ChangeDir("", m_sSSLCertFile);
}
CString CZNC::GetKeyLocation() const {
return CDir::ChangeDir(
"", m_sSSLKeyFile.empty() ? m_sSSLCertFile : m_sSSLKeyFile);
}
CString CZNC::GetDHParamLocation() const {
return CDir::ChangeDir(
"", m_sSSLDHParamFile.empty() ? m_sSSLCertFile : m_sSSLDHParamFile);
}
CString CZNC::ExpandConfigPath(const CString& sConfigFile, bool bAllowMkDir) {
CString sRetPath;
if (sConfigFile.empty()) {
sRetPath = GetConfPath(bAllowMkDir) + "/znc.conf";
} else {
if (sConfigFile.StartsWith("./") || sConfigFile.StartsWith("../")) {
sRetPath = GetCurPath() + "/" + sConfigFile;
} else if (!sConfigFile.StartsWith("/")) {
sRetPath = GetConfPath(bAllowMkDir) + "/" + sConfigFile;
} else {
sRetPath = sConfigFile;
}
}
return sRetPath;
}
bool CZNC::WriteConfig() {
if (GetConfigFile().empty()) {
DEBUG("Config file name is empty?!");
return false;
}
// We first write to a temporary file and then move it to the right place
CFile* pFile = new CFile(GetConfigFile() + "~");
if (!pFile->Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) {
DEBUG("Could not write config to " + GetConfigFile() + "~: " +
CString(strerror(errno)));
delete pFile;
return false;
}
// We have to "transfer" our lock on the config to the new file.
// The old file (= inode) is going away and thus a lock on it would be
// useless. These lock should always succeed (races, anyone?).
if (!pFile->TryExLock()) {
DEBUG("Error while locking the new config file, errno says: " +
CString(strerror(errno)));
pFile->Delete();
delete pFile;
return false;
}
pFile->Write(MakeConfigHeader() + "\n");
CConfig config;
config.AddKeyValuePair("AnonIPLimit", CString(m_uiAnonIPLimit));
config.AddKeyValuePair("MaxBufferSize", CString(m_uiMaxBufferSize));
config.AddKeyValuePair("SSLCertFile", CString(GetPemLocation()));
config.AddKeyValuePair("SSLKeyFile", CString(GetKeyLocation()));
config.AddKeyValuePair("SSLDHParamFile", CString(GetDHParamLocation()));
config.AddKeyValuePair("ProtectWebSessions",
CString(m_bProtectWebSessions));
config.AddKeyValuePair("HideVersion", CString(m_bHideVersion));
config.AddKeyValuePair("AuthOnlyViaModule", CString(m_bAuthOnlyViaModule));
config.AddKeyValuePair("Version", CString(VERSION_STR));
config.AddKeyValuePair("ConfigWriteDelay", CString(m_uiConfigWriteDelay));
unsigned int l = 0;
for (CListener* pListener : m_vpListeners) {
CConfig listenerConfig;
listenerConfig.AddKeyValuePair("Host", pListener->GetBindHost());
listenerConfig.AddKeyValuePair("URIPrefix",
pListener->GetURIPrefix() + "/");
listenerConfig.AddKeyValuePair("Port", CString(pListener->GetPort()));
listenerConfig.AddKeyValuePair(
"IPv4", CString(pListener->GetAddrType() != ADDR_IPV6ONLY));
listenerConfig.AddKeyValuePair(
"IPv6", CString(pListener->GetAddrType() != ADDR_IPV4ONLY));
listenerConfig.AddKeyValuePair("SSL", CString(pListener->IsSSL()));
listenerConfig.AddKeyValuePair(
"AllowIRC",
CString(pListener->GetAcceptType() != CListener::ACCEPT_HTTP));
listenerConfig.AddKeyValuePair(
"AllowWeb",
CString(pListener->GetAcceptType() != CListener::ACCEPT_IRC));
config.AddSubConfig("Listener", "listener" + CString(l++),
listenerConfig);
}
config.AddKeyValuePair("ConnectDelay", CString(m_uiConnectDelay));
config.AddKeyValuePair("ServerThrottle",
CString(m_sConnectThrottle.GetTTL() / 1000));
if (!m_sPidFile.empty()) {
config.AddKeyValuePair("PidFile", m_sPidFile.FirstLine());
}
if (!m_sSkinName.empty()) {
config.AddKeyValuePair("Skin", m_sSkinName.FirstLine());
}
if (!m_sStatusPrefix.empty()) {
config.AddKeyValuePair("StatusPrefix", m_sStatusPrefix.FirstLine());
}
if (!m_sSSLCiphers.empty()) {
config.AddKeyValuePair("SSLCiphers", CString(m_sSSLCiphers));
}
if (!m_sSSLProtocols.empty()) {
config.AddKeyValuePair("SSLProtocols", m_sSSLProtocols);
}
for (const CString& sLine : m_vsMotd) {
config.AddKeyValuePair("Motd", sLine.FirstLine());
}
for (const CString& sProxy : m_vsTrustedProxies) {
config.AddKeyValuePair("TrustedProxy", sProxy.FirstLine());
}
CModules& Mods = GetModules();
for (const CModule* pMod : Mods) {
CString sName = pMod->GetModName();
CString sArgs = pMod->GetArgs();
if (!sArgs.empty()) {
sArgs = " " + sArgs.FirstLine();
}
config.AddKeyValuePair("LoadModule", sName.FirstLine() + sArgs);
}
for (const auto& it : m_msUsers) {
CString sErr;
if (!it.second->IsValid(sErr)) {
DEBUG("** Error writing config for user [" << it.first << "] ["
<< sErr << "]");
continue;
}
config.AddSubConfig("User", it.second->GetUserName(),
it.second->ToConfig());
}
config.Write(*pFile);
// If Sync() fails... well, let's hope nothing important breaks..
pFile->Sync();
if (pFile->HadError()) {
DEBUG("Error while writing the config, errno says: " +
CString(strerror(errno)));
pFile->Delete();
delete pFile;
return false;
}
// We wrote to a temporary name, move it to the right place
if (!pFile->Move(GetConfigFile(), true)) {
DEBUG(
"Error while replacing the config file with a new version, errno "
"says "
<< strerror(errno));
pFile->Delete();
delete pFile;
return false;
}
// Everything went fine, just need to update the saved path.
pFile->SetFileName(GetConfigFile());
// Make sure the lock is kept alive as long as we need it.
delete m_pLockFile;
m_pLockFile = pFile;
return true;
}
CString CZNC::MakeConfigHeader() {
return "// WARNING\n"
"//\n"
"// Do NOT edit this file while ZNC is running!\n"
"// Use webadmin or *controlpanel instead.\n"
"//\n"
"// Altering this file by hand will forfeit all support.\n"
"//\n"
"// But if you feel risky, you might want to read help on /znc "
"saveconfig and /znc rehash.\n"
"// Also check https://wiki.znc.in/Configuration\n";
}
bool CZNC::WriteNewConfig(const CString& sConfigFile) {
CString sAnswer, sUser, sNetwork;
VCString vsLines;
vsLines.push_back(MakeConfigHeader());
vsLines.push_back("Version = " + CString(VERSION_STR));
m_sConfigFile = ExpandConfigPath(sConfigFile);
if (CFile::Exists(m_sConfigFile)) {
CUtils::PrintStatus(
false, "WARNING: config [" + m_sConfigFile + "] already exists.");
}
CUtils::PrintMessage("");
CUtils::PrintMessage("-- Global settings --");
CUtils::PrintMessage("");
// Listen
#ifdef HAVE_IPV6
bool b6 = true;
#else
bool b6 = false;
#endif
CString sListenHost;
CString sURIPrefix;
bool bListenSSL = false;
unsigned int uListenPort = 0;
bool bSuccess;
do {
bSuccess = true;
while (true) {
if (!CUtils::GetNumInput("Listen on port", uListenPort, 1025,
65534)) {
continue;
}
if (uListenPort == 6667) {
CUtils::PrintStatus(false,
"WARNING: Some web browsers reject port "
"6667. If you intend to");
CUtils::PrintStatus(false,
"use ZNC's web interface, you might want "
"to use another port.");
if (!CUtils::GetBoolInput("Proceed with port 6667 anyway?",
true)) {
continue;
}
}
break;
}
#ifdef HAVE_LIBSSL
bListenSSL = CUtils::GetBoolInput("Listen using SSL", bListenSSL);
#endif
#ifdef HAVE_IPV6
b6 = CUtils::GetBoolInput("Listen using both IPv4 and IPv6", b6);
#endif
// Don't ask for listen host, it may be configured later if needed.
CUtils::PrintAction("Verifying the listener");
CListener* pListener = new CListener(
(unsigned short int)uListenPort, sListenHost, sURIPrefix,
bListenSSL, b6 ? ADDR_ALL : ADDR_IPV4ONLY, CListener::ACCEPT_ALL);
if (!pListener->Listen()) {
CUtils::PrintStatus(false, FormatBindError());
bSuccess = false;
} else
CUtils::PrintStatus(true);
delete pListener;
} while (!bSuccess);
#ifdef HAVE_LIBSSL
CString sPemFile = GetPemLocation();
if (!CFile::Exists(sPemFile)) {
CUtils::PrintMessage("Unable to locate pem file: [" + sPemFile +
"], creating it");
WritePemFile();
}
#endif
vsLines.push_back("<Listener l>");
vsLines.push_back("\tPort = " + CString(uListenPort));
vsLines.push_back("\tIPv4 = true");
vsLines.push_back("\tIPv6 = " + CString(b6));
vsLines.push_back("\tSSL = " + CString(bListenSSL));
if (!sListenHost.empty()) {
vsLines.push_back("\tHost = " + sListenHost);
}
vsLines.push_back("</Listener>");
// !Listen
set<CModInfo> ssGlobalMods;
GetModules().GetDefaultMods(ssGlobalMods, CModInfo::GlobalModule);
vector<CString> vsGlobalModNames;
for (const CModInfo& Info : ssGlobalMods) {
vsGlobalModNames.push_back(Info.GetName());
vsLines.push_back("LoadModule = " + Info.GetName());
}
CUtils::PrintMessage(
"Enabled global modules [" +
CString(", ").Join(vsGlobalModNames.begin(), vsGlobalModNames.end()) +
"]");
// User
CUtils::PrintMessage("");
CUtils::PrintMessage("-- Admin user settings --");
CUtils::PrintMessage("");
vsLines.push_back("");
CString sNick;
do {
CUtils::GetInput("Username", sUser, "", "alphanumeric");
} while (!CUser::IsValidUserName(sUser));
vsLines.push_back("<User " + sUser + ">");
CString sSalt;
sAnswer = CUtils::GetSaltedHashPass(sSalt);
vsLines.push_back("\tPass = " + CUtils::sDefaultHash + "#" + sAnswer +
"#" + sSalt + "#");
vsLines.push_back("\tAdmin = true");
CUtils::GetInput("Nick", sNick, CUser::MakeCleanUserName(sUser));
vsLines.push_back("\tNick = " + sNick);
CUtils::GetInput("Alternate nick", sAnswer, sNick + "_");
if (!sAnswer.empty()) {
vsLines.push_back("\tAltNick = " + sAnswer);
}
CUtils::GetInput("Ident", sAnswer, sUser);
vsLines.push_back("\tIdent = " + sAnswer);
CUtils::GetInput("Real name", sAnswer, "", "optional");
if (!sAnswer.empty()) {
vsLines.push_back("\tRealName = " + sAnswer);
}
CUtils::GetInput("Bind host", sAnswer, "", "optional");
if (!sAnswer.empty()) {
vsLines.push_back("\tBindHost = " + sAnswer);
}
set<CModInfo> ssUserMods;
GetModules().GetDefaultMods(ssUserMods, CModInfo::UserModule);
vector<CString> vsUserModNames;
for (const CModInfo& Info : ssUserMods) {
vsUserModNames.push_back(Info.GetName());
vsLines.push_back("\tLoadModule = " + Info.GetName());
}
CUtils::PrintMessage(
"Enabled user modules [" +
CString(", ").Join(vsUserModNames.begin(), vsUserModNames.end()) + "]");
CUtils::PrintMessage("");
if (CUtils::GetBoolInput("Set up a network?", true)) {
vsLines.push_back("");
CUtils::PrintMessage("");
CUtils::PrintMessage("-- Network settings --");
CUtils::PrintMessage("");
do {
CUtils::GetInput("Name", sNetwork, "freenode");
} while (!CIRCNetwork::IsValidNetwork(sNetwork));
vsLines.push_back("\t<Network " + sNetwork + ">");
set<CModInfo> ssNetworkMods;
GetModules().GetDefaultMods(ssNetworkMods, CModInfo::NetworkModule);
vector<CString> vsNetworkModNames;
for (const CModInfo& Info : ssNetworkMods) {
vsNetworkModNames.push_back(Info.GetName());
vsLines.push_back("\t\tLoadModule = " + Info.GetName());
}
CString sHost, sPass, sHint;
bool bSSL = false;
unsigned int uServerPort = 0;
if (sNetwork.Equals("freenode")) {
sHost = "chat.freenode.net";
#ifdef HAVE_LIBSSL
bSSL = true;
#endif
} else {
sHint = "host only";
}
while (!CUtils::GetInput("Server host", sHost, sHost, sHint) ||
!CServer::IsValidHostName(sHost))
;
#ifdef HAVE_LIBSSL
bSSL = CUtils::GetBoolInput("Server uses SSL?", bSSL);
#endif
while (!CUtils::GetNumInput("Server port", uServerPort, 1, 65535,
bSSL ? 6697 : 6667))
;
CUtils::GetInput("Server password (probably empty)", sPass);
vsLines.push_back("\t\tServer = " + sHost + ((bSSL) ? " +" : " ") +
CString(uServerPort) + " " + sPass);
CString sChans;
if (CUtils::GetInput("Initial channels", sChans)) {
vsLines.push_back("");
VCString vsChans;
sChans.Replace(",", " ");
sChans.Replace(";", " ");
sChans.Split(" ", vsChans, false, "", "", true, true);
for (const CString& sChan : vsChans) {
vsLines.push_back("\t\t<Chan " + sChan + ">");
vsLines.push_back("\t\t</Chan>");
}
}
CUtils::PrintMessage("Enabled network modules [" +
CString(", ").Join(vsNetworkModNames.begin(),
vsNetworkModNames.end()) +
"]");
vsLines.push_back("\t</Network>");
}
vsLines.push_back("</User>");
CUtils::PrintMessage("");
// !User
CFile File;
bool bFileOK, bFileOpen = false;
do {
CUtils::PrintAction("Writing config [" + m_sConfigFile + "]");
bFileOK = true;
if (CFile::Exists(m_sConfigFile)) {
if (!File.TryExLock(m_sConfigFile)) {
CUtils::PrintStatus(false,
"ZNC is currently running on this config.");
bFileOK = false;
} else {
File.Close();
CUtils::PrintStatus(false, "This config already exists.");
if (CUtils::GetBoolInput(
"Are you sure you want to overwrite it?", false))
CUtils::PrintAction("Overwriting config [" + m_sConfigFile +
"]");
else
bFileOK = false;
}
}
if (bFileOK) {
File.SetFileName(m_sConfigFile);
if (File.Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) {
bFileOpen = true;
} else {
CUtils::PrintStatus(false, "Unable to open file");
bFileOK = false;
}
}
if (!bFileOK) {
while (!CUtils::GetInput("Please specify an alternate location",
m_sConfigFile, "",
"or \"stdout\" for displaying the config"))
;
if (m_sConfigFile.Equals("stdout"))
bFileOK = true;
else
m_sConfigFile = ExpandConfigPath(m_sConfigFile);
}
} while (!bFileOK);
if (!bFileOpen) {
CUtils::PrintMessage("");
CUtils::PrintMessage("Printing the new config to stdout:");
CUtils::PrintMessage("");
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
}
for (const CString& sLine : vsLines) {
if (bFileOpen) {
File.Write(sLine + "\n");
} else {
cout << sLine << endl;
}
}
if (bFileOpen) {
File.Close();
if (File.HadError())
CUtils::PrintStatus(false,
"There was an error while writing the config");
else
CUtils::PrintStatus(true);
} else {
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
}
if (File.HadError()) {
bFileOpen = false;
CUtils::PrintMessage("Printing the new config to stdout instead:");
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
for (const CString& sLine : vsLines) {
cout << sLine << endl;
}
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
}
const CString sProtocol(bListenSSL ? "https" : "http");
const CString sSSL(bListenSSL ? "+" : "");
CUtils::PrintMessage("");
CUtils::PrintMessage(
"To connect to this ZNC you need to connect to it as your IRC server",
true);
CUtils::PrintMessage(
"using the port that you supplied. You have to supply your login info",
true);
CUtils::PrintMessage(
"as the IRC server password like this: user/network:pass.", true);
CUtils::PrintMessage("");
CUtils::PrintMessage("Try something like this in your IRC client...", true);
CUtils::PrintMessage("/server <znc_server_ip> " + sSSL +
CString(uListenPort) + " " + sUser + ":<pass>",
true);
CUtils::PrintMessage("");
CUtils::PrintMessage(
"To manage settings, users and networks, point your web browser to",
true);
CUtils::PrintMessage(
sProtocol + "://<znc_server_ip>:" + CString(uListenPort) + "/", true);
CUtils::PrintMessage("");
File.UnLock();
bool bWantLaunch = bFileOpen;
if (bWantLaunch) {
// "export ZNC_NO_LAUNCH_AFTER_MAKECONF=1" would cause znc --makeconf to
// not offer immediate launch.
// Useful for distros which want to create config when znc package is
// installed.
// See https://github.com/znc/znc/pull/257
char* szNoLaunch = getenv("ZNC_NO_LAUNCH_AFTER_MAKECONF");
if (szNoLaunch && *szNoLaunch == '1') {
bWantLaunch = false;
}
}
if (bWantLaunch) {
bWantLaunch = CUtils::GetBoolInput("Launch ZNC now?", true);
}
return bWantLaunch;
}
void CZNC::BackupConfigOnce(const CString& sSuffix) {
static bool didBackup = false;
if (didBackup) return;
didBackup = true;
CUtils::PrintAction("Creating a config backup");
CString sBackup = CDir::ChangeDir(m_sConfigFile, "../znc.conf." + sSuffix);
if (CFile::Copy(m_sConfigFile, sBackup))
CUtils::PrintStatus(true, sBackup);
else
CUtils::PrintStatus(false, strerror(errno));
}
bool CZNC::ParseConfig(const CString& sConfig, CString& sError) {
m_sConfigFile = ExpandConfigPath(sConfig, false);
CConfig config;
if (!ReadConfig(config, sError)) return false;
if (!LoadGlobal(config, sError)) return false;
if (!LoadUsers(config, sError)) return false;
return true;
}
bool CZNC::ReadConfig(CConfig& config, CString& sError) {
sError.clear();
CUtils::PrintAction("Opening config [" + m_sConfigFile + "]");
if (!CFile::Exists(m_sConfigFile)) {
sError = "No such file";
CUtils::PrintStatus(false, sError);
CUtils::PrintMessage(
"Restart ZNC with the --makeconf option if you wish to create this "
"config.");
return false;
}
if (!CFile::IsReg(m_sConfigFile)) {
sError = "Not a file";
CUtils::PrintStatus(false, sError);
return false;
}
CFile* pFile = new CFile(m_sConfigFile);
// need to open the config file Read/Write for fcntl()
// exclusive locking to work properly!
if (!pFile->Open(m_sConfigFile, O_RDWR)) {
sError = "Can not open config file";
CUtils::PrintStatus(false, sError);
delete pFile;
return false;
}
if (!pFile->TryExLock()) {
sError = "ZNC is already running on this config.";
CUtils::PrintStatus(false, sError);
delete pFile;
return false;
}
// (re)open the config file
delete m_pLockFile;
m_pLockFile = pFile;
CFile& File = *pFile;
if (!config.Parse(File, sError)) {
CUtils::PrintStatus(false, sError);
return false;
}
CUtils::PrintStatus(true);
// check if config is from old ZNC version and
// create a backup file if necessary
CString sSavedVersion;
config.FindStringEntry("version", sSavedVersion);
if (sSavedVersion.empty()) {
CUtils::PrintError(
"Config does not contain a version identifier. It may be be too "
"old or corrupt.");
return false;
}
tuple<unsigned int, unsigned int> tSavedVersion =
make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(),
sSavedVersion.Token(1, false, ".").ToUInt());
tuple<unsigned int, unsigned int> tCurrentVersion =
make_tuple(VERSION_MAJOR, VERSION_MINOR);
if (tSavedVersion < tCurrentVersion) {
CUtils::PrintMessage("Found old config from ZNC " + sSavedVersion +
". Saving a backup of it.");
BackupConfigOnce("pre-" + CString(VERSION_STR));
} else if (tSavedVersion > tCurrentVersion) {
CUtils::PrintError("Config was saved from ZNC " + sSavedVersion +
". It may or may not work with current ZNC " +
GetVersion());
}
return true;
}
bool CZNC::RehashConfig(CString& sError) {
ALLMODULECALL(OnPreRehash(), NOTHING);
CConfig config;
if (!ReadConfig(config, sError)) return false;
if (!LoadGlobal(config, sError)) return false;
// do not reload users - it's dangerous!
ALLMODULECALL(OnPostRehash(), NOTHING);
return true;
}
bool CZNC::LoadGlobal(CConfig& config, CString& sError) {
sError.clear();
MCString msModules; // Modules are queued for later loading
VCString vsList;
config.FindStringVector("loadmodule", vsList);
for (const CString& sModLine : vsList) {
CString sModName = sModLine.Token(0);
CString sArgs = sModLine.Token(1, true);
// compatibility for pre-1.0 configs
CString sSavedVersion;
config.FindStringEntry("version", sSavedVersion);
tuple<unsigned int, unsigned int> tSavedVersion =
make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(),
sSavedVersion.Token(1, false, ".").ToUInt());
if (sModName == "saslauth" && tSavedVersion < make_tuple(0, 207)) {
CUtils::PrintMessage(
"saslauth module was renamed to cyrusauth. Loading cyrusauth "
"instead.");
sModName = "cyrusauth";
}
// end-compatibility for pre-1.0 configs
if (msModules.find(sModName) != msModules.end()) {
sError = "Module [" + sModName + "] already loaded";
CUtils::PrintError(sError);
return false;
}
CString sModRet;
CModule* pOldMod;
pOldMod = GetModules().FindModule(sModName);
if (!pOldMod) {
CUtils::PrintAction("Loading global module [" + sModName + "]");
bool bModRet =
GetModules().LoadModule(sModName, sArgs, CModInfo::GlobalModule,
nullptr, nullptr, sModRet);
CUtils::PrintStatus(bModRet, bModRet ? "" : sModRet);
if (!bModRet) {
sError = sModRet;
return false;
}
} else if (pOldMod->GetArgs() != sArgs) {
CUtils::PrintAction("Reloading global module [" + sModName + "]");
bool bModRet = GetModules().ReloadModule(sModName, sArgs, nullptr,
nullptr, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
sError = sModRet;
return false;
}
} else
CUtils::PrintMessage("Module [" + sModName + "] already loaded.");
msModules[sModName] = sArgs;
}
m_vsMotd.clear();
config.FindStringVector("motd", vsList);
for (const CString& sMotd : vsList) {
AddMotd(sMotd);
}
if (config.FindStringVector("bindhost", vsList)) {
CUtils::PrintStatus(false,
"WARNING: the global BindHost list is deprecated. "
"Ignoring the following lines:");
for (const CString& sHost : vsList) {
CUtils::PrintStatus(false, "BindHost = " + sHost);
}
}
if (config.FindStringVector("vhost", vsList)) {
CUtils::PrintStatus(false,
"WARNING: the global vHost list is deprecated. "
"Ignoring the following lines:");
for (const CString& sHost : vsList) {
CUtils::PrintStatus(false, "vHost = " + sHost);
}
}
m_vsTrustedProxies.clear();
config.FindStringVector("trustedproxy", vsList);
for (const CString& sProxy : vsList) {
AddTrustedProxy(sProxy);
}
CString sVal;
if (config.FindStringEntry("pidfile", sVal)) m_sPidFile = sVal;
if (config.FindStringEntry("statusprefix", sVal)) m_sStatusPrefix = sVal;
if (config.FindStringEntry("sslcertfile", sVal)) m_sSSLCertFile = sVal;
if (config.FindStringEntry("sslkeyfile", sVal)) m_sSSLKeyFile = sVal;
if (config.FindStringEntry("ssldhparamfile", sVal))
m_sSSLDHParamFile = sVal;
if (config.FindStringEntry("sslciphers", sVal)) m_sSSLCiphers = sVal;
if (config.FindStringEntry("skin", sVal)) SetSkinName(sVal);
if (config.FindStringEntry("connectdelay", sVal))
SetConnectDelay(sVal.ToUInt());
if (config.FindStringEntry("serverthrottle", sVal))
m_sConnectThrottle.SetTTL(sVal.ToUInt() * 1000);
if (config.FindStringEntry("anoniplimit", sVal))
m_uiAnonIPLimit = sVal.ToUInt();
if (config.FindStringEntry("maxbuffersize", sVal))
m_uiMaxBufferSize = sVal.ToUInt();
if (config.FindStringEntry("protectwebsessions", sVal))
m_bProtectWebSessions = sVal.ToBool();
if (config.FindStringEntry("hideversion", sVal))
m_bHideVersion = sVal.ToBool();
if (config.FindStringEntry("authonlyviamodule", sVal))
m_bAuthOnlyViaModule = sVal.ToBool();
if (config.FindStringEntry("sslprotocols", sVal)) {
if (!SetSSLProtocols(sVal)) {
VCString vsProtocols = GetAvailableSSLProtocols();
CUtils::PrintError("Invalid SSLProtocols value [" + sVal + "]");
CUtils::PrintError(
"The syntax is [SSLProtocols = [+|-]<protocol> ...]");
CUtils::PrintError(
"Available protocols are [" +
CString(", ").Join(vsProtocols.begin(), vsProtocols.end()) +
"]");
return false;
}
}
if (config.FindStringEntry("configwritedelay", sVal))
m_uiConfigWriteDelay = sVal.ToUInt();
UnloadRemovedModules(msModules);
if (!LoadListeners(config, sError)) return false;
return true;
}
bool CZNC::LoadUsers(CConfig& config, CString& sError) {
sError.clear();
m_msUsers.clear();
CConfig::SubConfig subConf;
config.FindSubConfig("user", subConf);
for (const auto& subIt : subConf) {
const CString& sUserName = subIt.first;
CConfig* pSubConf = subIt.second.m_pSubConfig;
CUtils::PrintMessage("Loading user [" + sUserName + "]");
std::unique_ptr<CUser> pUser(new CUser(sUserName));
if (!m_sStatusPrefix.empty()) {
if (!pUser->SetStatusPrefix(m_sStatusPrefix)) {
sError = "Invalid StatusPrefix [" + m_sStatusPrefix +
"] Must be 1-5 chars, no spaces.";
CUtils::PrintError(sError);
return false;
}
}
if (!pUser->ParseConfig(pSubConf, sError)) {
CUtils::PrintError(sError);
return false;
}
if (!pSubConf->empty()) {
sError = "Unhandled lines in config for User [" + sUserName + "]!";
CUtils::PrintError(sError);
DumpConfig(pSubConf);
return false;
}
CString sErr;
if (!AddUser(pUser.release(), sErr, true)) {
sError = "Invalid user [" + sUserName + "] " + sErr;
}
if (!sError.empty()) {
CUtils::PrintError(sError);
pUser->SetBeingDeleted(true);
return false;
}
}
if (m_msUsers.empty()) {
sError = "You must define at least one user in your config.";
CUtils::PrintError(sError);
return false;
}
return true;
}
bool CZNC::LoadListeners(CConfig& config, CString& sError) {
sError.clear();
// Delete all listeners
while (!m_vpListeners.empty()) {
delete m_vpListeners[0];
m_vpListeners.erase(m_vpListeners.begin());
}
// compatibility for pre-1.0 configs
const char* szListenerEntries[] = {"listen", "listen6", "listen4",
"listener", "listener6", "listener4"};
VCString vsList;
config.FindStringVector("loadmodule", vsList);
// This has to be after SSLCertFile is handled since it uses that value
for (const char* szEntry : szListenerEntries) {
config.FindStringVector(szEntry, vsList);
for (const CString& sListener : vsList) {
if (!AddListener(szEntry + CString(" ") + sListener, sError))
return false;
}
}
// end-compatibility for pre-1.0 configs
CConfig::SubConfig subConf;
config.FindSubConfig("listener", subConf);
for (const auto& subIt : subConf) {
CConfig* pSubConf = subIt.second.m_pSubConfig;
if (!AddListener(pSubConf, sError)) return false;
if (!pSubConf->empty()) {
sError = "Unhandled lines in Listener config!";
CUtils::PrintError(sError);
CZNC::DumpConfig(pSubConf);
return false;
}
}
if (m_vpListeners.empty()) {
sError = "You must supply at least one Listener in your config.";
CUtils::PrintError(sError);
return false;
}
return true;
}
void CZNC::UnloadRemovedModules(const MCString& msModules) {
// unload modules which are no longer in the config
set<CString> ssUnload;
for (CModule* pCurMod : GetModules()) {
if (msModules.find(pCurMod->GetModName()) == msModules.end())
ssUnload.insert(pCurMod->GetModName());
}
for (const CString& sMod : ssUnload) {
if (GetModules().UnloadModule(sMod))
CUtils::PrintMessage("Unloaded global module [" + sMod + "]");
else
CUtils::PrintMessage("Could not unload [" + sMod + "]");
}
}
void CZNC::DumpConfig(const CConfig* pConfig) {
CConfig::EntryMapIterator eit = pConfig->BeginEntries();
for (; eit != pConfig->EndEntries(); ++eit) {
const CString& sKey = eit->first;
const VCString& vsList = eit->second;
VCString::const_iterator it = vsList.begin();
for (; it != vsList.end(); ++it) {
CUtils::PrintError(sKey + " = " + *it);
}
}
CConfig::SubConfigMapIterator sit = pConfig->BeginSubConfigs();
for (; sit != pConfig->EndSubConfigs(); ++sit) {
const CString& sKey = sit->first;
const CConfig::SubConfig& sSub = sit->second;
CConfig::SubConfig::const_iterator it = sSub.begin();
for (; it != sSub.end(); ++it) {
CUtils::PrintError("SubConfig [" + sKey + " " + it->first + "]:");
DumpConfig(it->second.m_pSubConfig);
}
}
}
void CZNC::ClearTrustedProxies() { m_vsTrustedProxies.clear(); }
bool CZNC::AddTrustedProxy(const CString& sHost) {
if (sHost.empty()) {
return false;
}
for (const CString& sTrustedProxy : m_vsTrustedProxies) {
if (sTrustedProxy.Equals(sHost)) {
return false;
}
}
m_vsTrustedProxies.push_back(sHost);
return true;
}
bool CZNC::RemTrustedProxy(const CString& sHost) {
VCString::iterator it;
for (it = m_vsTrustedProxies.begin(); it != m_vsTrustedProxies.end();
++it) {
if (sHost.Equals(*it)) {
m_vsTrustedProxies.erase(it);
return true;
}
}
return false;
}
void CZNC::Broadcast(const CString& sMessage, bool bAdminOnly, CUser* pSkipUser,
CClient* pSkipClient) {
for (const auto& it : m_msUsers) {
if (bAdminOnly && !it.second->IsAdmin()) continue;
if (it.second != pSkipUser) {
// TODO: translate message to user's language
CString sMsg = sMessage;
bool bContinue = false;
USERMODULECALL(OnBroadcast(sMsg), it.second, nullptr, &bContinue);
if (bContinue) continue;
it.second->PutStatusNotice("*** " + sMsg, nullptr, pSkipClient);
}
}
}
CModule* CZNC::FindModule(const CString& sModName, const CString& sUsername) {
if (sUsername.empty()) {
return CZNC::Get().GetModules().FindModule(sModName);
}
CUser* pUser = FindUser(sUsername);
return (!pUser) ? nullptr : pUser->GetModules().FindModule(sModName);
}
CModule* CZNC::FindModule(const CString& sModName, CUser* pUser) {
if (pUser) {
return pUser->GetModules().FindModule(sModName);
}
return CZNC::Get().GetModules().FindModule(sModName);
}
bool CZNC::UpdateModule(const CString& sModule) {
CModule* pModule;
map<CUser*, CString> musLoaded;
map<CIRCNetwork*, CString> mnsLoaded;
// Unload the module for every user and network
for (const auto& it : m_msUsers) {
CUser* pUser = it.second;
pModule = pUser->GetModules().FindModule(sModule);
if (pModule) {
musLoaded[pUser] = pModule->GetArgs();
pUser->GetModules().UnloadModule(sModule);
}
// See if the user has this module loaded to a network
vector<CIRCNetwork*> vNetworks = pUser->GetNetworks();
for (CIRCNetwork* pNetwork : vNetworks) {
pModule = pNetwork->GetModules().FindModule(sModule);
if (pModule) {
mnsLoaded[pNetwork] = pModule->GetArgs();
pNetwork->GetModules().UnloadModule(sModule);
}
}
}
// Unload the global module
bool bGlobal = false;
CString sGlobalArgs;
pModule = GetModules().FindModule(sModule);
if (pModule) {
bGlobal = true;
sGlobalArgs = pModule->GetArgs();
GetModules().UnloadModule(sModule);
}
// Lets reload everything
bool bError = false;
CString sErr;
// Reload the global module
if (bGlobal) {
if (!GetModules().LoadModule(sModule, sGlobalArgs,
CModInfo::GlobalModule, nullptr, nullptr,
sErr)) {
DEBUG("Failed to reload [" << sModule << "] globally [" << sErr
<< "]");
bError = true;
}
}
// Reload the module for all users
for (const auto& it : musLoaded) {
CUser* pUser = it.first;
const CString& sArgs = it.second;
if (!pUser->GetModules().LoadModule(
sModule, sArgs, CModInfo::UserModule, pUser, nullptr, sErr)) {
DEBUG("Failed to reload [" << sModule << "] for ["
<< pUser->GetUserName() << "] [" << sErr
<< "]");
bError = true;
}
}
// Reload the module for all networks
for (const auto& it : mnsLoaded) {
CIRCNetwork* pNetwork = it.first;
const CString& sArgs = it.second;
if (!pNetwork->GetModules().LoadModule(
sModule, sArgs, CModInfo::NetworkModule, pNetwork->GetUser(),
pNetwork, sErr)) {
DEBUG("Failed to reload ["
<< sModule << "] for [" << pNetwork->GetUser()->GetUserName()
<< "/" << pNetwork->GetName() << "] [" << sErr << "]");
bError = true;
}
}
return !bError;
}
CUser* CZNC::FindUser(const CString& sUsername) {
map<CString, CUser*>::iterator it = m_msUsers.find(sUsername);
if (it != m_msUsers.end()) {
return it->second;
}
return nullptr;
}
bool CZNC::DeleteUser(const CString& sUsername) {
CUser* pUser = FindUser(sUsername);
if (!pUser) {
return false;
}
m_msDelUsers[pUser->GetUserName()] = pUser;
return true;
}
bool CZNC::AddUser(CUser* pUser, CString& sErrorRet, bool bStartup) {
if (FindUser(pUser->GetUserName()) != nullptr) {
sErrorRet = t_s("User already exists");
DEBUG("User [" << pUser->GetUserName() << "] - already exists");
return false;
}
if (!pUser->IsValid(sErrorRet)) {
DEBUG("Invalid user [" << pUser->GetUserName() << "] - [" << sErrorRet
<< "]");
return false;
}
bool bFailed = false;
// do not call OnAddUser hook during ZNC startup
if (!bStartup) {
GLOBALMODULECALL(OnAddUser(*pUser, sErrorRet), &bFailed);
}
if (bFailed) {
DEBUG("AddUser [" << pUser->GetUserName() << "] aborted by a module ["
<< sErrorRet << "]");
return false;
}
m_msUsers[pUser->GetUserName()] = pUser;
return true;
}
CListener* CZNC::FindListener(u_short uPort, const CString& sBindHost,
EAddrType eAddr) {
for (CListener* pListener : m_vpListeners) {
if (pListener->GetPort() != uPort) continue;
if (pListener->GetBindHost() != sBindHost) continue;
if (pListener->GetAddrType() != eAddr) continue;
return pListener;
}
return nullptr;
}
bool CZNC::AddListener(const CString& sLine, CString& sError) {
CString sName = sLine.Token(0);
CString sValue = sLine.Token(1, true);
EAddrType eAddr = ADDR_ALL;
if (sName.Equals("Listen4") || sName.Equals("Listen") ||
sName.Equals("Listener4")) {
eAddr = ADDR_IPV4ONLY;
}
if (sName.Equals("Listener6")) {
eAddr = ADDR_IPV6ONLY;
}
CListener::EAcceptType eAccept = CListener::ACCEPT_ALL;
if (sValue.TrimPrefix("irc_only "))
eAccept = CListener::ACCEPT_IRC;
else if (sValue.TrimPrefix("web_only "))
eAccept = CListener::ACCEPT_HTTP;
bool bSSL = false;
CString sPort;
CString sBindHost;
if (ADDR_IPV4ONLY == eAddr) {
sValue.Replace(":", " ");
}
if (sValue.Contains(" ")) {
sBindHost = sValue.Token(0, false, " ");
sPort = sValue.Token(1, true, " ");
} else {
sPort = sValue;
}
if (sPort.TrimPrefix("+")) {
bSSL = true;
}
// No support for URIPrefix for old-style configs.
CString sURIPrefix;
unsigned short uPort = sPort.ToUShort();
return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept,
sError);
}
bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost,
const CString& sURIPrefixRaw, bool bSSL, EAddrType eAddr,
CListener::EAcceptType eAccept, CString& sError) {
CString sHostComment;
if (!sBindHost.empty()) {
sHostComment = " on host [" + sBindHost + "]";
}
CString sIPV6Comment;
switch (eAddr) {
case ADDR_ALL:
sIPV6Comment = "";
break;
case ADDR_IPV4ONLY:
sIPV6Comment = " using ipv4";
break;
case ADDR_IPV6ONLY:
sIPV6Comment = " using ipv6";
}
CUtils::PrintAction("Binding to port [" + CString((bSSL) ? "+" : "") +
CString(uPort) + "]" + sHostComment + sIPV6Comment);
#ifndef HAVE_IPV6
if (ADDR_IPV6ONLY == eAddr) {
sError = t_s("IPv6 is not enabled");
CUtils::PrintStatus(false, sError);
return false;
}
#endif
#ifndef HAVE_LIBSSL
if (bSSL) {
sError = t_s("SSL is not enabled");
CUtils::PrintStatus(false, sError);
return false;
}
#else
CString sPemFile = GetPemLocation();
if (bSSL && !CFile::Exists(sPemFile)) {
sError = t_f("Unable to locate pem file: {1}")(sPemFile);
CUtils::PrintStatus(false, sError);
// If stdin is e.g. /dev/null and we call GetBoolInput(),
// we are stuck in an endless loop!
if (isatty(0) &&
CUtils::GetBoolInput("Would you like to create a new pem file?",
true)) {
sError.clear();
WritePemFile();
} else {
return false;
}
CUtils::PrintAction("Binding to port [+" + CString(uPort) + "]" +
sHostComment + sIPV6Comment);
}
#endif
if (!uPort) {
sError = t_s("Invalid port");
CUtils::PrintStatus(false, sError);
return false;
}
// URIPrefix must start with a slash and end without one.
CString sURIPrefix = CString(sURIPrefixRaw);
if (!sURIPrefix.empty()) {
if (!sURIPrefix.StartsWith("/")) {
sURIPrefix = "/" + sURIPrefix;
}
if (sURIPrefix.EndsWith("/")) {
sURIPrefix.TrimRight("/");
}
}
CListener* pListener =
new CListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept);
if (!pListener->Listen()) {
sError = FormatBindError();
CUtils::PrintStatus(false, sError);
delete pListener;
return false;
}
m_vpListeners.push_back(pListener);
CUtils::PrintStatus(true);
return true;
}
bool CZNC::AddListener(CConfig* pConfig, CString& sError) {
CString sBindHost;
CString sURIPrefix;
bool bSSL;
bool b4;
#ifdef HAVE_IPV6
bool b6 = true;
#else
bool b6 = false;
#endif
bool bIRC;
bool bWeb;
unsigned short uPort;
if (!pConfig->FindUShortEntry("port", uPort)) {
sError = "No port given";
CUtils::PrintError(sError);
return false;
}
pConfig->FindStringEntry("host", sBindHost);
pConfig->FindBoolEntry("ssl", bSSL, false);
pConfig->FindBoolEntry("ipv4", b4, true);
pConfig->FindBoolEntry("ipv6", b6, b6);
pConfig->FindBoolEntry("allowirc", bIRC, true);
pConfig->FindBoolEntry("allowweb", bWeb, true);
pConfig->FindStringEntry("uriprefix", sURIPrefix);
EAddrType eAddr;
if (b4 && b6) {
eAddr = ADDR_ALL;
} else if (b4 && !b6) {
eAddr = ADDR_IPV4ONLY;
} else if (!b4 && b6) {
eAddr = ADDR_IPV6ONLY;
} else {
sError = "No address family given";
CUtils::PrintError(sError);
return false;
}
CListener::EAcceptType eAccept;
if (bIRC && bWeb) {
eAccept = CListener::ACCEPT_ALL;
} else if (bIRC && !bWeb) {
eAccept = CListener::ACCEPT_IRC;
} else if (!bIRC && bWeb) {
eAccept = CListener::ACCEPT_HTTP;
} else {
sError = "Either Web or IRC or both should be selected";
CUtils::PrintError(sError);
return false;
}
return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept,
sError);
}
bool CZNC::AddListener(CListener* pListener) {
if (!pListener->GetRealListener()) {
// Listener doesn't actually listen
delete pListener;
return false;
}
// We don't check if there is an identical listener already listening
// since one can't listen on e.g. the same port multiple times
m_vpListeners.push_back(pListener);
return true;
}
bool CZNC::DelListener(CListener* pListener) {
auto it = std::find(m_vpListeners.begin(), m_vpListeners.end(), pListener);
if (it != m_vpListeners.end()) {
m_vpListeners.erase(it);
delete pListener;
return true;
}
return false;
}
CString CZNC::FormatBindError() {
CString sError = (errno == 0 ? t_s(("unknown error, check the host name"))
: CString(strerror(errno)));
return t_f("Unable to bind: {1}")(sError);
}
static CZNC* s_pZNC = nullptr;
void CZNC::CreateInstance() {
if (s_pZNC) abort();
s_pZNC = new CZNC();
}
CZNC& CZNC::Get() { return *s_pZNC; }
void CZNC::DestroyInstance() {
delete s_pZNC;
s_pZNC = nullptr;
}
CZNC::TrafficStatsMap CZNC::GetTrafficStats(TrafficStatsPair& Users,
TrafficStatsPair& ZNC,
TrafficStatsPair& Total) {
TrafficStatsMap ret;
unsigned long long uiUsers_in, uiUsers_out, uiZNC_in, uiZNC_out;
const map<CString, CUser*>& msUsers = CZNC::Get().GetUserMap();
uiUsers_in = uiUsers_out = 0;
uiZNC_in = BytesRead();
uiZNC_out = BytesWritten();
for (const auto& it : msUsers) {
ret[it.first] =
TrafficStatsPair(it.second->BytesRead(), it.second->BytesWritten());
uiUsers_in += it.second->BytesRead();
uiUsers_out += it.second->BytesWritten();
}
for (Csock* pSock : m_Manager) {
CUser* pUser = nullptr;
if (pSock->GetSockName().StartsWith("IRC::")) {
pUser = ((CIRCSock*)pSock)->GetNetwork()->GetUser();
} else if (pSock->GetSockName().StartsWith("USR::")) {
pUser = ((CClient*)pSock)->GetUser();
}
if (pUser) {
ret[pUser->GetUserName()].first += pSock->GetBytesRead();
ret[pUser->GetUserName()].second += pSock->GetBytesWritten();
uiUsers_in += pSock->GetBytesRead();
uiUsers_out += pSock->GetBytesWritten();
} else {
uiZNC_in += pSock->GetBytesRead();
uiZNC_out += pSock->GetBytesWritten();
}
}
Users = TrafficStatsPair(uiUsers_in, uiUsers_out);
ZNC = TrafficStatsPair(uiZNC_in, uiZNC_out);
Total = TrafficStatsPair(uiUsers_in + uiZNC_in, uiUsers_out + uiZNC_out);
return ret;
}
CZNC::TrafficStatsMap CZNC::GetNetworkTrafficStats(const CString& sUsername,
TrafficStatsPair& Total) {
TrafficStatsMap Networks;
CUser* pUser = FindUser(sUsername);
if (pUser) {
for (const CIRCNetwork* pNetwork : pUser->GetNetworks()) {
Networks[pNetwork->GetName()].first = pNetwork->BytesRead();
Networks[pNetwork->GetName()].second = pNetwork->BytesWritten();
Total.first += pNetwork->BytesRead();
Total.second += pNetwork->BytesWritten();
}
for (Csock* pSock : m_Manager) {
CIRCNetwork* pNetwork = nullptr;
if (pSock->GetSockName().StartsWith("IRC::")) {
pNetwork = ((CIRCSock*)pSock)->GetNetwork();
} else if (pSock->GetSockName().StartsWith("USR::")) {
pNetwork = ((CClient*)pSock)->GetNetwork();
}
if (pNetwork && pNetwork->GetUser() == pUser) {
Networks[pNetwork->GetName()].first = pSock->GetBytesRead();
Networks[pNetwork->GetName()].second = pSock->GetBytesWritten();
Total.first += pSock->GetBytesRead();
Total.second += pSock->GetBytesWritten();
}
}
}
return Networks;
}
void CZNC::AuthUser(std::shared_ptr<CAuthBase> AuthClass) {
// TODO unless the auth module calls it, CUser::IsHostAllowed() is not
// honoured
bool bReturn = false;
GLOBALMODULECALL(OnLoginAttempt(AuthClass), &bReturn);
if (bReturn) return;
CUser* pUser = FindUser(AuthClass->GetUsername());
if (!pUser || !pUser->CheckPass(AuthClass->GetPassword())) {
AuthClass->RefuseLogin("Invalid Password");
return;
}
CString sHost = AuthClass->GetRemoteIP();
if (!pUser->IsHostAllowed(sHost)) {
AuthClass->RefuseLogin("Your host [" + sHost + "] is not allowed");
return;
}
AuthClass->AcceptLogin(*pUser);
}
class CConnectQueueTimer : public CCron {
public:
CConnectQueueTimer(int iSecs) : CCron() {
SetName("Connect users");
Start(iSecs);
// Don't wait iSecs seconds for first timer run
m_bRunOnNextCall = true;
}
~CConnectQueueTimer() override {
// This is only needed when ZNC shuts down:
// CZNC::~CZNC() sets its CConnectQueueTimer pointer to nullptr and
// calls the manager's Cleanup() which destroys all sockets and
// timers. If something calls CZNC::EnableConnectQueue() here
// (e.g. because a CIRCSock is destroyed), the socket manager
// deletes that timer almost immediately, but CZNC now got a
// dangling pointer to this timer which can crash later on.
//
// Unlikely but possible ;)
CZNC::Get().LeakConnectQueueTimer(this);
}
protected:
void RunJob() override {
list<CIRCNetwork*> ConnectionQueue;
list<CIRCNetwork*>& RealConnectionQueue =
CZNC::Get().GetConnectionQueue();
// Problem: If a network can't connect right now because e.g. it
// is throttled, it will re-insert itself into the connection
// queue. However, we must only give each network a single
// chance during this timer run.
//
// Solution: We move the connection queue to our local list at
// the beginning and work from that.
ConnectionQueue.swap(RealConnectionQueue);
while (!ConnectionQueue.empty()) {
CIRCNetwork* pNetwork = ConnectionQueue.front();
ConnectionQueue.pop_front();
if (pNetwork->Connect()) {
break;
}
}
/* Now re-insert anything that is left in our local list into
* the real connection queue.
*/
RealConnectionQueue.splice(RealConnectionQueue.begin(),
ConnectionQueue);
if (RealConnectionQueue.empty()) {
DEBUG("ConnectQueueTimer done");
CZNC::Get().DisableConnectQueue();
}
}
};
void CZNC::SetConnectDelay(unsigned int i) {
if (i < 1) {
// Don't hammer server with our failed connects
i = 1;
}
if (m_uiConnectDelay != i && m_pConnectQueueTimer != nullptr) {
m_pConnectQueueTimer->Start(i);
}
m_uiConnectDelay = i;
}
VCString CZNC::GetAvailableSSLProtocols() {
// NOTE: keep in sync with SetSSLProtocols()
return {"SSLv2", "SSLv3", "TLSv1", "TLSV1.1", "TLSv1.2"};
}
bool CZNC::SetSSLProtocols(const CString& sProtocols) {
VCString vsProtocols;
sProtocols.Split(" ", vsProtocols, false, "", "", true, true);
unsigned int uDisabledProtocols = Csock::EDP_SSL;
for (CString& sProtocol : vsProtocols) {
unsigned int uFlag = 0;
bool bEnable = sProtocol.TrimPrefix("+");
bool bDisable = sProtocol.TrimPrefix("-");
// NOTE: keep in sync with GetAvailableSSLProtocols()
if (sProtocol.Equals("All")) {
uFlag = ~0;
} else if (sProtocol.Equals("SSLv2")) {
uFlag = Csock::EDP_SSLv2;
} else if (sProtocol.Equals("SSLv3")) {
uFlag = Csock::EDP_SSLv3;
} else if (sProtocol.Equals("TLSv1")) {
uFlag = Csock::EDP_TLSv1;
} else if (sProtocol.Equals("TLSv1.1")) {
uFlag = Csock::EDP_TLSv1_1;
} else if (sProtocol.Equals("TLSv1.2")) {
uFlag = Csock::EDP_TLSv1_2;
} else {
return false;
}
if (bEnable) {
uDisabledProtocols &= ~uFlag;
} else if (bDisable) {
uDisabledProtocols |= uFlag;
} else {
uDisabledProtocols = ~uFlag;
}
}
m_sSSLProtocols = sProtocols;
m_uDisabledSSLProtocols = uDisabledProtocols;
return true;
}
void CZNC::EnableConnectQueue() {
if (!m_pConnectQueueTimer && !m_uiConnectPaused &&
!m_lpConnectQueue.empty()) {
m_pConnectQueueTimer = new CConnectQueueTimer(m_uiConnectDelay);
GetManager().AddCron(m_pConnectQueueTimer);
}
}
void CZNC::DisableConnectQueue() {
if (m_pConnectQueueTimer) {
// This will kill the cron
m_pConnectQueueTimer->Stop();
m_pConnectQueueTimer = nullptr;
}
}
void CZNC::PauseConnectQueue() {
DEBUG("Connection queue paused");
m_uiConnectPaused++;
if (m_pConnectQueueTimer) {
m_pConnectQueueTimer->Pause();
}
}
void CZNC::ResumeConnectQueue() {
DEBUG("Connection queue resumed");
m_uiConnectPaused--;
EnableConnectQueue();
if (m_pConnectQueueTimer) {
m_pConnectQueueTimer->UnPause();
}
}
void CZNC::ForceEncoding() {
m_uiForceEncoding++;
#ifdef HAVE_ICU
for (Csock* pSock : GetManager()) {
pSock->SetEncoding(FixupEncoding(pSock->GetEncoding()));
}
#endif
}
void CZNC::UnforceEncoding() { m_uiForceEncoding--; }
bool CZNC::IsForcingEncoding() const { return m_uiForceEncoding; }
CString CZNC::FixupEncoding(const CString& sEncoding) const {
if (!m_uiForceEncoding) {
return sEncoding;
}
if (sEncoding.empty()) {
return "UTF-8";
}
const char* sRealEncoding = sEncoding.c_str();
if (sEncoding[0] == '*' || sEncoding[0] == '^') {
sRealEncoding++;
}
if (!*sRealEncoding) {
return "UTF-8";
}
#ifdef HAVE_ICU
UErrorCode e = U_ZERO_ERROR;
UConverter* cnv = ucnv_open(sRealEncoding, &e);
if (cnv) {
ucnv_close(cnv);
}
if (U_FAILURE(e)) {
return "UTF-8";
}
#endif
return sEncoding;
}
void CZNC::AddNetworkToQueue(CIRCNetwork* pNetwork) {
// Make sure we are not already in the queue
if (std::find(m_lpConnectQueue.begin(), m_lpConnectQueue.end(), pNetwork) !=
m_lpConnectQueue.end()) {
return;
}
m_lpConnectQueue.push_back(pNetwork);
EnableConnectQueue();
}
void CZNC::LeakConnectQueueTimer(CConnectQueueTimer* pTimer) {
if (m_pConnectQueueTimer == pTimer) m_pConnectQueueTimer = nullptr;
}
bool CZNC::WaitForChildLock() { return m_pLockFile && m_pLockFile->ExLock(); }
void CZNC::DisableConfigTimer() {
if (m_pConfigTimer) {
m_pConfigTimer->Stop();
m_pConfigTimer = nullptr;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1442_3 |
crossvul-cpp_data_good_1580_0 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: ParaNdis-Common.c
*
* This file contains NDIS driver procedures, common for NDIS5 and NDIS6
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
static VOID ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext);
static __inline pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue);
// TODO: remove when the problem solved
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue);
//#define ROUNDSIZE(sz) ((sz + 15) & ~15)
#define MAX_VLAN_ID 4095
#define ABSTRACT_PATHES_TAG 'APVR'
/**********************************************************
Validates MAC address
Valid MAC address is not broadcast, not multicast, not empty
if bLocal is set, it must be LOCAL
if not, is must be non-local or local
Parameters:
PUCHAR pcMacAddress - MAC address to validate
BOOLEAN bLocal - TRUE, if we validate locally administered address
Return value:
TRUE if valid
***********************************************************/
BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal)
{
BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE;
bBroadcast = ETH_IS_BROADCAST(pcMacAddress);
bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress);
bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress);
bEmpty = ETH_IS_EMPTY(pcMacAddress);
return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA);
}
typedef struct _tagConfigurationEntry
{
const char *Name;
ULONG ulValue;
ULONG ulMinimal;
ULONG ulMaximal;
}tConfigurationEntry;
typedef struct _tagConfigurationEntries
{
tConfigurationEntry PrioritySupport;
tConfigurationEntry ConnectRate;
tConfigurationEntry isLogEnabled;
tConfigurationEntry debugLevel;
tConfigurationEntry TxCapacity;
tConfigurationEntry RxCapacity;
tConfigurationEntry LogStatistics;
tConfigurationEntry OffloadTxChecksum;
tConfigurationEntry OffloadTxLSO;
tConfigurationEntry OffloadRxCS;
tConfigurationEntry stdIpcsV4;
tConfigurationEntry stdTcpcsV4;
tConfigurationEntry stdTcpcsV6;
tConfigurationEntry stdUdpcsV4;
tConfigurationEntry stdUdpcsV6;
tConfigurationEntry stdLsoV1;
tConfigurationEntry stdLsoV2ip4;
tConfigurationEntry stdLsoV2ip6;
tConfigurationEntry PriorityVlanTagging;
tConfigurationEntry VlanId;
tConfigurationEntry PublishIndices;
tConfigurationEntry MTU;
tConfigurationEntry NumberOfHandledRXPackersInDPC;
#if PARANDIS_SUPPORT_RSS
tConfigurationEntry RSSOffloadSupported;
tConfigurationEntry NumRSSQueues;
#endif
#if PARANDIS_SUPPORT_RSC
tConfigurationEntry RSCIPv4Supported;
tConfigurationEntry RSCIPv6Supported;
#endif
}tConfigurationEntries;
static const tConfigurationEntries defaultConfiguration =
{
{ "Priority", 0, 0, 1 },
{ "ConnectRate", 100,10,10000 },
{ "DoLog", 1, 0, 1 },
{ "DebugLevel", 2, 0, 8 },
{ "TxCapacity", 1024, 16, 1024 },
{ "RxCapacity", 256, 32, 1024 },
{ "LogStatistics", 0, 0, 10000},
{ "Offload.TxChecksum", 0, 0, 31},
{ "Offload.TxLSO", 0, 0, 2},
{ "Offload.RxCS", 0, 0, 31},
{ "*IPChecksumOffloadIPv4", 3, 0, 3 },
{ "*TCPChecksumOffloadIPv4",3, 0, 3 },
{ "*TCPChecksumOffloadIPv6",3, 0, 3 },
{ "*UDPChecksumOffloadIPv4",3, 0, 3 },
{ "*UDPChecksumOffloadIPv6",3, 0, 3 },
{ "*LsoV1IPv4", 1, 0, 1 },
{ "*LsoV2IPv4", 1, 0, 1 },
{ "*LsoV2IPv6", 1, 0, 1 },
{ "*PriorityVLANTag", 3, 0, 3},
{ "VlanId", 0, 0, MAX_VLAN_ID},
{ "PublishIndices", 1, 0, 1},
{ "MTU", 1500, 576, 65500},
{ "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000},
#if PARANDIS_SUPPORT_RSS
{ "*RSS", 1, 0, 1},
{ "*NumRssQueues", 8, 1, PARANDIS_RSS_MAX_RECEIVE_QUEUES},
#endif
#if PARANDIS_SUPPORT_RSC
{ "*RscIPv4", 1, 0, 1},
{ "*RscIPv6", 1, 0, 1},
#endif
};
static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext)
{
VirtIODeviceReset(pContext->IODevice);
DPrintf(0, ("[%s] Done\n", __FUNCTION__));
/* reset all the features in the device */
pContext->ulCurrentVlansFilterSet = 0;
}
/**********************************************************
Gets integer value for specifies in pEntry->Name name
Parameters:
NDIS_HANDLE cfg previously open configuration
tConfigurationEntry *pEntry - Entry to fill value in
***********************************************************/
static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry)
{
NDIS_STATUS status;
const char *statusName;
NDIS_STRING name = {0};
PNDIS_CONFIGURATION_PARAMETER pParam = NULL;
NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger;
NdisInitializeString(&name, (PUCHAR)pEntry->Name);
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadConfiguration(
&status,
&pParam,
cfg,
&name,
ParameterType);
if (status == NDIS_STATUS_SUCCESS)
{
ULONG ulValue = pParam->ParameterData.IntegerData;
if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal)
{
pEntry->ulValue = ulValue;
statusName = "value";
}
else
{
statusName = "out of range";
}
}
else
{
statusName = "nothing";
}
#pragma warning(pop)
DPrintf(2, ("[%s] %s read for %s - 0x%x\n",
__FUNCTION__,
statusName,
pEntry->Name,
pEntry->ulValue));
if (name.Buffer) NdisFreeString(name);
}
static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT4Lso)
{
DPrintf(0, ("[%s] Warning: %s", procname, reason));
pContext->Offload.flagsValue &= ~osbT4Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT6Lso)
{
DPrintf(0, ("[%s] Warning: %s\n", procname, reason));
pContext->Offload.flagsValue &= ~osbT6Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
/**********************************************************
Loads NIC parameters from adapter registry key
Parameters:
context
PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host
***********************************************************/
static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR pNewMACAddress)
{
NDIS_HANDLE cfg;
tConfigurationEntries *pConfiguration = (tConfigurationEntries *) ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries));
if (pConfiguration)
{
*pConfiguration = defaultConfiguration;
cfg = ParaNdis_OpenNICConfiguration(pContext);
if (cfg)
{
GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled);
GetConfigurationEntry(cfg, &pConfiguration->debugLevel);
GetConfigurationEntry(cfg, &pConfiguration->ConnectRate);
GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport);
GetConfigurationEntry(cfg, &pConfiguration->TxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->RxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->LogStatistics);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO);
GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS);
GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6);
GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging);
GetConfigurationEntry(cfg, &pConfiguration->VlanId);
GetConfigurationEntry(cfg, &pConfiguration->PublishIndices);
GetConfigurationEntry(cfg, &pConfiguration->MTU);
GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC);
#if PARANDIS_SUPPORT_RSS
GetConfigurationEntry(cfg, &pConfiguration->RSSOffloadSupported);
GetConfigurationEntry(cfg, &pConfiguration->NumRSSQueues);
#endif
#if PARANDIS_SUPPORT_RSC
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv4Supported);
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv6Supported);
#endif
bDebugPrint = pConfiguration->isLogEnabled.ulValue;
virtioDebugLevel = pConfiguration->debugLevel.ulValue;
pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue;
pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue;
pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue;
pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue;
pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0;
pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue;
pContext->ulFormalLinkSpeed *= 1000000;
pContext->Offload.flagsValue = 0;
// TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum;
if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp;
if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions;
// RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum;
/* full packet size that can be configured as GSO for VIRTIO is short */
/* NDIS test fails sometimes fails on segments 50-60K */
pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE;
pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue;
pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue;
pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue;
pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue;
pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue;
pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff;
pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue;
#if PARANDIS_SUPPORT_RSS
pContext->bRSSOffloadSupported = pConfiguration->RSSOffloadSupported.ulValue ? TRUE : FALSE;
pContext->RSSMaxQueuesNumber = (CCHAR) pConfiguration->NumRSSQueues.ulValue;
#endif
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4SupportedSW = (UCHAR)pConfiguration->RSCIPv4Supported.ulValue;
pContext->RSC.bIPv6SupportedSW = (UCHAR)pConfiguration->RSCIPv6Supported.ulValue;
#endif
if (!pContext->bDoSupportPriority)
pContext->ulPriorityVlanSetting = 0;
// if Vlan not supported
if (!IsVlanSupported(pContext)) {
pContext->VlanId = 0;
}
{
NDIS_STATUS status;
PVOID p;
UINT len = 0;
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadNetworkAddress(&status, &p, &len, cfg);
if (status == NDIS_STATUS_SUCCESS && len == ETH_LENGTH_OF_ADDRESS)
{
NdisMoveMemory(pNewMACAddress, p, len);
}
else if (len && len != ETH_LENGTH_OF_ADDRESS)
{
DPrintf(0, ("[%s] MAC address has wrong length of %d\n", __FUNCTION__, len));
}
else
{
DPrintf(4, ("[%s] Nothing read for MAC, error %X\n", __FUNCTION__, status));
}
#pragma warning(pop)
}
NdisCloseConfiguration(cfg);
}
NdisFreeMemory(pConfiguration, 0, 0);
}
}
void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from)
{
if (!pDest) pDest = &pContext->Offload.flags;
if (!from) from = &pContext->Offload.flagsValue;
pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum);
pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum);
pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum);
pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum);
pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum);
pDest->fTxLso = !!(*from & osbT4Lso);
pDest->fTxLsoIP = !!(*from & osbT4LsoIp);
pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp);
pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum);
pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum);
pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum);
pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum);
pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum);
pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum);
pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum);
pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum);
pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum);
pDest->fTxLsov6 = !!(*from & osbT6Lso);
pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt);
pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions);
pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum);
pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum);
pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum);
pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum);
}
/**********************************************************
Enumerates adapter resources and fills the structure holding them
Verifies that IO assigned and has correct size
Verifies that interrupt assigned
Parameters:
PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS
tAdapterResources *pResources - structure to fill
Return value:
TRUE if everything is OK
***********************************************************/
static BOOLEAN GetAdapterResources(PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources)
{
UINT i;
NdisZeroMemory(pResources, sizeof(*pResources));
for (i = 0; i < RList->Count; ++i)
{
ULONG type = RList->PartialDescriptors[i].Type;
if (type == CmResourceTypePort)
{
PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start;
ULONG len = RList->PartialDescriptors[i].u.Port.Length;
DPrintf(0, ("Found IO ports at %08lX(%d)\n", Start.LowPart, len));
pResources->ulIOAddress = Start.LowPart;
pResources->IOLength = len;
}
else if (type == CmResourceTypeInterrupt)
{
pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector;
pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level;
pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity;
pResources->InterruptFlags = RList->PartialDescriptors[i].Flags;
DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X\n",
pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags));
}
}
return pResources->ulIOAddress && pResources->Vector;
}
static void DumpVirtIOFeatures(PPARANDIS_ADAPTER pContext)
{
static const struct { ULONG bitmask; PCHAR Name; } Features[] =
{
{VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" },
{VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" },
{VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" },
{VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" },
{VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"},
{VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"},
{VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"},
{VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"},
{VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"},
{VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"},
{VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"},
{VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"},
{VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"},
{VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"},
{VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"},
{VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"},
{VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"},
{VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"},
{VIRTIO_NET_F_CTRL_MAC_ADDR, "VIRTIO_NET_F_CTRL_MAC_ADDR"},
{VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"},
{VIRTIO_F_ANY_LAYOUT, "VIRTIO_F_ANY_LAYOUT"},
{ VIRTIO_RING_F_EVENT_IDX, "VIRTIO_RING_F_EVENT_IDX" },
};
UINT i;
for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Features[i].bitmask))
{
DPrintf(0, ("VirtIO Host Feature %s\n", Features[i].Name));
}
}
}
static BOOLEAN
AckFeature(PPARANDIS_ADAPTER pContext, UINT32 Feature)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Feature))
{
VirtIOFeatureEnable(pContext->u32GuestFeatures, Feature);
return TRUE;
}
return FALSE;
}
/**********************************************************
Prints out statistics
***********************************************************/
static void PrintStatistics(PARANDIS_ADAPTER *pContext)
{
ULONG64 totalTxFrames =
pContext->Statistics.ifHCOutBroadcastPkts +
pContext->Statistics.ifHCOutMulticastPkts +
pContext->Statistics.ifHCOutUcastPkts;
ULONG64 totalRxFrames =
pContext->Statistics.ifHCInBroadcastPkts +
pContext->Statistics.ifHCInMulticastPkts +
pContext->Statistics.ifHCInUcastPkts;
#if 0 /* TODO - setup accessor functions*/
DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d\n",
pContext->CurrentMacAddress[5],
pContext->RXPath.m_NetNofReceiveBuffers,
pContext->NetMaxReceiveBuffers));
DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d\n",
pContext->TXPath.GetFreeTXDescriptors(),
pContext->maxFreeTxDescriptors,
pContext->TXPath.GetFreeHWBuffers()));
#endif
DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u\n",
pContext->Statistics.ifHCOutOctets,
pContext->Statistics.ifHCInOctets));
DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d\n",
totalTxFrames,
pContext->extraStatistics.framesCSOffload,
pContext->extraStatistics.framesLSO,
pContext->extraStatistics.framesIndirect));
DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d\n",
totalRxFrames, pContext->extraStatistics.framesRxPriority,
pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut));
if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood)
{
DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d\n",
pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood));
}
}
static
VOID InitializeRSCState(PPARANDIS_ADAPTER pContext)
{
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4Enabled = FALSE;
pContext->RSC.bIPv6Enabled = FALSE;
if(!pContext->bGuestChecksumSupported)
{
DPrintf(0, ("[%s] Guest TSO cannot be enabled without guest checksum\n", __FUNCTION__) );
return;
}
if(pContext->RSC.bIPv4SupportedSW)
{
pContext->RSC.bIPv4Enabled =
pContext->RSC.bIPv4SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO4);
}
else
{
pContext->RSC.bIPv4SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO4);
}
if(pContext->RSC.bIPv6SupportedSW)
{
pContext->RSC.bIPv6Enabled =
pContext->RSC.bIPv6SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO6);
}
else
{
pContext->RSC.bIPv6SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO6);
}
pContext->RSC.bHasDynamicConfig = (pContext->RSC.bIPv4Enabled || pContext->RSC.bIPv6Enabled) &&
AckFeature(pContext, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
DPrintf(0, ("[%s] Guest TSO state: IP4=%d, IP6=%d, Dynamic=%d\n", __FUNCTION__,
pContext->RSC.bIPv4Enabled, pContext->RSC.bIPv6Enabled, pContext->RSC.bHasDynamicConfig) );
#else
UNREFERENCED_PARAMETER(pContext);
#endif
}
static __inline void
DumpMac(int dbg_level, const char* header_str, UCHAR* mac)
{
DPrintf(dbg_level,("%s: %02x-%02x-%02x-%02x-%02x-%02x\n",
header_str, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]));
}
static __inline void
SetDeviceMAC(PPARANDIS_ADAPTER pContext, PUCHAR pDeviceMAC)
{
if(pContext->bCfgMACAddrSupported && !pContext->bCtrlMACAddrSupported)
{
VirtIODeviceSet(pContext->IODevice, 0, pDeviceMAC, ETH_LENGTH_OF_ADDRESS);
}
}
static void
InitializeMAC(PPARANDIS_ADAPTER pContext, PUCHAR pCurrentMAC)
{
//Acknowledge related features
pContext->bCfgMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_MAC);
pContext->bCtrlMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_CTRL_MAC_ADDR);
//Read and validate permanent MAC address
if (pContext->bCfgMACAddrSupported)
{
VirtIODeviceGet(pContext->IODevice, 0, &pContext->PermanentMacAddress, ETH_LENGTH_OF_ADDRESS);
if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE))
{
DumpMac(0, "Invalid device MAC ignored", pContext->PermanentMacAddress);
NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress));
}
}
if (ETH_IS_EMPTY(pContext->PermanentMacAddress))
{
pContext->PermanentMacAddress[0] = 0x02;
pContext->PermanentMacAddress[1] = 0x50;
pContext->PermanentMacAddress[2] = 0xF2;
pContext->PermanentMacAddress[3] = 0x00;
pContext->PermanentMacAddress[4] = 0x01;
pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF);
DumpMac(0, "No device MAC present, use default", pContext->PermanentMacAddress);
}
DumpMac(0, "Permanent device MAC", pContext->PermanentMacAddress);
//Read and validate configured MAC address
if (ParaNdis_ValidateMacAddress(pCurrentMAC, TRUE))
{
DPrintf(0, ("[%s] MAC address from configuration used\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pCurrentMAC);
}
else
{
DPrintf(0, ("No valid MAC configured\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pContext->PermanentMacAddress);
}
//If control channel message for MAC address configuration is not supported
// Configure device with actual MAC address via configurations space
//Else actual MAC address will be configured later via control queue
SetDeviceMAC(pContext, pContext->CurrentMacAddress);
DumpMac(0, "Actual MAC", pContext->CurrentMacAddress);
}
static __inline void
RestoreMAC(PPARANDIS_ADAPTER pContext)
{
SetDeviceMAC(pContext, pContext->PermanentMacAddress);
}
/**********************************************************
Initializes the context structure
Major variables, received from NDIS on initialization, must be be set before this call
(for ex. pContext->MiniportHandle)
If this procedure fails, no need to call
ParaNdis_CleanupContext
Parameters:
Return value:
SUCCESS, if resources are OK
NDIS_STATUS_RESOURCE_CONFLICT if not
***********************************************************/
NDIS_STATUS ParaNdis_InitializeContext(
PARANDIS_ADAPTER *pContext,
PNDIS_RESOURCE_LIST pResourceList)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
USHORT linkStatus = 0;
UCHAR CurrentMAC[ETH_LENGTH_OF_ADDRESS] = {0};
ULONG dependentOptions;
DEBUG_ENTRY(0);
ReadNicConfiguration(pContext, CurrentMAC);
pContext->fCurrentLinkState = MediaConnectStateUnknown;
pContext->powerState = NdisDeviceStateUnspecified;
pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS;
#if PARANDIS_SUPPORT_RSC
pContext->MaxPacketSize.nMaxDataSizeHwRx = MAX_HW_RX_PACKET_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = MAX_OS_RX_PACKET_SIZE;
#else
pContext->MaxPacketSize.nMaxDataSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = pContext->MaxPacketSize.nMaxFullSizeOS;
#endif
if (pContext->ulPriorityVlanSetting)
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
if (GetAdapterResources(pResourceList, &pContext->AdapterResources) &&
NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange(
&pContext->pIoPortOffset,
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength)
)
{
if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE)
{
DPrintf(0, ("[%s] Message interrupt assigned\n", __FUNCTION__));
pContext->bUsingMSIX = TRUE;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(*pContext->IODevice));
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER);
pContext->u32HostFeatures = VirtIODeviceReadHostFeatures(pContext->IODevice);
DumpVirtIOFeatures(pContext);
pContext->bLinkDetectSupported = AckFeature(pContext, VIRTIO_NET_F_STATUS);
if(pContext->bLinkDetectSupported) {
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0;
DPrintf(0, ("[%s] Link status on driver startup: %d\n", __FUNCTION__, pContext->bConnected));
}
InitializeMAC(pContext, CurrentMAC);
pContext->bUseMergedBuffers = AckFeature(pContext, VIRTIO_NET_F_MRG_RXBUF);
pContext->nVirtioHeaderSize = (pContext->bUseMergedBuffers) ? sizeof(virtio_net_hdr_ext) : sizeof(virtio_net_hdr_basic);
pContext->bDoPublishIndices = AckFeature(pContext, VIRTIO_RING_F_EVENT_IDX);
}
else
{
DPrintf(0, ("[%s] Error: Incomplete resources\n", __FUNCTION__));
/* avoid deregistering if failed */
pContext->AdapterResources.ulIOAddress = 0;
status = NDIS_STATUS_RESOURCE_CONFLICT;
}
pContext->bMultiQueue = AckFeature(pContext, VIRTIO_NET_F_CTRL_MQ);
if (pContext->bMultiQueue)
{
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS + sizeof(USHORT), &pContext->nHardwareQueues,
sizeof(pContext->nHardwareQueues));
}
else
{
pContext->nHardwareQueues = 1;
}
dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum;
if((pContext->Offload.flagsValue & dependentOptions) && !AckFeature(pContext, VIRTIO_NET_F_CSUM))
{
DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload\n", __FUNCTION__) );
pContext->Offload.flagsValue &= ~dependentOptions;
}
pContext->bGuestChecksumSupported = AckFeature(pContext, VIRTIO_NET_F_GUEST_CSUM);
AckFeature(pContext, VIRTIO_NET_F_CTRL_VQ);
InitializeRSCState(pContext);
// now, after we checked the capabilities, we can initialize current
// configuration of offload tasks
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
if (pContext->Offload.flags.fTxLso && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO4))
{
DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4\n");
}
if (pContext->Offload.flags.fTxLsov6 && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO6))
{
DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6");
}
pContext->bUseIndirect = AckFeature(pContext, VIRTIO_F_INDIRECT);
pContext->bAnyLaypout = AckFeature(pContext, VIRTIO_F_ANY_LAYOUT);
pContext->bHasHardwareFilters = AckFeature(pContext, VIRTIO_NET_F_CTRL_RX_EXTRA);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
NdisInitializeEvent(&pContext->ResetEvent);
DEBUG_EXIT_STATUS(0, status);
return status;
}
void ParaNdis_FreeRxBufferDescriptor(PARANDIS_ADAPTER *pContext, pRxNetDescriptor p)
{
ULONG i;
for(i = 0; i < p->PagesAllocated; i++)
{
ParaNdis_FreePhysicalMemory(pContext, &p->PhysicalPages[i]);
}
if(p->BufferSGArray) NdisFreeMemory(p->BufferSGArray, 0, 0);
if(p->PhysicalPages) NdisFreeMemory(p->PhysicalPages, 0, 0);
NdisFreeMemory(p, 0, 0);
}
/**********************************************************
Allocates maximum RX buffers for incoming packets
Buffers are chained in NetReceiveBuffers
Parameters:
context
***********************************************************/
void ParaNdis_DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa)
{
if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL);
*ppq = NULL;
if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa);
RtlZeroMemory(ppa, sizeof(*ppa));
}
#if PARANDIS_SUPPORT_RSS
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *pContext)
{
if (!pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] No MSIX, using 1 queue\n", __FUNCTION__));
return 1;
}
if (pContext->bMultiQueue)
{
DPrintf(0, ("[%s] Number of hardware queues = %d\n", __FUNCTION__, pContext->nHardwareQueues));
}
else
{
DPrintf(0, ("[%s] - CTRL_MQ not acked, # bindles set to 1\n", __FUNCTION__));
return 1;
}
ULONG lnProcessors;
#if NDIS_SUPPORT_NDIS620
lnProcessors = NdisGroupActiveProcessorCount(ALL_PROCESSOR_GROUPS);
#elif NDIS_SUPPORT_NDIS6
lnProcessors = NdisSystemProcessorCount();
#else
lnProcessors = 1;
#endif
ULONG lnMSIs = (pContext->pMSIXInfoTable->MessageCount - 1) / 2; /* RX/TX pairs + control queue*/
DPrintf(0, ("[%s] %lu CPUs reported\n", __FUNCTION__, lnProcessors));
DPrintf(0, ("[%s] %lu MSIs, %lu queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, lnMSIs));
USHORT nMSIs = USHORT(lnMSIs & 0xFFFF);
USHORT nProcessors = USHORT(lnProcessors & 0xFFFF);
DPrintf(0, ("[%s] %u CPUs reported\n", __FUNCTION__, nProcessors));
DPrintf(0, ("[%s] %lu MSIs, %u queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, nMSIs));
USHORT nBundles = (pContext->nHardwareQueues < nProcessors) ? pContext->nHardwareQueues : nProcessors;
nBundles = (nMSIs < nBundles) ? nMSIs : nBundles;
DPrintf(0, ("[%s] # of path bundles = %u\n", __FUNCTION__, nBundles));
return nBundles;
}
#else
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *)
{
return 1;
}
#endif
static NDIS_STATUS SetupDPCTarget(PARANDIS_ADAPTER *pContext)
{
ULONG i;
#if NDIS_SUPPORT_NDIS620
NDIS_STATUS status;
PROCESSOR_NUMBER procNumber;
#endif
for (i = 0; i < pContext->nPathBundles; i++)
{
#if NDIS_SUPPORT_NDIS620
status = KeGetProcessorNumberFromIndex(i, &procNumber);
if (status != NDIS_STATUS_SUCCESS)
{
DPrintf(0, ("[%s] - KeGetProcessorNumberFromIndex failed for index %lu - %d\n", __FUNCTION__, i, status));
return status;
}
ParaNdis_ProcessorNumberToGroupAffinity(&pContext->pPathBundles[i].rxPath.DPCAffinity, &procNumber);
pContext->pPathBundles[i].txPath.DPCAffinity = pContext->pPathBundles[i].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->pPathBundles[i].rxPath.DPCTargetProcessor = 1i64 << i;
pContext->pPathBundles[i].txPath.DPCTargetProcessor = pContext->pPathBundles[i].rxPath.DPCTargetProcessor;
#else
#error not supported
#endif
}
#if NDIS_SUPPORT_NDIS620
pContext->CXPath.DPCAffinity = pContext->pPathBundles[0].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->CXPath.DPCTargetProcessor = pContext->pPathBundles[0].rxPath.DPCTargetProcessor;
#else
#error not yet defined
#endif
return NDIS_STATUS_SUCCESS;
}
#if PARANDIS_SUPPORT_RSS
NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext)
{
USHORT rssIndex, bundleIndex;
ULONG cpuIndex;
ULONG rssTableSize = pContext->RSSParameters.RSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
rssIndex = 0;
bundleIndex = 0;
USHORT *cpuIndexTable;
ULONG cpuNumbers;
cpuNumbers = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
cpuIndexTable = (USHORT *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, cpuNumbers * sizeof(*cpuIndexTable),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (cpuIndexTable == nullptr)
{
DPrintf(0, ("[%s] cpu index table allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(cpuIndexTable, sizeof(*cpuIndexTable) * cpuNumbers);
for (bundleIndex = 0; bundleIndex < pContext->nPathBundles; ++bundleIndex)
{
cpuIndex = pContext->pPathBundles[bundleIndex].rxPath.getCPUIndex();
if (cpuIndex == INVALID_PROCESSOR_INDEX)
{
DPrintf(0, ("[%s] Invalid CPU index for path %u\n", __FUNCTION__, bundleIndex));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else if (cpuIndex >= cpuNumbers)
{
DPrintf(0, ("[%s] CPU index %lu exceeds CPU range %lu\n", __FUNCTION__, cpuIndex, cpuNumbers));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else
{
cpuIndexTable[cpuIndex] = bundleIndex;
}
}
DPrintf(0, ("[%s] Entering, RSS table size = %lu, # of path bundles = %u. RSS2QueueLength = %u, RSS2QueueMap =0x%p\n",
__FUNCTION__, rssTableSize, pContext->nPathBundles,
pContext->RSS2QueueLength, pContext->RSS2QueueMap));
if (pContext->RSS2QueueLength && pContext->RSS2QueueLength < rssTableSize)
{
DPrintf(0, ("[%s] Freeing RSS2Queue Map\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueLength = 0;
}
if (!pContext->RSS2QueueLength)
{
pContext->RSS2QueueLength = USHORT(rssTableSize);
pContext->RSS2QueueMap = (CPUPathesBundle **)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, rssTableSize * sizeof(*pContext->RSS2QueueMap),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->RSS2QueueMap == nullptr)
{
DPrintf(0, ("[%s] - Allocating RSS to queue mapping failed\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(pContext->RSS2QueueMap, sizeof(*pContext->RSS2QueueMap) * pContext->RSS2QueueLength);
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles;
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
cpuIndex = NdisProcessorNumberToIndex(pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex]);
bundleIndex = cpuIndexTable[cpuIndex];
DPrintf(3, ("[%s] filling the relationship, rssIndex = %u, bundleIndex = %u\n", __FUNCTION__, rssIndex, bundleIndex));
DPrintf(3, ("[%s] RSS proc number %u/%u, bundle affinity %u/%u\n", __FUNCTION__,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Group,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Number,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Group,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Mask));
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles + bundleIndex;
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SUCCESS;
}
#endif
/**********************************************************
Initializes VirtIO buffering and related stuff:
Allocates RX and TX queues and buffers
Parameters:
context
Return value:
TRUE if both queues are allocated
***********************************************************/
static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_RESOURCES;
DEBUG_ENTRY(0);
UINT i;
USHORT nVirtIOQueues = pContext->nHardwareQueues * 2 + 2;
pContext->nPathBundles = DetermineQueueNumber(pContext);
if (pContext->nPathBundles == 0)
{
DPrintf(0, ("[%s] - no I/O pathes\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
if (nVirtIOQueues > pContext->IODevice->maxQueues)
{
ULONG IODeviceSize = VirtIODeviceSizeRequired(nVirtIOQueues);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = (VirtIODevice *)NdisAllocateMemoryWithTagPriority(
pContext->MiniportHandle,
IODeviceSize,
PARANDIS_MEMORY_TAG,
NormalPoolPriority);
if (pContext->IODevice == nullptr)
{
DPrintf(0, ("[%s] - IODevice allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, IODeviceSize);
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
DPrintf(0, ("[%s] %u queues' slots reallocated for size %lu\n", __FUNCTION__, pContext->IODevice->maxQueues, IODeviceSize));
}
new (&pContext->CXPath, PLACEMENT_NEW) CParaNdisCX();
pContext->bCXPathAllocated = TRUE;
if (!pContext->CXPath.Create(pContext, 2 * pContext->nHardwareQueues))
{
DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__));
pContext->bHasHardwareFilters = FALSE;
pContext->bCtrlMACAddrSupported = FALSE;
}
else
{
pContext->bCXPathCreated = TRUE;
}
pContext->pPathBundles = (CPUPathesBundle *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, pContext->nPathBundles * sizeof(*pContext->pPathBundles),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->pPathBundles == nullptr)
{
DPrintf(0, ("[%s] Path bundles allocation failed\n", __FUNCTION__));
return status;
}
for (i = 0; i < pContext->nPathBundles; i++)
{
new (pContext->pPathBundles + i, PLACEMENT_NEW) CPUPathesBundle();
if (!pContext->pPathBundles[i].rxPath.Create(pContext, i * 2))
{
DPrintf(0, ("%s: CParaNdisRX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].rxCreated = true;
if (!pContext->pPathBundles[i].txPath.Create(pContext, i * 2 + 1))
{
DPrintf(0, ("%s: CParaNdisTX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].txCreated = true;
}
if (pContext->bCXPathCreated)
{
pContext->pPathBundles[0].cxPath = &pContext->CXPath;
}
status = NDIS_STATUS_SUCCESS;
return status;
}
static void ReadLinkState(PARANDIS_ADAPTER *pContext)
{
if (pContext->bLinkDetectSupported)
{
USHORT linkStatus = 0;
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = !!(linkStatus & VIRTIO_NET_S_LINK_UP);
}
else
{
pContext->bConnected = TRUE;
}
}
static void ParaNdis_RemoveDriverOKStatus(PPARANDIS_ADAPTER pContext )
{
VirtIODeviceRemoveStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
KeMemoryBarrier();
pContext->bDeviceInitialized = FALSE;
}
static VOID ParaNdis_AddDriverOKStatus(PPARANDIS_ADAPTER pContext)
{
pContext->bDeviceInitialized = TRUE;
KeMemoryBarrier();
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
}
/**********************************************************
Finishes initialization of context structure, calling also version dependent part
If this procedure failed, ParaNdis_CleanupContext must be called
Parameters:
context
Return value:
SUCCESS or some kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
DEBUG_ENTRY(0);
status = ParaNdis_FinishSpecificInitialization(pContext);
DPrintf(0, ("[%s] ParaNdis_FinishSpecificInitialization passed, status = %d\n", __FUNCTION__, status));
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_VirtIONetInit(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_ConfigureMSIXVectors(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = SetupDPCTarget(pContext);
DPrintf(0, ("[%s] SetupDPCTarget passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS && pContext->nPathBundles > 1)
{
u16 nPathes = u16(pContext->nPathBundles);
BOOLEAN sendSuccess = pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, VIRTIO_NET_CTRL_MQ_VQ_PAIR_SET, &nPathes, sizeof(nPathes), NULL, 0, 2);
if (!sendSuccess)
{
DPrintf(0, ("[%s] - Send MQ control message failed\n", __FUNCTION__));
status = NDIS_STATUS_DEVICE_FAILED;
}
}
pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1;
if (status == NDIS_STATUS_SUCCESS)
{
ReadLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
ParaNdis_AddDriverOKStatus(pContext);
ParaNdis_UpdateMAC(pContext);
}
DEBUG_EXIT_STATUS(0, status);
return status;
}
/**********************************************************
Releases VirtIO related resources - queues and buffers
Parameters:
context
Return value:
***********************************************************/
static void VirtIONetRelease(PARANDIS_ADAPTER *pContext)
{
BOOLEAN b;
ULONG i;
DEBUG_ENTRY(0);
/* list NetReceiveBuffersWaiting must be free */
for (i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
pRxNetDescriptor pBufferDescriptor;
while (NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pContext->ReceiveQueues + i)))
{
pBufferDescriptor->Queue->ReuseReceiveBuffer(FALSE, pBufferDescriptor);
}
}
do
{
b = pContext->m_upstreamPacketPending != 0;
if (b)
{
DPrintf(0, ("[%s] There are waiting buffers\n", __FUNCTION__));
PrintStatistics(pContext);
NdisMSleep(5000000);
}
} while (b);
RestoreMAC(pContext);
for (i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txCreated)
{
pContext->pPathBundles[i].txPath.Shutdown();
}
if (pContext->pPathBundles[i].rxCreated)
{
pContext->pPathBundles[i].rxPath.Shutdown();
/* this can be freed, queue shut down */
pContext->pPathBundles[i].rxPath.FreeRxDescriptorsFromList();
}
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
PrintStatistics(pContext);
}
static void PreventDPCServicing(PARANDIS_ADAPTER *pContext)
{
LONG inside;
pContext->bEnableInterruptHandlingDPC = FALSE;
KeMemoryBarrier();
do
{
inside = InterlockedIncrement(&pContext->counterDPCInside);
InterlockedDecrement(&pContext->counterDPCInside);
if (inside > 1)
{
DPrintf(0, ("[%s] waiting!\n", __FUNCTION__));
NdisMSleep(20000);
}
} while (inside > 1);
}
/**********************************************************
Frees all the resources allocated when the context initialized,
calling also version-dependent part
Parameters:
context
***********************************************************/
VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext)
{
/* disable any interrupt generation */
if (pContext->IODevice->addr)
{
if (pContext->bDeviceInitialized)
{
ParaNdis_RemoveDriverOKStatus(pContext);
}
}
PreventDPCServicing(pContext);
/****************************************
ensure all the incoming packets returned,
free all the buffers and their descriptors
*****************************************/
if (pContext->IODevice->addr)
{
ParaNdis_ResetVirtIONetDevice(pContext);
}
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
VirtIONetRelease(pContext);
ParaNdis_FinalizeCleanup(pContext);
if (pContext->ReceiveQueuesInitialized)
{
ULONG i;
for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
NdisFreeSpinLock(&pContext->ReceiveQueues[i].Lock);
}
}
pContext->m_PauseLock.~CNdisRWLock();
#if PARANDIS_SUPPORT_RSS
if (pContext->bRSSInitialized)
{
ParaNdis6_RSSCleanupConfiguration(&pContext->RSSParameters);
}
pContext->RSSParameters.rwLock.~CNdisRWLock();
#endif
if (pContext->bCXPathAllocated)
{
pContext->CXPath.~CParaNdisCX();
pContext->bCXPathAllocated = false;
}
if (pContext->pPathBundles != NULL)
{
USHORT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].~CPUPathesBundle();
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->pPathBundles, PARANDIS_MEMORY_TAG);
pContext->pPathBundles = nullptr;
}
if (pContext->RSS2QueueMap)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueMap = nullptr;
pContext->RSS2QueueLength = 0;
}
if (pContext->IODevice)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = nullptr;
}
if (pContext->AdapterResources.ulIOAddress)
{
NdisMDeregisterIoPortRange(
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength,
pContext->pIoPortOffset);
pContext->AdapterResources.ulIOAddress = 0;
}
}
/**********************************************************
System shutdown handler (shutdown, restart, bugcheck)
Parameters:
context
***********************************************************/
VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0); // this is only for kdbg :)
ParaNdis_ResetVirtIONetDevice(pContext);
}
static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo)
{
ULONG i;
if (pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
if ((pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx) && !pPacketInfo->hasVlanHeader)
return FALSE;
if (IsVlanSupported(pContext) && pPacketInfo->hasVlanHeader)
{
if (pContext->VlanId && pContext->VlanId != pPacketInfo->Vlan.VlanId)
{
return FALSE;
}
}
if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS)
return TRUE;
if(pPacketInfo->isUnicast)
{
ULONG Res;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED))
return FALSE;
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, pContext->CurrentMacAddress, &Res);
return !Res;
}
if(pPacketInfo->isBroadcast)
return (pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST);
// Multi-cast
if(pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST)
return TRUE;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST))
return FALSE;
for (i = 0; i < pContext->MulticastData.nofMulticastEntries; i++)
{
ULONG Res;
PUCHAR CurrMcastAddr = &pContext->MulticastData.MulticastList[i*ETH_LENGTH_OF_ADDRESS];
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, CurrMcastAddr, &Res);
if(!Res)
return TRUE;
}
return FALSE;
}
BOOLEAN ParaNdis_PerformPacketAnalyzis(
#if PARANDIS_SUPPORT_RSS
PPARANDIS_RSS_PARAMS RSSParameters,
#endif
PNET_PACKET_INFO PacketInfo,
PVOID HeadersBuffer,
ULONG DataLength)
{
if(!ParaNdis_AnalyzeReceivedPacket(HeadersBuffer, DataLength, PacketInfo))
return FALSE;
#if PARANDIS_SUPPORT_RSS
if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED)
{
ParaNdis6_RSSAnalyzeReceivedPacket(RSSParameters, HeadersBuffer, PacketInfo);
}
#endif
return TRUE;
}
VOID ParaNdis_ProcessorNumberToGroupAffinity(PGROUP_AFFINITY Affinity, const PPROCESSOR_NUMBER Processor)
{
Affinity->Group = Processor->Group;
Affinity->Mask = 1;
Affinity->Mask <<= Processor->Number;
}
CCHAR ParaNdis_GetScalingDataForPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo, PPROCESSOR_NUMBER pTargetProcessor)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetScalingDataForPacket(&pContext->RSSParameters, pPacketInfo, pTargetProcessor);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(pPacketInfo);
UNREFERENCED_PARAMETER(pTargetProcessor);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
static __inline
CCHAR GetReceiveQueueForCurrentCPU(PARANDIS_ADAPTER *pContext)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetCurrentCpuReceiveQueue(&pContext->RSSParameters);
#else
UNREFERENCED_PARAMETER(pContext);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
VOID ParaNdis_QueueRSSDpc(PARANDIS_ADAPTER *pContext, ULONG MessageIndex, PGROUP_AFFINITY pTargetAffinity)
{
#if PARANDIS_SUPPORT_RSS
NdisMQueueDpcEx(pContext->InterruptHandle, MessageIndex, pTargetAffinity, NULL);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(MessageIndex);
UNREFERENCED_PARAMETER(pTargetAffinity);
ASSERT(FALSE);
#endif
}
VOID ParaNdis_ReceiveQueueAddBuffer(PPARANDIS_RECEIVE_QUEUE pQueue, pRxNetDescriptor pBuffer)
{
NdisInterlockedInsertTailList( &pQueue->BuffersList,
&pBuffer->ReceiveQueueListEntry,
&pQueue->Lock);
}
VOID ParaMdis_TestPausing(PARANDIS_ADAPTER *pContext)
{
ONPAUSECOMPLETEPROC callback = nullptr;
if (pContext->m_upstreamPacketPending == 0)
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
if (pContext->m_upstreamPacketPending == 0 && (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc))
{
callback = pContext->ReceivePauseCompletionProc;
pContext->ReceiveState = srsDisabled;
pContext->ReceivePauseCompletionProc = NULL;
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
}
}
if (callback) callback(pContext);
}
static __inline
pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue)
{
PLIST_ENTRY pListEntry = NdisInterlockedRemoveHeadList(&pQueue->BuffersList, &pQueue->Lock);
return pListEntry ? CONTAINING_RECORD(pListEntry, RxNetDescriptor, ReceiveQueueListEntry) : NULL;
}
static __inline
BOOLEAN ReceiveQueueHasBuffers(PPARANDIS_RECEIVE_QUEUE pQueue)
{
BOOLEAN res;
NdisAcquireSpinLock(&pQueue->Lock);
res = !IsListEmpty(&pQueue->BuffersList);
NdisReleaseSpinLock(&pQueue->Lock);
return res;
}
static VOID
UpdateReceiveSuccessStatistics(PPARANDIS_ADAPTER pContext,
PNET_PACKET_INFO pPacketInfo,
UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifHCInOctets += pPacketInfo->dataLength;
if(pPacketInfo->isUnicast)
{
pContext->Statistics.ifHCInUcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInUcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isBroadcast)
{
pContext->Statistics.ifHCInBroadcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInBroadcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isMulticast)
{
pContext->Statistics.ifHCInMulticastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInMulticastOctets += pPacketInfo->dataLength;
}
else
{
ASSERT(FALSE);
}
}
static __inline VOID
UpdateReceiveFailStatistics(PPARANDIS_ADAPTER pContext, UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifInErrors++;
pContext->Statistics.ifInDiscards += nCoalescedSegmentsCount;
}
static BOOLEAN ProcessReceiveQueue(PARANDIS_ADAPTER *pContext,
PULONG pnPacketsToIndicateLeft,
CCHAR nQueueIndex,
PNET_BUFFER_LIST *indicate,
PNET_BUFFER_LIST *indicateTail,
ULONG *nIndicate)
{
pRxNetDescriptor pBufferDescriptor;
PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex];
if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1)
{
while( (*pnPacketsToIndicateLeft > 0) &&
(NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) )
{
PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo;
if( !pContext->bSurprizeRemoved &&
pContext->ReceiveState == srsEnabled &&
pContext->bConnected &&
ShallPassPacket(pContext, pPacketInfo))
{
UINT nCoalescedSegmentsCount;
PNET_BUFFER_LIST packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor, &nCoalescedSegmentsCount);
if(packet != NULL)
{
UpdateReceiveSuccessStatistics(pContext, pPacketInfo, nCoalescedSegmentsCount);
if (*indicate == nullptr)
{
*indicate = *indicateTail = packet;
}
else
{
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = packet;
*indicateTail = packet;
}
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = NULL;
(*pnPacketsToIndicateLeft)--;
(*nIndicate)++;
}
else
{
UpdateReceiveFailStatistics(pContext, nCoalescedSegmentsCount);
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
else
{
pContext->extraStatistics.framesFilteredOut++;
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
}
NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount);
return ReceiveQueueHasBuffers(pTargetReceiveQueue);
}
static
BOOLEAN RxDPCWorkBody(PARANDIS_ADAPTER *pContext, CPUPathesBundle *pathBundle, ULONG nPacketsToIndicate)
{
BOOLEAN res = FALSE;
BOOLEAN bMoreDataInRing;
PNET_BUFFER_LIST indicate, indicateTail;
ULONG nIndicate;
CCHAR CurrCpuReceiveQueue = GetReceiveQueueForCurrentCPU(pContext);
do
{
indicate = nullptr;
indicateTail = nullptr;
nIndicate = 0;
{
CNdisDispatchReadAutoLock tLock(pContext->m_PauseLock);
pathBundle->rxPath.ProcessRxRing(CurrCpuReceiveQueue);
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED,
&indicate, &indicateTail, &nIndicate);
if(CurrCpuReceiveQueue != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED)
{
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, CurrCpuReceiveQueue,
&indicate, &indicateTail, &nIndicate);
}
bMoreDataInRing = pathBundle->rxPath.RestartQueue();
}
if (nIndicate)
{
NdisMIndicateReceiveNetBufferLists(pContext->MiniportHandle,
indicate,
0,
nIndicate,
0);
}
ParaMdis_TestPausing(pContext);
} while (bMoreDataInRing);
return res;
}
bool ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate)
{
bool stillRequiresProcessing = false;
UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC);
DEBUG_ENTRY(5);
InterlockedIncrement(&pContext->counterDPCInside);
CPUPathesBundle *pathBundle = nullptr;
if (pContext->nPathBundles == 1)
{
pathBundle = pContext->pPathBundles;
}
else
{
ULONG procNumber = KeGetCurrentProcessorNumber();
if (procNumber < pContext->nPathBundles)
{
pathBundle = pContext->pPathBundles + procNumber;
}
}
if (pathBundle == nullptr)
{
return false;
}
if (pContext->bEnableInterruptHandlingDPC)
{
bool bDoKick = false;
InterlockedExchange(&pContext->bDPCInactive, 0);
if (RxDPCWorkBody(pContext, pathBundle, numOfPacketsToIndicate))
{
stillRequiresProcessing = true;
}
if (pContext->CXPath.WasInterruptReported() && pContext->bLinkDetectSupported)
{
ReadLinkState(pContext);
ParaNdis_SynchronizeLinkState(pContext);
pContext->CXPath.ClearInterruptReport();
}
if (!stillRequiresProcessing)
{
bDoKick = pathBundle->txPath.DoPendingTasks(true);
if (pathBundle->txPath.RestartQueue(bDoKick))
{
stillRequiresProcessing = true;
}
}
}
InterlockedDecrement(&pContext->counterDPCInside);
return stillRequiresProcessing;
}
VOID ParaNdis_ResetRxClassification(PARANDIS_ADAPTER *pContext)
{
ULONG i;
PPARANDIS_RECEIVE_QUEUE pUnclassified = &pContext->ReceiveQueues[PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED];
NdisAcquireSpinLock(&pUnclassified->Lock);
for(i = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED + 1; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
PPARANDIS_RECEIVE_QUEUE pCurrQueue = &pContext->ReceiveQueues[i];
NdisAcquireSpinLock(&pCurrQueue->Lock);
while(!IsListEmpty(&pCurrQueue->BuffersList))
{
PLIST_ENTRY pListEntry = RemoveHeadList(&pCurrQueue->BuffersList);
InsertTailList(&pUnclassified->BuffersList, pListEntry);
}
NdisReleaseSpinLock(&pCurrQueue->Lock);
}
NdisReleaseSpinLock(&pUnclassified->Lock);
}
/**********************************************************
Periodically called procedure, checking dpc activity
If DPC are not running, it does exactly the same that the DPC
Parameters:
context
***********************************************************/
static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext)
{
BOOLEAN bStopped;
BOOLEAN bReportHang = FALSE;
bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE);
if (bStopped)
{
pContext->nDetectedInactivity++;
}
else
{
pContext->nDetectedInactivity = 0;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txPath.HasHWBuffersIsUse())
{
if (pContext->nDetectedStoppedTx++ > 1)
{
DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!\n", __FUNCTION__, pContext->pPathBundles[i].txPath.GetFreeHWBuffers()));
//bReportHang = TRUE;
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 0);
#endif
break;
}
}
}
if (pContext->Limits.nPrintDiagnostic &&
++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic)
{
pContext->Counters.nPrintDiagnostic = 0;
// todo - collect more and put out optionally
PrintStatistics(pContext);
}
if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn)
{
pContext->Counters.nRxInactivity++;
if (pContext->Counters.nRxInactivity >= 10)
{
#if defined(CRASH_ON_NO_RX)
ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1;
proc(pContext);
#endif
}
}
else
{
pContext->Counters.nRxInactivity = 0;
pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets;
}
return bReportHang;
}
/**********************************************************
Common implementation of periodic poll
Parameters:
context
Return:
TRUE, if reset required
***********************************************************/
BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext)
{
static int nHangOn = 0;
BOOLEAN b = nHangOn >= 3 && nHangOn < 6;
DEBUG_ENTRY(3);
b |= CheckRunningDpc(pContext);
//uncomment to cause 3 consecutive resets
//nHangOn++;
DEBUG_EXIT_STATUS(b ? 0 : 6, b);
return b;
}
/////////////////////////////////////////////////////////////////////////////////////
//
// ReadVirtIODeviceRegister\WriteVirtIODeviceRegister
// NDIS specific implementation of the IO space read\write
//
/////////////////////////////////////////////////////////////////////////////////////
u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister)
{
ULONG ulValue;
NdisRawReadPortUlong(ulRegister, &ulValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
return ulValue;
}
void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
NdisRawWritePortUlong(ulRegister, ulValue);
}
u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister)
{
u8 bValue;
NdisRawReadPortUchar(ulRegister, &bValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
return bValue;
}
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
NdisRawWritePortUchar(ulRegister, bValue);
}
u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister)
{
u16 wValue;
NdisRawReadPortUshort(ulRegister, &wValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
return wValue;
}
void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue)
{
#if 1
NdisRawWritePortUshort(ulRegister, wValue);
#else
// test only to cause long TX waiting queue of NDIS packets
// to recognize it and request for reset via Hang handler
static int nCounterToFail = 0;
static const int StartFail = 200, StopFail = 600;
BOOLEAN bFail = FALSE;
DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
if ((ulRegister & 0x1F) == 0x10)
{
nCounterToFail++;
bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail;
}
if (!bFail) NdisRawWritePortUshort(ulRegister, wValue);
else
{
DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
}
#endif
}
/**********************************************************
Common handler of multicast address configuration
Parameters:
PVOID Buffer array of addresses from NDIS
ULONG BufferSize size of incoming buffer
PUINT pBytesRead update on success
PUINT pBytesNeeded update on wrong buffer size
Return value:
SUCCESS or kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_SetMulticastList(
PARANDIS_ADAPTER *pContext,
PVOID Buffer,
ULONG BufferSize,
PUINT pBytesRead,
PUINT pBytesNeeded)
{
NDIS_STATUS status;
ULONG length = BufferSize;
if (length > sizeof(pContext->MulticastData.MulticastList))
{
status = NDIS_STATUS_MULTICAST_FULL;
*pBytesNeeded = sizeof(pContext->MulticastData.MulticastList);
}
else if (length % ETH_LENGTH_OF_ADDRESS)
{
status = NDIS_STATUS_INVALID_LENGTH;
*pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS;
}
else
{
NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList));
if (length)
NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length);
pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS;
DPrintf(1, ("[%s] New multicast list of %d bytes\n", __FUNCTION__, length));
*pBytesRead = length;
status = NDIS_STATUS_SUCCESS;
}
return status;
}
/**********************************************************
Common handler of PnP events
Parameters:
Return value:
***********************************************************/
VOID ParaNdis_OnPnPEvent(
PARANDIS_ADAPTER *pContext,
NDIS_DEVICE_PNP_EVENT pEvent,
PVOID pInfo,
ULONG ulSize)
{
const char *pName = "";
UNREFERENCED_PARAMETER(pInfo);
UNREFERENCED_PARAMETER(ulSize);
DEBUG_ENTRY(0);
#undef MAKECASE
#define MAKECASE(x) case (x): pName = #x; break;
switch (pEvent)
{
MAKECASE(NdisDevicePnPEventQueryRemoved)
MAKECASE(NdisDevicePnPEventRemoved)
MAKECASE(NdisDevicePnPEventSurpriseRemoved)
MAKECASE(NdisDevicePnPEventQueryStopped)
MAKECASE(NdisDevicePnPEventStopped)
MAKECASE(NdisDevicePnPEventPowerProfileChanged)
MAKECASE(NdisDevicePnPEventFilterListChanged)
default:
break;
}
ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0);
DPrintf(0, ("[%s] (%s)\n", __FUNCTION__, pName));
if (pEvent == NdisDevicePnPEventSurpriseRemoved)
{
// on simulated surprise removal (under PnpTest) we need to reset the device
// to prevent any access of device queues to memory buffers
pContext->bSurprizeRemoved = TRUE;
ParaNdis_ResetVirtIONetDevice(pContext);
{
UINT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Pause();
}
}
}
pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent;
if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0]))
pContext->nPnpEventIndex = 0;
}
static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext)
{
u8 val;
ULONG f = pContext->PacketFilter;
val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2);
//SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2);
}
static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext)
{
u32 u32UniCastEntries = 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET,
&u32UniCastEntries,
sizeof(u32UniCastEntries),
&pContext->MulticastData,
sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS,
2);
}
static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK)
{
u16 val = vlanId & 0xfff;
UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK);
}
static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn)
{
ULONG i;
for (i = 0; i <= MAX_VLAN_ID; ++i)
SetSingleVlanFilter(pContext, i, bOn, 7);
}
/*
possible values of filter set (pContext->ulCurrentVlansFilterSet):
0 - all disabled
1..4095 - one selected enabled
4096 - all enabled
Note that only 0th vlan can't be enabled
*/
VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ULONG newFilterSet;
if (IsVlanSupported(pContext))
newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1);
else
newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0;
if (newFilterSet != pContext->ulCurrentVlansFilterSet)
{
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, FALSE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2);
pContext->ulCurrentVlansFilterSet = newFilterSet;
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, TRUE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2);
}
}
}
VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ParaNdis_DeviceFiltersUpdateRxMode(pContext);
ParaNdis_DeviceFiltersUpdateAddresses(pContext);
ParaNdis_DeviceFiltersUpdateVlanId(pContext);
}
}
static VOID
ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext)
{
if (pContext->bCtrlMACAddrSupported)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_ADDR_SET,
pContext->CurrentMacAddress,
ETH_LENGTH_OF_ADDRESS,
NULL, 0, 4);
}
}
#if PARANDIS_SUPPORT_RSC
VOID
ParaNdis_UpdateGuestOffloads(PARANDIS_ADAPTER *pContext, UINT64 Offloads)
{
if (pContext->RSC.bHasDynamicConfig)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_GUEST_OFFLOADS, VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET,
&Offloads,
sizeof(Offloads),
NULL, 0, 2);
}
}
#endif
VOID ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext)
{
UINT i;
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER);
/* GetHostFeature must be called with any mask once upon device initialization:
otherwise the device will not work properly */
VirtIODeviceReadHostFeatures(pContext->IODevice);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Renew();
pContext->pPathBundles[i].rxPath.Renew();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Renew();
}
ParaNdis_RestoreDeviceConfigurationAfterReset(pContext);
ParaNdis_UpdateDeviceFilters(pContext);
ParaNdis_UpdateMAC(pContext);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].rxPath.PopulateQueue();
}
ReadLinkState(pContext);
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_AddDriverOKStatus(pContext);
// if bFastSuspendInProcess is set by Win8 power-off procedure,
// the ParaNdis_Resume enables Tx and RX
// otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart)
ParaNdis_Resume(pContext);
pContext->bFastSuspendInProcess = FALSE;
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0);
}
VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0);
pContext->bConnected = FALSE;
// if bFastSuspendInProcess is set by Win8 power-off procedure
// the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis)
pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled;
ParaNdis_Suspend(pContext);
ParaNdis_RemoveDriverOKStatus(pContext);
if (pContext->bFastSuspendInProcess)
{
InterlockedExchange(&pContext->ReuseBufferRegular, FALSE);
}
#if !NDIS_SUPPORT_NDIS620
// WLK tests for Windows 2008 require media disconnect indication
// on power off. HCK tests for newer versions require media state unknown
// indication only and fail on disconnect indication
ParaNdis_SetLinkState(pContext, MediaConnectStateDisconnected);
#endif
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
PreventDPCServicing(pContext);
/*******************************************************************
shutdown queues to have all the receive buffers under our control
all the transmit buffers move to list of free buffers
********************************************************************/
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Shutdown();
pContext->pPathBundles[i].rxPath.Shutdown();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
ParaNdis_ResetVirtIONetDevice(pContext);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0);
}
void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext)
{
if (pContext->AdapterResources.ulIOAddress)
{
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 1);
#endif
}
}
tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset,
BOOLEAN verifyLength)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
//VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS
//VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate,
verifyLength, __FUNCTION__);
if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)
{
res.flags.IpOK = FALSE;
res.flags.IpFailed = TRUE;
return res;
}
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1580_0 |
crossvul-cpp_data_good_4220_3 | /* -*- C++ -*-
* Copyright 2019-2020 LibRaw LLC (info@libraw.org)
*
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
*/
#include "../../internal/libraw_cxx_defs.h"
void LibRaw::kodak_thumb_loader()
{
INT64 est_datasize =
T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate?
if (ID.toffset < 0)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND)
throw LIBRAW_EXCEPTION_IO_EOF;
if(INT64(T.theight) * INT64(T.twidth) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (INT64(T.theight) * INT64(T.twidth) < 64ULL)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
// some kodak cameras
ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth,
s_iheight = S.iheight;
ushort s_flags = libraw_internal_data.unpacker_data.load_flags;
libraw_internal_data.unpacker_data.load_flags = 12;
int s_colors = P1.colors;
unsigned s_filters = P1.filters;
ushort(*s_image)[4] = imgdata.image;
S.height = T.theight;
S.width = T.twidth;
P1.filters = 0;
if (thumb_load_raw == &LibRaw::kodak_ycbcr_load_raw)
{
S.height += S.height & 1;
S.width += S.width & 1;
}
imgdata.image =
(ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image));
merror(imgdata.image, "LibRaw::kodak_thumb_loader()");
ID.input->seek(ID.toffset, SEEK_SET);
// read kodak thumbnail into T.image[]
try
{
(this->*thumb_load_raw)();
}
catch (...)
{
free(imgdata.image);
imgdata.image = s_image;
T.twidth = 0;
S.width = s_width;
S.iwidth = s_iwidth;
S.iheight = s_iheight;
T.theight = 0;
S.height = s_height;
T.tcolors = 0;
P1.colors = s_colors;
P1.filters = s_filters;
T.tlength = 0;
libraw_internal_data.unpacker_data.load_flags = s_flags;
return;
}
// from scale_colors
{
double dmax;
float scale_mul[4];
int c, val;
for (dmax = DBL_MAX, c = 0; c < 3; c++)
if (dmax > C.pre_mul[c])
dmax = C.pre_mul[c];
for (c = 0; c < 3; c++)
scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum;
scale_mul[3] = scale_mul[1];
size_t size = S.height * S.width;
for (unsigned i = 0; i < size * 4; i++)
{
val = imgdata.image[0][i];
if (!val)
continue;
val *= scale_mul[i & 3];
imgdata.image[0][i] = CLIP(val);
}
}
// from convert_to_rgb
ushort *img;
int row, col;
int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] =
(int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4);
merror(t_hist, "LibRaw::kodak_thumb_loader()");
float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0},
{-0.111855984, 1.73688626, -0.625030339, 0},
{-0.0379119813, -0.891268849, 1.92918086, 0}};
for (img = imgdata.image[0], row = 0; row < S.height; row++)
for (col = 0; col < S.width; col++, img += 4)
{
out[0] = out[1] = out[2] = 0;
int c;
for (c = 0; c < 3; c++)
{
out[0] += out_cam[0][c] * img[c];
out[1] += out_cam[1][c] * img[c];
out[2] += out_cam[2][c] * img[c];
}
for (c = 0; c < 3; c++)
img[c] = CLIP((int)out[c]);
for (c = 0; c < P1.colors; c++)
t_hist[c][img[c] >> 3]++;
}
// from gamma_lut
int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] =
libraw_internal_data.output_data.histogram;
libraw_internal_data.output_data.histogram = t_hist;
// make curve output curve!
ushort *t_curve = (ushort *)calloc(sizeof(C.curve), 1);
merror(t_curve, "LibRaw::kodak_thumb_loader()");
memmove(t_curve, C.curve, sizeof(C.curve));
memset(C.curve, 0, sizeof(C.curve));
{
int perc, val, total, t_white = 0x2000, c;
perc = S.width * S.height * 0.01; /* 99th percentile white level */
if (IO.fuji_width)
perc /= 2;
if (!((O.highlight & ~2) || O.no_auto_bright))
for (t_white = c = 0; c < P1.colors; c++)
{
for (val = 0x2000, total = 0; --val > 32;)
if ((total += libraw_internal_data.output_data.histogram[c][val]) >
perc)
break;
if (t_white < val)
t_white = val;
}
gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright);
}
libraw_internal_data.output_data.histogram = save_hist;
free(t_hist);
// from write_ppm_tiff - copy pixels into bitmap
int s_flip = imgdata.sizes.flip;
if (imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS)
imgdata.sizes.flip = 0;
S.iheight = S.height;
S.iwidth = S.width;
if (S.flip & 4)
SWAP(S.height, S.width);
if (T.thumb)
free(T.thumb);
T.thumb = (char *)calloc(S.width * S.height, P1.colors);
merror(T.thumb, "LibRaw::kodak_thumb_loader()");
T.tlength = S.width * S.height * P1.colors;
// from write_tiff_ppm
{
int soff = flip_index(0, 0);
int cstep = flip_index(0, 1) - soff;
int rstep = flip_index(1, 0) - flip_index(0, S.width);
for (int row = 0; row < S.height; row++, soff += rstep)
{
char *ppm = T.thumb + row * S.width * P1.colors;
for (int col = 0; col < S.width; col++, soff += cstep)
for (int c = 0; c < P1.colors; c++)
ppm[col * P1.colors + c] =
imgdata.color.curve[imgdata.image[soff][c]] >> 8;
}
}
memmove(C.curve, t_curve, sizeof(C.curve));
free(t_curve);
// restore variables
free(imgdata.image);
imgdata.image = s_image;
if (imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS)
imgdata.sizes.flip = s_flip;
T.twidth = S.width;
S.width = s_width;
S.iwidth = s_iwidth;
S.iheight = s_iheight;
T.theight = S.height;
S.height = s_height;
T.tcolors = P1.colors;
P1.colors = s_colors;
P1.filters = s_filters;
libraw_internal_data.unpacker_data.load_flags = s_flags;
}
// ������� thumbnail �� �����, ������ thumb_format � ������������ � ��������
int LibRaw::thumbOK(INT64 maxsz)
{
if (!ID.input)
return 0;
if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
load_raw == &LibRaw::broadcom_load_raw) // RPi
)
return 0;
INT64 fsize = ID.input->size();
if (fsize > 0x7fffffffU)
return 0; // No thumb for raw > 2Gb
int tsize = 0;
int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3;
if (write_thumb == &LibRaw::jpeg_thumb)
tsize = T.tlength;
else if (write_thumb == &LibRaw::ppm_thumb)
tsize = tcol * T.twidth * T.theight;
else if (write_thumb == &LibRaw::ppm16_thumb)
tsize = tcol * T.twidth * T.theight *
((imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_USE_PPM16_THUMBS)
? 2
: 1);
#ifdef USE_X3FTOOLS
else if (write_thumb == &LibRaw::x3f_thumb_loader)
{
tsize = x3f_thumb_size();
}
#endif
else // Kodak => no check
tsize = 1;
if (tsize < 0)
return 0;
if (maxsz > 0 && tsize > maxsz)
return 0;
return (tsize + ID.toffset <= fsize) ? 1 : 0;
}
int LibRaw::dcraw_thumb_writer(const char *fname)
{
// CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD);
if (!fname)
return ENOENT;
FILE *tfp = fopen(fname, "wb");
if (!tfp)
return errno;
if (!T.thumb)
{
fclose(tfp);
return LIBRAW_OUT_OF_ORDER_CALL;
}
try
{
switch (T.tformat)
{
case LIBRAW_THUMBNAIL_JPEG:
jpeg_thumb_writer(tfp, T.thumb, T.tlength);
break;
case LIBRAW_THUMBNAIL_BITMAP:
fprintf(tfp, "P6\n%d %d\n255\n", T.twidth, T.theight);
fwrite(T.thumb, 1, T.tlength, tfp);
break;
default:
fclose(tfp);
return LIBRAW_UNSUPPORTED_THUMBNAIL;
}
fclose(tfp);
return 0;
}
catch (LibRaw_exceptions err)
{
fclose(tfp);
EXCEPTION_HANDLER(err);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_4220_3 |
crossvul-cpp_data_bad_1376_0 | /*
* Copyright 2004-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/protocol/TProtocolException.h>
#include <folly/Format.h>
namespace apache { namespace thrift { namespace protocol {
[[noreturn]] void TProtocolException::throwUnionMissingStop() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"missing stop marker to terminate a union");
}
[[noreturn]] void TProtocolException::throwReportedTypeMismatch() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"The reported type of thrift element does not match the serialized type");
}
[[noreturn]] void TProtocolException::throwNegativeSize() {
throw TProtocolException(TProtocolException::NEGATIVE_SIZE);
}
[[noreturn]] void TProtocolException::throwExceededSizeLimit() {
throw TProtocolException(TProtocolException::SIZE_LIMIT);
}
[[noreturn]] void TProtocolException::throwMissingRequiredField(
folly::StringPiece field,
folly::StringPiece type) {
constexpr auto fmt =
"Required field '{}' was not found in serialized data! Struct: {}";
throw TProtocolException(
TProtocolException::MISSING_REQUIRED_FIELD,
folly::sformat(fmt, field, type));
}
[[noreturn]] void TProtocolException::throwBoolValueOutOfRange(uint8_t value) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
folly::sformat(
"Attempt to interpret value {} as bool, probably the data is corrupted",
value));
}
}}}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1376_0 |
crossvul-cpp_data_good_1442_4 | /*
* Copyright (C) 2004-2016 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "znctest.h"
namespace znc_inttest {
namespace {
TEST_F(ZNCTest, Modperl) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod perleval");
client.Write("PRIVMSG *perleval :2+2");
client.ReadUntil(":*perleval!znc@znc.in PRIVMSG nick :Result: 4");
client.Write("PRIVMSG *perleval :$self->GetUser->GetUserName");
client.ReadUntil("Result: user");
}
TEST_F(ZNCTest, Modpython) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod pyeval");
client.Write("PRIVMSG *pyeval :2+2");
client.ReadUntil(":*pyeval!znc@znc.in PRIVMSG nick :4");
client.Write("PRIVMSG *pyeval :module.GetUser().GetUserName()");
client.ReadUntil("nick :'user'");
ircd.Write(":server 001 nick :Hello");
ircd.Write(":n!u@h PRIVMSG nick :Hi\xF0, github issue #1229");
// "replacement character"
client.ReadUntil("Hi\xEF\xBF\xBD, github issue");
// Non-existing encoding
client.Write("PRIVMSG *controlpanel :Set ClientEncoding $me Western");
client.Write("JOIN #a\342");
client.ReadUntil(
":*controlpanel!znc@znc.in PRIVMSG nick :ClientEncoding = UTF-8");
ircd.ReadUntil("JOIN #a\xEF\xBF\xBD");
}
TEST_F(ZNCTest, ModpythonSocket) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("socktest.py", R"(
import znc
class acc(znc.Socket):
def OnReadData(self, data):
self.GetModule().PutModule('received {} bytes'.format(len(data)))
self.Close()
class lis(znc.Socket):
def OnAccepted(self, host, port):
sock = self.GetModule().CreateSocket(acc)
sock.DisableReadLine()
return sock
class socktest(znc.Module):
def OnLoad(self, args, ret):
listen = self.CreateSocket(lis)
self.port = listen.Listen()
return True
def OnModCommand(self, cmd):
sock = self.CreateSocket()
sock.Connect('127.0.0.1', self.port)
sock.WriteBytes(b'blah')
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod socktest");
client.Write("PRIVMSG *socktest :foo");
client.ReadUntil("received 4 bytes");
}
TEST_F(ZNCTest, ModperlSocket) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("socktest.pm", R"(
package socktest::acc;
use base 'ZNC::Socket';
sub OnReadData {
my ($self, $data, $len) = @_;
$self->GetModule->PutModule("received $len bytes");
$self->Close;
}
package socktest::lis;
use base 'ZNC::Socket';
sub OnAccepted {
my $self = shift;
return $self->GetModule->CreateSocket('socktest::acc');
}
package socktest::conn;
use base 'ZNC::Socket';
package socktest;
use base 'ZNC::Module';
sub OnLoad {
my $self = shift;
my $listen = $self->CreateSocket('socktest::lis');
$self->{port} = $listen->Listen;
return 1;
}
sub OnModCommand {
my ($self, $cmd) = @_;
my $sock = $self->CreateSocket('socktest::conn');
$sock->Connect('127.0.0.1', $self->{port});
$sock->Write('blah');
}
1;
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod socktest");
client.Write("PRIVMSG *socktest :foo");
client.ReadUntil("received 4 bytes");
}
TEST_F(ZNCTest, ModpythonVCString) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("test.py", R"(
import znc
class test(znc.Module):
def OnUserRawMessage(self, msg):
self.PutModule(str(msg.GetParams()))
return znc.CONTINUE
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod test");
client.Write("PRIVMSG *test :foo");
client.ReadUntil("'*test', 'foo'");
}
TEST_F(ZNCTest, ModperlVCString) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("test.pm", R"(
package test;
use base 'ZNC::Module';
sub OnUserRawMessage {
my ($self, $msg) = @_;
my @params = $msg->GetParams;
$self->PutModule("@params");
return $ZNC::CONTINUE;
}
1;
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod test");
client.Write("PRIVMSG *test :foo");
client.ReadUntil(":*test foo");
}
TEST_F(ZNCTest, ModperlNV) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("test.pm", R"(
package test;
use base 'ZNC::Module';
sub OnLoad {
my $self = shift;
$self->SetNV('a', 'X');
$self->NV->{b} = 'Y';
my @k = keys %{$self->NV};
$self->PutModule("@k");
return $ZNC::CONTINUE;
}
1;
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod test");
client.ReadUntil(":a b");
}
} // namespace
} // namespace znc_inttest
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1442_4 |
crossvul-cpp_data_bad_2411_3 | /*
Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform.hpp"
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#endif
#include <string.h>
#include <new>
#include "stream_engine.hpp"
#include "io_thread.hpp"
#include "session_base.hpp"
#include "v1_encoder.hpp"
#include "v1_decoder.hpp"
#include "v2_encoder.hpp"
#include "v2_decoder.hpp"
#include "null_mechanism.hpp"
#include "plain_mechanism.hpp"
#include "curve_client.hpp"
#include "curve_server.hpp"
#include "raw_decoder.hpp"
#include "raw_encoder.hpp"
#include "config.hpp"
#include "err.hpp"
#include "ip.hpp"
#include "likely.hpp"
#include "wire.hpp"
zmq::stream_engine_t::stream_engine_t (fd_t fd_, const options_t &options_,
const std::string &endpoint_) :
s (fd_),
inpos (NULL),
insize (0),
decoder (NULL),
outpos (NULL),
outsize (0),
encoder (NULL),
handshaking (true),
greeting_size (v2_greeting_size),
greeting_bytes_read (0),
session (NULL),
options (options_),
endpoint (endpoint_),
plugged (false),
read_msg (&stream_engine_t::read_identity),
write_msg (&stream_engine_t::write_identity),
io_error (false),
subscription_required (false),
mechanism (NULL),
input_stopped (false),
output_stopped (false),
socket (NULL)
{
int rc = tx_msg.init ();
errno_assert (rc == 0);
// Put the socket into non-blocking mode.
unblock_socket (s);
if (!get_peer_ip_address (s, peer_address))
peer_address = "";
#ifdef SO_NOSIGPIPE
// Make sure that SIGPIPE signal is not generated when writing to a
// connection that was already closed by the peer.
int set = 1;
rc = setsockopt (s, SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof (int));
errno_assert (rc == 0);
#endif
}
zmq::stream_engine_t::~stream_engine_t ()
{
zmq_assert (!plugged);
if (s != retired_fd) {
#ifdef ZMQ_HAVE_WINDOWS
int rc = closesocket (s);
wsa_assert (rc != SOCKET_ERROR);
#else
int rc = close (s);
errno_assert (rc == 0);
#endif
s = retired_fd;
}
int rc = tx_msg.close ();
errno_assert (rc == 0);
delete encoder;
delete decoder;
delete mechanism;
}
void zmq::stream_engine_t::plug (io_thread_t *io_thread_,
session_base_t *session_)
{
zmq_assert (!plugged);
plugged = true;
// Connect to session object.
zmq_assert (!session);
zmq_assert (session_);
session = session_;
socket = session-> get_socket ();
// Connect to I/O threads poller object.
io_object_t::plug (io_thread_);
handle = add_fd (s);
io_error = false;
if (options.raw_sock) {
// no handshaking for raw sock, instantiate raw encoder and decoders
encoder = new (std::nothrow) raw_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) raw_decoder_t (in_batch_size);
alloc_assert (decoder);
// disable handshaking for raw socket
handshaking = false;
read_msg = &stream_engine_t::pull_msg_from_session;
write_msg = &stream_engine_t::push_msg_to_session;
}
else {
// Send the 'length' and 'flags' fields of the identity message.
// The 'length' field is encoded in the long format.
outpos = greeting_send;
outpos [outsize++] = 0xff;
put_uint64 (&outpos [outsize], options.identity_size + 1);
outsize += 8;
outpos [outsize++] = 0x7f;
}
set_pollin (handle);
set_pollout (handle);
// Flush all the data that may have been already received downstream.
in_event ();
}
void zmq::stream_engine_t::unplug ()
{
zmq_assert (plugged);
plugged = false;
// Cancel all fd subscriptions.
if (!io_error)
rm_fd (handle);
// Disconnect from I/O threads poller object.
io_object_t::unplug ();
session = NULL;
}
void zmq::stream_engine_t::terminate ()
{
unplug ();
delete this;
}
void zmq::stream_engine_t::in_event ()
{
assert (!io_error);
// If still handshaking, receive and process the greeting message.
if (unlikely (handshaking))
if (!handshake ())
return;
zmq_assert (decoder);
// If there has been an I/O error, stop polling.
if (input_stopped) {
rm_fd (handle);
io_error = true;
return;
}
// If there's no data to process in the buffer...
if (!insize) {
// Retrieve the buffer and read as much data as possible.
// Note that buffer can be arbitrarily large. However, we assume
// the underlying TCP layer has fixed buffer size and thus the
// number of bytes read will be always limited.
size_t bufsize = 0;
decoder->get_buffer (&inpos, &bufsize);
int const rc = read (inpos, bufsize);
if (rc == 0) {
error ();
return;
}
if (rc == -1) {
if (errno != EAGAIN)
error ();
return;
}
// Adjust input size
insize = static_cast <size_t> (rc);
}
int rc = 0;
size_t processed = 0;
while (insize > 0) {
rc = decoder->decode (inpos, insize, processed);
zmq_assert (processed <= insize);
inpos += processed;
insize -= processed;
if (rc == 0 || rc == -1)
break;
rc = (this->*write_msg) (decoder->msg ());
if (rc == -1)
break;
}
// Tear down the connection if we have failed to decode input data
// or the session has rejected the message.
if (rc == -1) {
if (errno != EAGAIN) {
error ();
return;
}
input_stopped = true;
reset_pollin (handle);
}
session->flush ();
}
void zmq::stream_engine_t::out_event ()
{
zmq_assert (!io_error);
// If write buffer is empty, try to read new data from the encoder.
if (!outsize) {
// Even when we stop polling as soon as there is no
// data to send, the poller may invoke out_event one
// more time due to 'speculative write' optimisation.
if (unlikely (encoder == NULL)) {
zmq_assert (handshaking);
return;
}
outpos = NULL;
outsize = encoder->encode (&outpos, 0);
while (outsize < out_batch_size) {
if ((this->*read_msg) (&tx_msg) == -1)
break;
encoder->load_msg (&tx_msg);
unsigned char *bufptr = outpos + outsize;
size_t n = encoder->encode (&bufptr, out_batch_size - outsize);
zmq_assert (n > 0);
if (outpos == NULL)
outpos = bufptr;
outsize += n;
}
// If there is no data to send, stop polling for output.
if (outsize == 0) {
output_stopped = true;
reset_pollout (handle);
return;
}
}
// If there are any data to write in write buffer, write as much as
// possible to the socket. Note that amount of data to write can be
// arbitrarily large. However, we assume that underlying TCP layer has
// limited transmission buffer and thus the actual number of bytes
// written should be reasonably modest.
int nbytes = write (outpos, outsize);
// IO error has occurred. We stop waiting for output events.
// The engine is not terminated until we detect input error;
// this is necessary to prevent losing incoming messages.
if (nbytes == -1) {
reset_pollout (handle);
return;
}
outpos += nbytes;
outsize -= nbytes;
// If we are still handshaking and there are no data
// to send, stop polling for output.
if (unlikely (handshaking))
if (outsize == 0)
reset_pollout (handle);
}
void zmq::stream_engine_t::restart_output ()
{
if (unlikely (io_error))
return;
if (likely (output_stopped)) {
set_pollout (handle);
output_stopped = false;
}
// Speculative write: The assumption is that at the moment new message
// was sent by the user the socket is probably available for writing.
// Thus we try to write the data to socket avoiding polling for POLLOUT.
// Consequently, the latency should be better in request/reply scenarios.
out_event ();
}
void zmq::stream_engine_t::restart_input ()
{
zmq_assert (input_stopped);
zmq_assert (session != NULL);
zmq_assert (decoder != NULL);
int rc = (this->*write_msg) (decoder->msg ());
if (rc == -1) {
if (errno == EAGAIN)
session->flush ();
else
error ();
return;
}
while (insize > 0) {
size_t processed = 0;
rc = decoder->decode (inpos, insize, processed);
zmq_assert (processed <= insize);
inpos += processed;
insize -= processed;
if (rc == 0 || rc == -1)
break;
rc = (this->*write_msg) (decoder->msg ());
if (rc == -1)
break;
}
if (rc == -1 && errno == EAGAIN)
session->flush ();
else
if (rc == -1 || io_error)
error ();
else {
input_stopped = false;
set_pollin (handle);
session->flush ();
// Speculative read.
in_event ();
}
}
bool zmq::stream_engine_t::handshake ()
{
zmq_assert (handshaking);
zmq_assert (greeting_bytes_read < greeting_size);
// Receive the greeting.
while (greeting_bytes_read < greeting_size) {
const int n = read (greeting_recv + greeting_bytes_read,
greeting_size - greeting_bytes_read);
if (n == 0) {
error ();
return false;
}
if (n == -1) {
if (errno != EAGAIN)
error ();
return false;
}
greeting_bytes_read += n;
// We have received at least one byte from the peer.
// If the first byte is not 0xff, we know that the
// peer is using unversioned protocol.
if (greeting_recv [0] != 0xff)
break;
if (greeting_bytes_read < signature_size)
continue;
// Inspect the right-most bit of the 10th byte (which coincides
// with the 'flags' field if a regular message was sent).
// Zero indicates this is a header of identity message
// (i.e. the peer is using the unversioned protocol).
if (!(greeting_recv [9] & 0x01))
break;
// The peer is using versioned protocol.
// Send the major version number.
if (outpos + outsize == greeting_send + signature_size) {
if (outsize == 0)
set_pollout (handle);
outpos [outsize++] = 3; // Major version number
}
if (greeting_bytes_read > signature_size) {
if (outpos + outsize == greeting_send + signature_size + 1) {
if (outsize == 0)
set_pollout (handle);
// Use ZMTP/2.0 to talk to older peers.
if (greeting_recv [10] == ZMTP_1_0
|| greeting_recv [10] == ZMTP_2_0)
outpos [outsize++] = options.type;
else {
outpos [outsize++] = 0; // Minor version number
memset (outpos + outsize, 0, 20);
zmq_assert (options.mechanism == ZMQ_NULL
|| options.mechanism == ZMQ_PLAIN
|| options.mechanism == ZMQ_CURVE);
if (options.mechanism == ZMQ_NULL)
memcpy (outpos + outsize, "NULL", 4);
else
if (options.mechanism == ZMQ_PLAIN)
memcpy (outpos + outsize, "PLAIN", 5);
else
memcpy (outpos + outsize, "CURVE", 5);
outsize += 20;
memset (outpos + outsize, 0, 32);
outsize += 32;
greeting_size = v3_greeting_size;
}
}
}
}
// Position of the revision field in the greeting.
const size_t revision_pos = 10;
// Is the peer using ZMTP/1.0 with no revision number?
// If so, we send and receive rest of identity message
if (greeting_recv [0] != 0xff || !(greeting_recv [9] & 0x01)) {
encoder = new (std::nothrow) v1_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v1_decoder_t (in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
// We have already sent the message header.
// Since there is no way to tell the encoder to
// skip the message header, we simply throw that
// header data away.
const size_t header_size = options.identity_size + 1 >= 255 ? 10 : 2;
unsigned char tmp [10], *bufferp = tmp;
// Prepare the identity message and load it into encoder.
// Then consume bytes we have already sent to the peer.
const int rc = tx_msg.init_size (options.identity_size);
zmq_assert (rc == 0);
memcpy (tx_msg.data (), options.identity, options.identity_size);
encoder->load_msg (&tx_msg);
size_t buffer_size = encoder->encode (&bufferp, header_size);
zmq_assert (buffer_size == header_size);
// Make sure the decoder sees the data we have already received.
inpos = greeting_recv;
insize = greeting_bytes_read;
// To allow for interoperability with peers that do not forward
// their subscriptions, we inject a phantom subscription message
// message into the incoming message stream.
if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB)
subscription_required = true;
// We are sending our identity now and the next message
// will come from the socket.
read_msg = &stream_engine_t::pull_msg_from_session;
// We are expecting identity message.
write_msg = &stream_engine_t::write_identity;
}
else
if (greeting_recv [revision_pos] == ZMTP_1_0) {
encoder = new (std::nothrow) v1_encoder_t (
out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v1_decoder_t (
in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
}
else
if (greeting_recv [revision_pos] == ZMTP_2_0) {
encoder = new (std::nothrow) v2_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v2_decoder_t (
in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
}
else {
encoder = new (std::nothrow) v2_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v2_decoder_t (
in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
if (options.mechanism == ZMQ_NULL
&& memcmp (greeting_recv + 12, "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) {
mechanism = new (std::nothrow)
null_mechanism_t (session, peer_address, options);
alloc_assert (mechanism);
}
else
if (options.mechanism == ZMQ_PLAIN
&& memcmp (greeting_recv + 12, "PLAIN\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) {
mechanism = new (std::nothrow)
plain_mechanism_t (session, peer_address, options);
alloc_assert (mechanism);
}
#ifdef HAVE_LIBSODIUM
else
if (options.mechanism == ZMQ_CURVE
&& memcmp (greeting_recv + 12, "CURVE\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) {
if (options.as_server)
mechanism = new (std::nothrow)
curve_server_t (session, peer_address, options);
else
mechanism = new (std::nothrow) curve_client_t (options);
alloc_assert (mechanism);
}
#endif
else {
error ();
return false;
}
read_msg = &stream_engine_t::next_handshake_command;
write_msg = &stream_engine_t::process_handshake_command;
}
// Start polling for output if necessary.
if (outsize == 0)
set_pollout (handle);
// Handshaking was successful.
// Switch into the normal message flow.
handshaking = false;
return true;
}
int zmq::stream_engine_t::read_identity (msg_t *msg_)
{
int rc = msg_->init_size (options.identity_size);
errno_assert (rc == 0);
if (options.identity_size > 0)
memcpy (msg_->data (), options.identity, options.identity_size);
read_msg = &stream_engine_t::pull_msg_from_session;
return 0;
}
int zmq::stream_engine_t::write_identity (msg_t *msg_)
{
if (options.recv_identity) {
msg_->set_flags (msg_t::identity);
int rc = session->push_msg (msg_);
errno_assert (rc == 0);
}
else {
int rc = msg_->close ();
errno_assert (rc == 0);
rc = msg_->init ();
errno_assert (rc == 0);
}
if (subscription_required)
write_msg = &stream_engine_t::write_subscription_msg;
else
write_msg = &stream_engine_t::push_msg_to_session;
return 0;
}
int zmq::stream_engine_t::next_handshake_command (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->next_handshake_command (msg_);
if (rc == 0) {
msg_->set_flags (msg_t::command);
if (mechanism->is_handshake_complete ())
mechanism_ready ();
}
return rc;
}
int zmq::stream_engine_t::process_handshake_command (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->process_handshake_command (msg_);
if (rc == 0) {
if (mechanism->is_handshake_complete ())
mechanism_ready ();
if (output_stopped)
restart_output ();
}
return rc;
}
void zmq::stream_engine_t::zap_msg_available ()
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->zap_msg_available ();
if (rc == -1) {
error ();
return;
}
if (input_stopped)
restart_input ();
if (output_stopped)
restart_output ();
}
void zmq::stream_engine_t::mechanism_ready ()
{
if (options.recv_identity) {
msg_t identity;
mechanism->peer_identity (&identity);
const int rc = session->push_msg (&identity);
if (rc == -1 && errno == EAGAIN) {
// If the write is failing at this stage with
// an EAGAIN the pipe must be being shut down,
// so we can just bail out of the identity set.
return;
}
errno_assert (rc == 0);
session->flush ();
}
read_msg = &stream_engine_t::pull_and_encode;
write_msg = &stream_engine_t::decode_and_push;
}
int zmq::stream_engine_t::pull_msg_from_session (msg_t *msg_)
{
return session->pull_msg (msg_);
}
int zmq::stream_engine_t::push_msg_to_session (msg_t *msg_)
{
return session->push_msg (msg_);
}
int zmq::stream_engine_t::pull_and_encode (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
if (session->pull_msg (msg_) == -1)
return -1;
if (mechanism->encode (msg_) == -1)
return -1;
return 0;
}
int zmq::stream_engine_t::decode_and_push (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
if (mechanism->decode (msg_) == -1)
return -1;
if (session->push_msg (msg_) == -1) {
if (errno == EAGAIN)
write_msg = &stream_engine_t::push_one_then_decode_and_push;
return -1;
}
return 0;
}
int zmq::stream_engine_t::push_one_then_decode_and_push (msg_t *msg_)
{
const int rc = session->push_msg (msg_);
if (rc == 0)
write_msg = &stream_engine_t::decode_and_push;
return rc;
}
int zmq::stream_engine_t::write_subscription_msg (msg_t *msg_)
{
msg_t subscription;
// Inject the subscription message, so that also
// ZMQ 2.x peers receive published messages.
int rc = subscription.init_size (1);
errno_assert (rc == 0);
*(unsigned char*) subscription.data () = 1;
rc = session->push_msg (&subscription);
if (rc == -1)
return -1;
write_msg = &stream_engine_t::push_msg_to_session;
return push_msg_to_session (msg_);
}
void zmq::stream_engine_t::error ()
{
zmq_assert (session);
socket->event_disconnected (endpoint, s);
session->flush ();
session->detach ();
unplug ();
delete this;
}
int zmq::stream_engine_t::write (const void *data_, size_t size_)
{
#ifdef ZMQ_HAVE_WINDOWS
int nbytes = send (s, (char*) data_, (int) size_, 0);
// If not a single byte can be written to the socket in non-blocking mode
// we'll get an error (this may happen during the speculative write).
if (nbytes == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK)
return 0;
// Signalise peer failure.
if (nbytes == SOCKET_ERROR && (
WSAGetLastError () == WSAENETDOWN ||
WSAGetLastError () == WSAENETRESET ||
WSAGetLastError () == WSAEHOSTUNREACH ||
WSAGetLastError () == WSAECONNABORTED ||
WSAGetLastError () == WSAETIMEDOUT ||
WSAGetLastError () == WSAECONNRESET))
return -1;
wsa_assert (nbytes != SOCKET_ERROR);
return nbytes;
#else
ssize_t nbytes = send (s, data_, size_, 0);
// Several errors are OK. When speculative write is being done we may not
// be able to write a single byte from the socket. Also, SIGSTOP issued
// by a debugging tool can result in EINTR error.
if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK ||
errno == EINTR))
return 0;
// Signalise peer failure.
if (nbytes == -1) {
errno_assert (errno != EACCES
&& errno != EBADF
&& errno != EDESTADDRREQ
&& errno != EFAULT
&& errno != EINVAL
&& errno != EISCONN
&& errno != EMSGSIZE
&& errno != ENOMEM
&& errno != ENOTSOCK
&& errno != EOPNOTSUPP);
return -1;
}
return static_cast <int> (nbytes);
#endif
}
int zmq::stream_engine_t::read (void *data_, size_t size_)
{
#ifdef ZMQ_HAVE_WINDOWS
const int rc = recv (s, (char*) data_, (int) size_, 0);
// If not a single byte can be read from the socket in non-blocking mode
// we'll get an error (this may happen during the speculative read).
if (rc == SOCKET_ERROR) {
if (WSAGetLastError () == WSAEWOULDBLOCK)
errno = EAGAIN;
else {
wsa_assert (WSAGetLastError () == WSAENETDOWN
|| WSAGetLastError () == WSAENETRESET
|| WSAGetLastError () == WSAECONNABORTED
|| WSAGetLastError () == WSAETIMEDOUT
|| WSAGetLastError () == WSAECONNRESET
|| WSAGetLastError () == WSAECONNREFUSED
|| WSAGetLastError () == WSAENOTCONN);
errno = wsa_error_to_errno (WSAGetLastError ());
}
}
return rc == SOCKET_ERROR? -1: rc;
#else
const ssize_t rc = recv (s, data_, size_, 0);
// Several errors are OK. When speculative read is being done we may not
// be able to read a single byte from the socket. Also, SIGSTOP issued
// by a debugging tool can result in EINTR error.
if (rc == -1) {
errno_assert (errno != EBADF
&& errno != EFAULT
&& errno != EINVAL
&& errno != ENOMEM
&& errno != ENOTSOCK);
if (errno == EWOULDBLOCK || errno == EINTR)
errno = EAGAIN;
}
return static_cast <int> (rc);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_2411_3 |
crossvul-cpp_data_bad_1692_0 | /*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "lazy_entry.hpp"
#include <cstring>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
namespace
{
const int lazy_entry_grow_factor = 150; // percent
const int lazy_entry_dict_init = 5;
const int lazy_entry_list_init = 5;
}
namespace libtorrent
{
namespace
{
int fail(int* error_pos
, std::vector<lazy_entry*>& stack
, char const* start
, char const* orig_start)
{
while (!stack.empty()) {
lazy_entry* top = stack.back();
if (top->type() == lazy_entry::dict_t || top->type() == lazy_entry::list_t)
{
top->pop();
break;
}
stack.pop_back();
}
if (error_pos) *error_pos = start - orig_start;
return -1;
}
}
#define TORRENT_FAIL_BDECODE(code) do { ec = make_error_code(code); return fail(error_pos, stack, start, orig_start); } while (false)
namespace { bool numeric(char c) { return c >= '0' && c <= '9'; } }
// fills in 'val' with what the string between start and the
// first occurance of the delimiter is interpreted as an int.
// return the pointer to the delimiter, or 0 if there is a
// parse error. val should be initialized to zero
char const* parse_int(char const* start, char const* end, char delimiter
, boost::int64_t& val, bdecode_errors::error_code_enum& ec)
{
while (start < end && *start != delimiter)
{
if (!numeric(*start))
{
ec = bdecode_errors::expected_string;
return start;
}
if (val > INT64_MAX / 10)
{
ec = bdecode_errors::overflow;
return start;
}
val *= 10;
int digit = *start - '0';
if (val > INT64_MAX - digit)
{
ec = bdecode_errors::overflow;
return start;
}
val += digit;
++start;
}
if (*start != delimiter)
ec = bdecode_errors::expected_colon;
return start;
}
char const* find_char(char const* start, char const* end, char delimiter)
{
while (start < end && *start != delimiter) ++start;
return start;
}
// return 0 = success
int lazy_bdecode(char const* start, char const* end, lazy_entry& ret
, error_code& ec, int* error_pos, int depth_limit, int item_limit)
{
char const* const orig_start = start;
ret.clear();
if (start == end) return 0;
std::vector<lazy_entry*> stack;
stack.push_back(&ret);
while (start <= end)
{
if (stack.empty()) break; // done!
lazy_entry* top = stack.back();
if (int(stack.size()) > depth_limit) TORRENT_FAIL_BDECODE(bdecode_errors::depth_exceeded);
if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
char t = *start;
++start;
if (start >= end && t != 'e') TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
switch (top->type())
{
case lazy_entry::dict_t:
{
if (t == 'e')
{
top->set_end(start);
stack.pop_back();
continue;
}
if (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_string);
boost::int64_t len = t - '0';
bdecode_errors::error_code_enum e = bdecode_errors::no_error;
start = parse_int(start, end, ':', len, e);
if (e)
TORRENT_FAIL_BDECODE(e);
if (start + len + 1 > end)
TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
if (len < 0)
TORRENT_FAIL_BDECODE(bdecode_errors::overflow);
++start;
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
lazy_entry* ent = top->dict_append(start);
if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);
start += len;
if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
stack.push_back(ent);
t = *start;
++start;
break;
}
case lazy_entry::list_t:
{
if (t == 'e')
{
top->set_end(start);
stack.pop_back();
continue;
}
lazy_entry* ent = top->list_append();
if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);
stack.push_back(ent);
break;
}
default: break;
}
--item_limit;
if (item_limit <= 0) TORRENT_FAIL_BDECODE(bdecode_errors::limit_exceeded);
top = stack.back();
switch (t)
{
case 'd':
top->construct_dict(start - 1);
continue;
case 'l':
top->construct_list(start - 1);
continue;
case 'i':
{
char const* int_start = start;
start = find_char(start, end, 'e');
top->construct_int(int_start, start - int_start);
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
TORRENT_ASSERT(*start == 'e');
++start;
stack.pop_back();
continue;
}
default:
{
if (!numeric(t))
TORRENT_FAIL_BDECODE(bdecode_errors::expected_value);
boost::int64_t len = t - '0';
bdecode_errors::error_code_enum e = bdecode_errors::no_error;
start = parse_int(start, end, ':', len, e);
if (e)
TORRENT_FAIL_BDECODE(e);
if (start + len + 1 > end)
TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
if (len < 0)
TORRENT_FAIL_BDECODE(bdecode_errors::overflow);
++start;
top->construct_string(start, int(len));
stack.pop_back();
start += len;
continue;
}
}
return 0;
}
return 0;
}
boost::int64_t lazy_entry::int_value() const
{
TORRENT_ASSERT(m_type == int_t);
boost::int64_t val = 0;
bool negative = false;
if (*m_data.start == '-') negative = true;
bdecode_errors::error_code_enum ec = bdecode_errors::no_error;
parse_int(m_data.start + negative
, m_data.start + m_size, 'e', val, ec);
if (ec) return 0;
if (negative) val = -val;
return val;
}
lazy_entry* lazy_entry::dict_append(char const* name)
{
TORRENT_ASSERT(m_type == dict_t);
TORRENT_ASSERT(m_size <= m_capacity);
if (m_capacity == 0)
{
int capacity = lazy_entry_dict_init;
m_data.dict = new (std::nothrow) lazy_dict_entry[capacity];
if (m_data.dict == 0) return 0;
m_capacity = capacity;
}
else if (m_size == m_capacity)
{
int capacity = m_capacity * lazy_entry_grow_factor / 100;
lazy_dict_entry* tmp = new (std::nothrow) lazy_dict_entry[capacity];
if (tmp == 0) return 0;
std::memcpy(tmp, m_data.dict, sizeof(lazy_dict_entry) * m_size);
for (int i = 0; i < int(m_size); ++i) m_data.dict[i].val.release();
delete[] m_data.dict;
m_data.dict = tmp;
m_capacity = capacity;
}
TORRENT_ASSERT(m_size < m_capacity);
lazy_dict_entry& ret = m_data.dict[m_size++];
ret.name = name;
return &ret.val;
}
void lazy_entry::pop()
{
if (m_size > 0) --m_size;
}
namespace
{
// the number of decimal digits needed
// to represent the given value
int num_digits(int val)
{
int ret = 1;
while (val >= 10)
{
++ret;
val /= 10;
}
return ret;
}
}
void lazy_entry::construct_string(char const* start, int length)
{
TORRENT_ASSERT(m_type == none_t);
m_type = string_t;
m_data.start = start;
m_size = length;
m_begin = start - 1 - num_digits(length);
m_len = start - m_begin + length;
}
namespace
{
// str1 is null-terminated
// str2 is not, str2 is len2 chars
bool string_equal(char const* str1, char const* str2, int len2)
{
while (len2 > 0)
{
if (*str1 != *str2) return false;
if (*str1 == 0) return false;
++str1;
++str2;
--len2;
}
return *str1 == 0;
}
}
std::pair<std::string, lazy_entry const*> lazy_entry::dict_at(int i) const
{
TORRENT_ASSERT(m_type == dict_t);
TORRENT_ASSERT(i < int(m_size));
lazy_dict_entry const& e = m_data.dict[i];
return std::make_pair(std::string(e.name, e.val.m_begin - e.name), &e.val);
}
std::string lazy_entry::dict_find_string_value(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::string_t) return std::string();
return e->string_value();
}
pascal_string lazy_entry::dict_find_pstr(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::string_t) return pascal_string(0, 0);
return e->string_pstr();
}
lazy_entry const* lazy_entry::dict_find_string(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::string_t) return 0;
return e;
}
lazy_entry const* lazy_entry::dict_find_int(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::int_t) return 0;
return e;
}
boost::int64_t lazy_entry::dict_find_int_value(char const* name, boost::int64_t default_val) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::int_t) return default_val;
return e->int_value();
}
lazy_entry const* lazy_entry::dict_find_dict(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::dict_t) return 0;
return e;
}
lazy_entry const* lazy_entry::dict_find_dict(std::string const& name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::dict_t) return 0;
return e;
}
lazy_entry const* lazy_entry::dict_find_list(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::list_t) return 0;
return e;
}
lazy_entry* lazy_entry::dict_find(char const* name)
{
TORRENT_ASSERT(m_type == dict_t);
for (int i = 0; i < int(m_size); ++i)
{
lazy_dict_entry& e = m_data.dict[i];
if (string_equal(name, e.name, e.val.m_begin - e.name))
return &e.val;
}
return 0;
}
lazy_entry* lazy_entry::dict_find(std::string const& name)
{
TORRENT_ASSERT(m_type == dict_t);
for (int i = 0; i < int(m_size); ++i)
{
lazy_dict_entry& e = m_data.dict[i];
if (name.size() != e.val.m_begin - e.name) continue;
if (std::equal(name.begin(), name.end(), e.name))
return &e.val;
}
return 0;
}
lazy_entry* lazy_entry::list_append()
{
TORRENT_ASSERT(m_type == list_t);
TORRENT_ASSERT(m_size <= m_capacity);
if (m_capacity == 0)
{
int capacity = lazy_entry_list_init;
m_data.list = new (std::nothrow) lazy_entry[capacity];
if (m_data.list == 0) return 0;
m_capacity = capacity;
}
else if (m_size == m_capacity)
{
int capacity = m_capacity * lazy_entry_grow_factor / 100;
lazy_entry* tmp = new (std::nothrow) lazy_entry[capacity];
if (tmp == 0) return 0;
std::memcpy(tmp, m_data.list, sizeof(lazy_entry) * m_size);
for (int i = 0; i < int(m_size); ++i) m_data.list[i].release();
delete[] m_data.list;
m_data.list = tmp;
m_capacity = capacity;
}
TORRENT_ASSERT(m_size < m_capacity);
return m_data.list + (m_size++);
}
std::string lazy_entry::list_string_value_at(int i) const
{
lazy_entry const* e = list_at(i);
if (e == 0 || e->type() != lazy_entry::string_t) return std::string();
return e->string_value();
}
pascal_string lazy_entry::list_pstr_at(int i) const
{
lazy_entry const* e = list_at(i);
if (e == 0 || e->type() != lazy_entry::string_t) return pascal_string(0, 0);
return e->string_pstr();
}
boost::int64_t lazy_entry::list_int_value_at(int i, boost::int64_t default_val) const
{
lazy_entry const* e = list_at(i);
if (e == 0 || e->type() != lazy_entry::int_t) return default_val;
return e->int_value();
}
void lazy_entry::clear()
{
switch (m_type)
{
case list_t: delete[] m_data.list; break;
case dict_t: delete[] m_data.dict; break;
default: break;
}
m_data.start = 0;
m_size = 0;
m_capacity = 0;
m_type = none_t;
}
std::pair<char const*, int> lazy_entry::data_section() const
{
typedef std::pair<char const*, int> return_t;
return return_t(m_begin, m_len);
}
int line_longer_than(lazy_entry const& e, int limit)
{
int line_len = 0;
switch (e.type())
{
case lazy_entry::list_t:
line_len += 4;
if (line_len > limit) return -1;
for (int i = 0; i < e.list_size(); ++i)
{
int ret = line_longer_than(*e.list_at(i), limit - line_len);
if (ret == -1) return -1;
line_len += ret + 2;
}
break;
case lazy_entry::dict_t:
line_len += 4;
if (line_len > limit) return -1;
for (int i = 0; i < e.dict_size(); ++i)
{
line_len += 4 + e.dict_at(i).first.size();
if (line_len > limit) return -1;
int ret = line_longer_than(*e.dict_at(i).second, limit - line_len);
if (ret == -1) return -1;
line_len += ret + 1;
}
break;
case lazy_entry::string_t:
line_len += 3 + e.string_length();
break;
case lazy_entry::int_t:
{
boost::int64_t val = e.int_value();
while (val > 0)
{
++line_len;
val /= 10;
}
line_len += 2;
}
break;
case lazy_entry::none_t:
line_len += 4;
break;
}
if (line_len > limit) return -1;
return line_len;
}
std::string print_entry(lazy_entry const& e, bool single_line, int indent)
{
char indent_str[200];
memset(indent_str, ' ', 200);
indent_str[0] = ',';
indent_str[1] = '\n';
indent_str[199] = 0;
if (indent < 197 && indent >= 0) indent_str[indent+2] = 0;
std::string ret;
switch (e.type())
{
case lazy_entry::none_t: return "none";
case lazy_entry::int_t:
{
char str[100];
snprintf(str, sizeof(str), "%" PRId64, e.int_value());
return str;
}
case lazy_entry::string_t:
{
bool printable = true;
char const* str = e.string_ptr();
for (int i = 0; i < e.string_length(); ++i)
{
char c = str[i];
if (c >= 32 && c < 127) continue;
printable = false;
break;
}
ret += "'";
if (printable)
{
if (single_line && e.string_length() > 30)
{
ret.append(e.string_ptr(), 14);
ret += "...";
ret.append(e.string_ptr() + e.string_length()-14, 14);
}
else
ret.append(e.string_ptr(), e.string_length());
ret += "'";
return ret;
}
if (single_line && e.string_length() > 20)
{
for (int i = 0; i < 9; ++i)
{
char tmp[5];
snprintf(tmp, sizeof(tmp), "%02x", (unsigned char)str[i]);
ret += tmp;
}
ret += "...";
for (int i = e.string_length() - 9
, len(e.string_length()); i < len; ++i)
{
char tmp[5];
snprintf(tmp, sizeof(tmp), "%02x", (unsigned char)str[i]);
ret += tmp;
}
}
else
{
for (int i = 0; i < e.string_length(); ++i)
{
char tmp[5];
snprintf(tmp, sizeof(tmp), "%02x", (unsigned char)str[i]);
ret += tmp;
}
}
ret += "'";
return ret;
}
case lazy_entry::list_t:
{
ret += '[';
bool one_liner = line_longer_than(e, 200) != -1 || single_line;
if (!one_liner) ret += indent_str + 1;
for (int i = 0; i < e.list_size(); ++i)
{
if (i == 0 && one_liner) ret += " ";
ret += print_entry(*e.list_at(i), single_line, indent + 2);
if (i < e.list_size() - 1) ret += (one_liner?", ":indent_str);
else ret += (one_liner?" ":indent_str+1);
}
ret += "]";
return ret;
}
case lazy_entry::dict_t:
{
ret += "{";
bool one_liner = line_longer_than(e, 200) != -1 || single_line;
if (!one_liner) ret += indent_str+1;
for (int i = 0; i < e.dict_size(); ++i)
{
if (i == 0 && one_liner) ret += " ";
std::pair<std::string, lazy_entry const*> ent = e.dict_at(i);
ret += "'";
ret += ent.first;
ret += "': ";
ret += print_entry(*ent.second, single_line, indent + 2);
if (i < e.dict_size() - 1) ret += (one_liner?", ":indent_str);
else ret += (one_liner?" ":indent_str+1);
}
ret += "}";
return ret;
}
}
return ret;
}
struct bdecode_error_category : boost::system::error_category
{
virtual const char* name() const BOOST_SYSTEM_NOEXCEPT;
virtual std::string message(int ev) const BOOST_SYSTEM_NOEXCEPT;
virtual boost::system::error_condition default_error_condition(int ev) const BOOST_SYSTEM_NOEXCEPT
{ return boost::system::error_condition(ev, *this); }
};
const char* bdecode_error_category::name() const BOOST_SYSTEM_NOEXCEPT
{
return "bdecode error";
}
std::string bdecode_error_category::message(int ev) const BOOST_SYSTEM_NOEXCEPT
{
static char const* msgs[] =
{
"no error",
"expected string in bencoded string",
"expected colon in bencoded string",
"unexpected end of file in bencoded string",
"expected value (list, dict, int or string) in bencoded string",
"bencoded nesting depth exceeded",
"bencoded item count limit exceeded",
"integer overflow",
};
if (ev < 0 || ev >= int(sizeof(msgs)/sizeof(msgs[0])))
return "Unknown error";
return msgs[ev];
}
boost::system::error_category& get_bdecode_category()
{
static bdecode_error_category bdecode_category;
return bdecode_category;
}
namespace bdecode_errors
{
boost::system::error_code make_error_code(error_code_enum e)
{
return boost::system::error_code(e, get_bdecode_category());
}
}
};
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1692_0 |
crossvul-cpp_data_bad_512_0 | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "ScpFileSystem.h"
#include "Terminal.h"
#include "Common.h"
#include "Exceptions.h"
#include "Interface.h"
#include "TextsCore.h"
#include "HelpCore.h"
#include "SecureShell.h"
#include <StrUtils.hpp>
#include <stdio.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
#define FILE_OPERATION_LOOP_TERMINAL FTerminal
//---------------------------------------------------------------------------
const int coRaiseExcept = 1;
const int coExpectNoOutput = 2;
const int coWaitForLastLine = 4;
const int coOnlyReturnCode = 8;
const int coIgnoreWarnings = 16;
const int coReadProgress = 32;
const int ecRaiseExcept = 1;
const int ecIgnoreWarnings = 2;
const int ecReadProgress = 4;
const int ecDefault = ecRaiseExcept;
//---------------------------------------------------------------------------
DERIVE_EXT_EXCEPTION(EScpFileSkipped, ESkipFile);
//===========================================================================
#define MaxShellCommand fsLang
#define ShellCommandCount MaxShellCommand + 1
#define MaxCommandLen 40
struct TCommandType
{
int MinLines;
int MaxLines;
bool ModifiesFiles;
bool ChangesDirectory;
bool InteractiveCommand;
wchar_t Command[MaxCommandLen];
};
// Only one character! See TSCPFileSystem::ReadCommandOutput()
#define LastLineSeparator L":"
#define LAST_LINE L"WinSCP: this is end-of-file"
#define FIRST_LINE L"WinSCP: this is begin-of-file"
extern const TCommandType DefaultCommandSet[];
#define NationalVarCount 10
extern const wchar_t NationalVars[NationalVarCount][15];
#define CHECK_CMD DebugAssert((Cmd >=0) && (Cmd <= MaxShellCommand))
class TSessionData;
//---------------------------------------------------------------------------
class TCommandSet
{
private:
TCommandType CommandSet[ShellCommandCount];
TSessionData * FSessionData;
UnicodeString FReturnVar;
int __fastcall GetMaxLines(TFSCommand Cmd);
int __fastcall GetMinLines(TFSCommand Cmd);
bool __fastcall GetModifiesFiles(TFSCommand Cmd);
bool __fastcall GetChangesDirectory(TFSCommand Cmd);
bool __fastcall GetOneLineCommand(TFSCommand Cmd);
void __fastcall SetCommands(TFSCommand Cmd, UnicodeString value);
UnicodeString __fastcall GetCommands(TFSCommand Cmd);
UnicodeString __fastcall GetFirstLine();
bool __fastcall GetInteractiveCommand(TFSCommand Cmd);
UnicodeString __fastcall GetLastLine();
UnicodeString __fastcall GetReturnVar();
public:
__fastcall TCommandSet(TSessionData *aSessionData);
void __fastcall Default();
void __fastcall CopyFrom(TCommandSet * Source);
UnicodeString __fastcall Command(TFSCommand Cmd, const TVarRec * args, int size);
TStrings * __fastcall CreateCommandList();
UnicodeString __fastcall FullCommand(TFSCommand Cmd, const TVarRec * args, int size);
static UnicodeString __fastcall ExtractCommand(UnicodeString Command);
__property int MaxLines[TFSCommand Cmd] = { read=GetMaxLines};
__property int MinLines[TFSCommand Cmd] = { read=GetMinLines };
__property bool ModifiesFiles[TFSCommand Cmd] = { read=GetModifiesFiles };
__property bool ChangesDirectory[TFSCommand Cmd] = { read=GetChangesDirectory };
__property bool OneLineCommand[TFSCommand Cmd] = { read=GetOneLineCommand };
__property UnicodeString Commands[TFSCommand Cmd] = { read=GetCommands, write=SetCommands };
__property UnicodeString FirstLine = { read = GetFirstLine };
__property bool InteractiveCommand[TFSCommand Cmd] = { read = GetInteractiveCommand };
__property UnicodeString LastLine = { read=GetLastLine };
__property TSessionData * SessionData = { read=FSessionData, write=FSessionData };
__property UnicodeString ReturnVar = { read=GetReturnVar, write=FReturnVar };
};
//===========================================================================
const wchar_t NationalVars[NationalVarCount][15] =
{L"LANG", L"LANGUAGE", L"LC_CTYPE", L"LC_COLLATE", L"LC_MONETARY", L"LC_NUMERIC",
L"LC_TIME", L"LC_MESSAGES", L"LC_ALL", L"HUMAN_BLOCKS" };
const wchar_t FullTimeOption[] = L"--full-time";
//---------------------------------------------------------------------------
#define F false
#define T true
// TODO: remove "mf" and "cd", it is implemented in TTerminal already
const TCommandType DefaultCommandSet[ShellCommandCount] = {
// min max mf cd ia command
/*Null*/ { -1, -1, F, F, F, L"" },
/*VarValue*/ { -1, -1, F, F, F, L"echo \"$%s\"" /* variable */ },
/*LastLine*/ { -1, -1, F, F, F, L"echo \"%s" LastLineSeparator "%s\"" /* last line, return var */ },
/*FirstLine*/ { -1, -1, F, F, F, L"echo \"%s\"" /* first line */ },
/*CurrentDirectory*/ { 1, 1, F, F, F, L"pwd" },
/*ChangeDirectory*/ { 0, 0, F, T, F, L"cd %s" /* directory */ },
// list directory can be empty on permission denied, this is handled in ReadDirectory
/*ListDirectory*/ { -1, -1, F, F, F, L"%s %s \"%s\"" /* listing command, options, directory */ },
/*ListCurrentDirectory*/{ -1, -1, F, F, F, L"%s %s" /* listing command, options */ },
/*ListFile*/ { 1, 1, F, F, F, L"%s -d %s \"%s\"" /* listing command, options, file/directory */ },
/*LookupUserGroups*/ { 0, 1, F, F, F, L"groups" },
/*CopyToRemote*/ { -1, -1, T, F, T, L"scp -r %s -d -t \"%s\"" /* options, directory */ },
/*CopyToLocal*/ { -1, -1, F, F, T, L"scp -r %s -d -f \"%s\"" /* options, file */ },
/*DeleteFile*/ { 0, 0, T, F, F, L"rm -f -r \"%s\"" /* file/directory */},
/*RenameFile*/ { 0, 0, T, F, F, L"mv -f \"%s\" \"%s\"" /* file/directory, new name*/},
/*CreateDirectory*/ { 0, 0, T, F, F, L"mkdir \"%s\"" /* new directory */},
/*ChangeMode*/ { 0, 0, T, F, F, L"chmod %s %s \"%s\"" /* options, mode, filename */},
/*ChangeGroup*/ { 0, 0, T, F, F, L"chgrp %s \"%s\" \"%s\"" /* options, group, filename */},
/*ChangeOwner*/ { 0, 0, T, F, F, L"chown %s \"%s\" \"%s\"" /* options, owner, filename */},
/*HomeDirectory*/ { 0, 0, F, T, F, L"cd" },
/*Unset*/ { 0, 0, F, F, F, L"unset \"%s\"" /* variable */ },
/*Unalias*/ { 0, 0, F, F, F, L"unalias \"%s\"" /* alias */ },
/*CreateLink*/ { 0, 0, T, F, F, L"ln %s \"%s\" \"%s\"" /*symbolic (-s), filename, point to*/},
/*CopyFile*/ { 0, 0, T, F, F, L"cp -p -r -f %s \"%s\" \"%s\"" /* file/directory, target name*/},
/*AnyCommand*/ { 0, -1, T, T, F, L"%s" },
/*Lang*/ { 0, 1, F, F, F, L"printenv LANG"}
};
#undef F
#undef T
//---------------------------------------------------------------------------
__fastcall TCommandSet::TCommandSet(TSessionData *aSessionData):
FSessionData(aSessionData), FReturnVar(L"")
{
DebugAssert(FSessionData);
Default();
}
//---------------------------------------------------------------------------
void __fastcall TCommandSet::CopyFrom(TCommandSet * Source)
{
memmove(&CommandSet, Source->CommandSet, sizeof(CommandSet));
}
//---------------------------------------------------------------------------
void __fastcall TCommandSet::Default()
{
DebugAssert(sizeof(CommandSet) == sizeof(DefaultCommandSet));
memmove(&CommandSet, &DefaultCommandSet, sizeof(CommandSet));
}
//---------------------------------------------------------------------------
int __fastcall TCommandSet::GetMaxLines(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].MaxLines;
}
//---------------------------------------------------------------------------
int __fastcall TCommandSet::GetMinLines(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].MinLines;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetModifiesFiles(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].ModifiesFiles;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetChangesDirectory(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].ChangesDirectory;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetInteractiveCommand(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].InteractiveCommand;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetOneLineCommand(TFSCommand /*Cmd*/)
{
//CHECK_CMD;
// #56: we send "echo last line" from all commands on same line
// just as it was in 1.0
return True; //CommandSet[Cmd].OneLineCommand;
}
//---------------------------------------------------------------------------
void __fastcall TCommandSet::SetCommands(TFSCommand Cmd, UnicodeString value)
{
CHECK_CMD;
wcscpy(CommandSet[Cmd].Command, value.SubString(1, MaxCommandLen - 1).c_str());
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetCommands(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].Command;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::Command(TFSCommand Cmd, const TVarRec * args, int size)
{
if (args) return Format(Commands[Cmd], args, size);
else return Commands[Cmd];
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::FullCommand(TFSCommand Cmd, const TVarRec * args, int size)
{
UnicodeString Separator;
if (OneLineCommand[Cmd]) Separator = L" ; ";
else Separator = L"\n";
UnicodeString Line = Command(Cmd, args, size);
UnicodeString LastLineCmd =
Command(fsLastLine, ARRAYOFCONST((LastLine, ReturnVar)));
UnicodeString FirstLineCmd;
if (InteractiveCommand[Cmd])
FirstLineCmd = Command(fsFirstLine, ARRAYOFCONST((FirstLine))) + Separator;
UnicodeString Result;
if (!Line.IsEmpty())
Result = FORMAT(L"%s%s%s%s", (FirstLineCmd, Line, Separator, LastLineCmd));
else
Result = FORMAT(L"%s%s", (FirstLineCmd, LastLineCmd));
return Result;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetFirstLine()
{
return FIRST_LINE;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetLastLine()
{
return LAST_LINE;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetReturnVar()
{
DebugAssert(SessionData);
if (!FReturnVar.IsEmpty())
{
return UnicodeString(L'$') + FReturnVar;
}
else if (SessionData->DetectReturnVar)
{
return L'0';
}
else
{
return UnicodeString(L'$') + SessionData->ReturnVar;
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::ExtractCommand(UnicodeString Command)
{
int P = Command.Pos(L" ");
if (P > 0)
{
Command.SetLength(P-1);
}
return Command;
}
//---------------------------------------------------------------------------
TStrings * __fastcall TCommandSet::CreateCommandList()
{
TStrings * CommandList = new TStringList();
for (Integer Index = 0; Index < ShellCommandCount; Index++)
{
UnicodeString Cmd = Commands[(TFSCommand)Index];
if (!Cmd.IsEmpty())
{
Cmd = ExtractCommand(Cmd);
if ((Cmd != L"%s") && (CommandList->IndexOf(Cmd) < 0))
CommandList->Add(Cmd);
}
}
return CommandList;
}
//===========================================================================
__fastcall TSCPFileSystem::TSCPFileSystem(TTerminal * ATerminal, TSecureShell * SecureShell):
TCustomFileSystem(ATerminal)
{
FSecureShell = SecureShell;
FCommandSet = new TCommandSet(FTerminal->SessionData);
FLsFullTime = FTerminal->SessionData->SCPLsFullTime;
FOutput = new TStringList();
FProcessingCommand = false;
FOnCaptureOutput = NULL;
FFileSystemInfo.ProtocolBaseName = L"SCP";
FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
}
//---------------------------------------------------------------------------
__fastcall TSCPFileSystem::~TSCPFileSystem()
{
delete FCommandSet;
delete FOutput;
delete FSecureShell;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Open()
{
// this is used for reconnects only
FSecureShell->Open();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Close()
{
FSecureShell->Close();
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::GetActive()
{
return FSecureShell->Active;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CollectUsage()
{
FSecureShell->CollectUsage();
}
//---------------------------------------------------------------------------
const TSessionInfo & __fastcall TSCPFileSystem::GetSessionInfo()
{
return FSecureShell->GetSessionInfo();
}
//---------------------------------------------------------------------------
const TFileSystemInfo & __fastcall TSCPFileSystem::GetFileSystemInfo(bool Retrieve)
{
if (FFileSystemInfo.AdditionalInfo.IsEmpty() && Retrieve)
{
UnicodeString UName;
FTerminal->ExceptionOnFail = true;
try
{
try
{
AnyCommand(L"uname -a", NULL);
for (int Index = 0; Index < Output->Count; Index++)
{
if (Index > 0)
{
UName += L"; ";
}
UName += Output->Strings[Index];
}
}
catch(...)
{
if (!FTerminal->Active)
{
throw;
}
}
}
__finally
{
FTerminal->ExceptionOnFail = false;
}
FFileSystemInfo.RemoteSystem = UName;
}
return FFileSystemInfo;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
{
return false;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::GetStoredCredentialsTried()
{
return FSecureShell->GetStoredCredentialsTried();
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::GetUserName()
{
return FSecureShell->UserName;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Idle()
{
// Keep session alive
if ((FTerminal->SessionData->PingType != ptOff) &&
(Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
{
if ((FTerminal->SessionData->PingType == ptDummyCommand) &&
FSecureShell->Ready)
{
if (!FProcessingCommand)
{
ExecCommand(fsNull, NULL, 0, 0);
}
else
{
FTerminal->LogEvent(L"Cannot send keepalive, command is being executed");
// send at least SSH-level keepalive, if nothing else, it at least updates
// LastDataSent, no the next keepalive attempt is postponed
FSecureShell->KeepAlive();
}
}
else
{
FSecureShell->KeepAlive();
}
}
FSecureShell->Idle();
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::AbsolutePath(UnicodeString Path, bool /*Local*/)
{
return ::AbsolutePath(CurrentDirectory, Path);
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::IsCapable(int Capability) const
{
DebugAssert(FTerminal);
switch (Capability) {
case fcUserGroupListing:
case fcModeChanging:
case fcModeChangingUpload:
case fcPreservingTimestampUpload:
case fcGroupChanging:
case fcOwnerChanging:
case fcAnyCommand:
case fcShellAnyCommand:
case fcHardLink:
case fcSymbolicLink:
case fcResolveSymlink:
case fcRename:
case fcRemoteMove:
case fcRemoteCopy:
case fcRemoveCtrlZUpload:
case fcRemoveBOMUpload:
return true;
case fcTextMode:
return FTerminal->SessionData->EOLType != FTerminal->Configuration->LocalEOLType;
case fcNativeTextMode:
case fcNewerOnlyUpload:
case fcTimestampChanging:
case fcLoadingAdditionalProperties:
case fcCheckingSpaceAvailable:
case fcIgnorePermErrors:
case fcCalculatingChecksum:
case fcSecondaryShell: // has fcShellAnyCommand
case fcGroupOwnerChangingByID: // by name
case fcMoveToQueue:
case fcLocking:
case fcPreservingTimestampDirs:
case fcResumeSupport:
case fsSkipTransfer:
case fsParallelTransfers: // does not implement cpNoRecurse
return false;
case fcChangePassword:
return FSecureShell->CanChangePassword();
default:
DebugFail();
return false;
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::DelimitStr(UnicodeString Str)
{
if (!Str.IsEmpty())
{
Str = ::DelimitStr(Str, L"\\`$\"");
if (Str[1] == L'-') Str = L"./"+Str;
}
return Str;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::EnsureLocation()
{
if (!FCachedDirectoryChange.IsEmpty())
{
FTerminal->LogEvent(FORMAT(L"Locating to cached directory \"%s\".",
(FCachedDirectoryChange)));
UnicodeString Directory = FCachedDirectoryChange;
FCachedDirectoryChange = L"";
try
{
ChangeDirectory(Directory);
}
catch(...)
{
// when location to cached directory fails, pretend again
// location in cached directory
// here used to be check (CurrentDirectory != Directory), but it is
// false always (current directory is already set to cached directory),
// making the condition below useless. check removed.
if (FTerminal->Active)
{
FCachedDirectoryChange = Directory;
}
throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SendCommand(const UnicodeString Cmd)
{
EnsureLocation();
UnicodeString Line;
FSecureShell->ClearStdError();
FReturnCode = 0;
FOutput->Clear();
// We suppose, that 'Cmd' already contains command that ensures,
// that 'LastLine' will be printed
FSecureShell->SendLine(Cmd);
FProcessingCommand = true;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::IsTotalListingLine(const UnicodeString Line)
{
// On some hosts there is not "total" but "totalt". What's the reason??
// see mail from "Jan Wiklund (SysOp)" <jan@park.se>
return !Line.SubString(1, 5).CompareIC(L"total");
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::RemoveLastLine(UnicodeString & Line,
int & ReturnCode, UnicodeString LastLine)
{
bool IsLastLine = false;
if (LastLine.IsEmpty()) LastLine = LAST_LINE;
// #55: fixed so, even when last line of command output does not
// contain CR/LF, we can recognize last line
int Pos = Line.Pos(LastLine);
if (Pos)
{
// 2003-07-14: There must be nothing after return code number to
// consider string as last line. This fixes bug with 'set' command
// in console window
UnicodeString ReturnCodeStr = Line.SubString(Pos + LastLine.Length() + 1,
Line.Length() - Pos + LastLine.Length());
if (TryStrToInt(ReturnCodeStr, ReturnCode))
{
IsLastLine = true;
Line.SetLength(Pos - 1);
}
}
return IsLastLine;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::IsLastLine(UnicodeString & Line)
{
bool Result = false;
try
{
Result = RemoveLastLine(Line, FReturnCode, FCommandSet->LastLine);
}
catch (Exception &E)
{
FTerminal->TerminalError(&E, LoadStr(CANT_DETECT_RETURN_CODE));
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SkipFirstLine()
{
UnicodeString Line = FSecureShell->ReceiveLine();
if (Line != FCommandSet->FirstLine)
{
FTerminal->TerminalError(NULL, FMTLOAD(FIRST_LINE_EXPECTED, (Line)));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadCommandOutput(int Params, const UnicodeString * Cmd)
{
try
{
if (Params & coWaitForLastLine)
{
UnicodeString Line;
bool IsLast;
unsigned int Total = 0;
// #55: fixed so, even when last line of command output does not
// contain CR/LF, we can recognize last line
do
{
Line = FSecureShell->ReceiveLine();
IsLast = IsLastLine(Line);
if (!IsLast || !Line.IsEmpty())
{
FOutput->Add(Line);
if (FLAGSET(Params, coReadProgress))
{
Total++;
if (Total % 10 == 0)
{
bool Cancel; //dummy
FTerminal->DoReadDirectoryProgress(Total, 0, Cancel);
}
}
}
}
while (!IsLast);
}
if (Params & coRaiseExcept)
{
UnicodeString Message = FSecureShell->GetStdError();
if ((Params & coExpectNoOutput) && FOutput->Count)
{
if (!Message.IsEmpty()) Message += L"\n";
Message += FOutput->Text;
}
while (!Message.IsEmpty() && (Message.LastDelimiter(L"\n\r") == Message.Length()))
{
Message.SetLength(Message.Length() - 1);
}
bool WrongReturnCode =
(ReturnCode > 1) || (ReturnCode == 1 && !(Params & coIgnoreWarnings));
if (FOnCaptureOutput != NULL)
{
FOnCaptureOutput(IntToStr(ReturnCode), cotExitCode);
}
if (Params & coOnlyReturnCode && WrongReturnCode)
{
FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
}
else if (!(Params & coOnlyReturnCode) &&
((!Message.IsEmpty() && ((FOutput->Count == 0) || !(Params & coIgnoreWarnings))) ||
WrongReturnCode))
{
DebugAssert(Cmd != NULL);
FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED, (*Cmd, ReturnCode, Message)));
}
}
}
__finally
{
FProcessingCommand = false;
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ExecCommand(const UnicodeString & Cmd, int Params,
const UnicodeString & CmdString)
{
if (Params < 0)
{
Params = ecDefault;
}
TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
SendCommand(Cmd);
int COParams = coWaitForLastLine;
if (Params & ecRaiseExcept) COParams |= coRaiseExcept;
if (Params & ecIgnoreWarnings) COParams |= coIgnoreWarnings;
if (Params & ecReadProgress) COParams |= coReadProgress;
ReadCommandOutput(COParams, &CmdString);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
int size, int Params)
{
if (Params < 0) Params = ecDefault;
UnicodeString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
UnicodeString Command = FCommandSet->Command(Cmd, args, size);
ExecCommand(FullCommand, Params, Command);
if (Params & ecRaiseExcept)
{
Integer MinL = FCommandSet->MinLines[Cmd];
Integer MaxL = FCommandSet->MaxLines[Cmd];
if (((MinL >= 0) && (MinL > FOutput->Count)) ||
((MaxL >= 0) && (MaxL > FOutput->Count)))
{
FTerminal->TerminalError(FmtLoadStr(INVALID_OUTPUT_ERROR,
ARRAYOFCONST((FullCommand, Output->Text))));
}
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::GetCurrentDirectory()
{
return FCurrentDirectory;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DoStartup()
{
// Capabilities of SCP protocol are fixed
FTerminal->SaveCapabilities(FFileSystemInfo);
// SkipStartupMessage and DetectReturnVar must succeed,
// otherwise session is to be closed.
try
{
FTerminal->ExceptionOnFail = true;
SkipStartupMessage();
if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
FTerminal->ExceptionOnFail = false;
}
catch (Exception & E)
{
FTerminal->FatalError(&E, L"");
}
// Needs to be done before UnsetNationalVars()
DetectUtf();
#define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
COND_OPER(ClearAliases);
COND_OPER(UnsetNationalVars);
#undef COND_OPER
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DetectUtf()
{
switch (FTerminal->SessionData->NotUtf)
{
case asOn:
FSecureShell->UtfStrings = false; // noop
break;
case asOff:
FSecureShell->UtfStrings = true;
break;
default:
DebugFail();
case asAuto:
FSecureShell->UtfStrings = false; // noop
try
{
ExecCommand(fsLang, NULL, 0, false);
if ((FOutput->Count >= 1) &&
ContainsText(FOutput->Strings[0], L"UTF-8"))
{
FSecureShell->UtfStrings = true;
}
}
catch (Exception & E)
{
// ignore non-fatal errors
if (!FTerminal->Active)
{
throw;
}
}
break;
}
if (FSecureShell->UtfStrings)
{
FTerminal->LogEvent(L"We will use UTF-8");
}
else
{
FTerminal->LogEvent(L"We will not use UTF-8");
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SkipStartupMessage()
{
try
{
FTerminal->LogEvent(L"Skipping host startup message (if any).");
ExecCommand(fsNull, NULL, 0, 0);
}
catch (Exception & E)
{
FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR), 0, HELP_SKIP_STARTUP_MESSAGE_ERROR);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::LookupUsersGroups()
{
ExecCommand(fsLookupUsersGroups);
FTerminal->FUsers.Clear();
FTerminal->FGroups.Clear();
if (FOutput->Count > 0)
{
UnicodeString Groups = FOutput->Strings[0];
while (!Groups.IsEmpty())
{
UnicodeString NewGroup = CutToChar(Groups, L' ', false);
FTerminal->FGroups.Add(TRemoteToken(NewGroup));
FTerminal->FMembership.Add(TRemoteToken(NewGroup));
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DetectReturnVar()
{
// This suppose that something was already executed (probably SkipStartupMessage())
// or return code variable is already set on start up.
try
{
// #60 17.10.01: "status" and "?" switched
UnicodeString ReturnVars[2] = { L"status", L"?" };
UnicodeString NewReturnVar = L"";
FTerminal->LogEvent(L"Detecting variable containing return code of last command.");
for (int Index = 0; Index < 2; Index++)
{
bool Success = true;
try
{
FTerminal->LogEvent(FORMAT(L"Trying \"$%s\".", (ReturnVars[Index])));
ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255))
{
FTerminal->LogEvent(L"The response is not numerical exit code");
Abort();
}
}
catch (EFatal &E)
{
// if fatal error occurs, we need to exit ...
throw;
}
catch (Exception &E)
{
// ...otherwise, we will try next variable (if any)
Success = false;
}
if (Success)
{
NewReturnVar = ReturnVars[Index];
break;
}
}
if (NewReturnVar.IsEmpty())
{
EXCEPTION;
}
else
{
FCommandSet->ReturnVar = NewReturnVar;
FTerminal->LogEvent(FORMAT(L"Return code variable \"%s\" selected.",
(FCommandSet->ReturnVar)));
}
}
catch (Exception &E)
{
FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ClearAlias(UnicodeString Alias)
{
if (!Alias.IsEmpty())
{
// this command usually fails, because there will never be
// aliases on all commands -> see last False parameter
ExecCommand(fsUnalias, ARRAYOFCONST((Alias)), false);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ClearAliases()
{
try
{
FTerminal->LogEvent(L"Clearing all aliases.");
ClearAlias(TCommandSet::ExtractCommand(FTerminal->SessionData->ListingCommand));
TStrings * CommandList = FCommandSet->CreateCommandList();
try
{
for (int Index = 0; Index < CommandList->Count; Index++)
{
ClearAlias(CommandList->Strings[Index]);
}
}
__finally
{
delete CommandList;
}
}
catch (Exception &E)
{
FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::UnsetNationalVars()
{
try
{
FTerminal->LogEvent(L"Clearing national user variables.");
for (int Index = 0; Index < NationalVarCount; Index++)
{
ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
}
}
catch (Exception &E)
{
FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadCurrentDirectory()
{
if (FCachedDirectoryChange.IsEmpty())
{
ExecCommand(fsCurrentDirectory);
FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
}
else
{
FCurrentDirectory = FCachedDirectoryChange;
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::HomeDirectory()
{
ExecCommand(fsHomeDirectory);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::AnnounceFileListOperation()
{
// noop
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ChangeDirectory(const UnicodeString Directory)
{
UnicodeString ToDir;
if (!Directory.IsEmpty() &&
((Directory[1] != L'~') || (Directory.SubString(1, 2) == L"~ ")))
{
ToDir = L"\"" + DelimitStr(Directory) + L"\"";
}
else
{
ToDir = DelimitStr(Directory);
}
ExecCommand(fsChangeDirectory, ARRAYOFCONST((ToDir)));
FCachedDirectoryChange = L"";
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
{
FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
{
DebugAssert(FileList);
// emptying file list moved before command execution
FileList->Reset();
bool Again;
do
{
Again = false;
try
{
int Params = ecDefault | ecReadProgress |
FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
const wchar_t * Options =
((FLsFullTime == asAuto) || (FLsFullTime == asOn)) ? FullTimeOption : L"";
bool ListCurrentDirectory = (FileList->Directory == FTerminal->CurrentDirectory);
if (ListCurrentDirectory)
{
FTerminal->LogEvent(L"Listing current directory.");
ExecCommand(fsListCurrentDirectory,
ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options)), Params);
}
else
{
FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".",
(FileList->Directory)));
ExecCommand(fsListDirectory,
ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options,
DelimitStr(FileList->Directory))),
Params);
}
TRemoteFile * File;
// If output is not empty, we have successfully got file listing,
// otherwise there was an error, in case it was "permission denied"
// we try to get at least parent directory (see "else" statement below)
if (FOutput->Count > 0)
{
// Copy LS command output, because eventual symlink analysis would
// modify FTerminal->Output
TStringList * OutputCopy = new TStringList();
try
{
OutputCopy->Assign(FOutput);
// delete leading "total xxx" line
// On some hosts there is not "total" but "totalt". What's the reason??
// see mail from "Jan Wiklund (SysOp)" <jan@park.se>
if (IsTotalListingLine(OutputCopy->Strings[0]))
{
OutputCopy->Delete(0);
}
for (int Index = 0; Index < OutputCopy->Count; Index++)
{
UnicodeString OutputLine = OutputCopy->Strings[Index];
if (!OutputLine.IsEmpty())
{
File = CreateRemoteFile(OutputCopy->Strings[Index]);
FileList->AddFile(File);
}
}
}
__finally
{
delete OutputCopy;
}
}
else
{
bool Empty;
if (ListCurrentDirectory)
{
// Empty file list -> probably "permission denied", we
// at least get link to parent directory ("..")
FTerminal->ReadFile(
UnixIncludeTrailingBackslash(FTerminal->FFiles->Directory) +
PARENTDIRECTORY, File);
Empty = (File == NULL);
if (!Empty)
{
DebugAssert(File->IsParentDirectory);
FileList->AddFile(File);
}
}
else
{
Empty = true;
}
if (Empty)
{
throw ExtException(
NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
HELP_EMPTY_DIRECTORY);
}
}
if (FLsFullTime == asAuto)
{
FTerminal->LogEvent(
FORMAT(L"Directory listing with %s succeed, next time all errors during "
"directory listing will be displayed immediately.",
(FullTimeOption)));
FLsFullTime = asOn;
}
}
catch(Exception & E)
{
if (FTerminal->Active)
{
if (FLsFullTime == asAuto)
{
FTerminal->Log->AddException(&E);
FLsFullTime = asOff;
Again = true;
FTerminal->LogEvent(
FORMAT(L"Directory listing with %s failed, try again regular listing.",
(FullTimeOption)));
}
else
{
throw;
}
}
else
{
throw;
}
}
}
while (Again);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
TRemoteFile *& File)
{
CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadFile(const UnicodeString FileName,
TRemoteFile *& File)
{
CustomReadFile(FileName, File, NULL);
}
//---------------------------------------------------------------------------
TRemoteFile * __fastcall TSCPFileSystem::CreateRemoteFile(
const UnicodeString & ListingStr, TRemoteFile * LinkedByFile)
{
TRemoteFile * File = new TRemoteFile(LinkedByFile);
try
{
File->Terminal = FTerminal;
File->ListingStr = ListingStr;
File->ShiftTimeInSeconds(TimeToSeconds(FTerminal->SessionData->TimeDifference));
File->Complete();
}
catch(...)
{
delete File;
throw;
}
return File;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CustomReadFile(const UnicodeString FileName,
TRemoteFile *& File, TRemoteFile * ALinkedByFile)
{
File = NULL;
int Params = ecDefault |
FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
// the auto-detection of --full-time support is not implemented for fsListFile,
// so we use it only if we already know that it is supported (asOn).
const wchar_t * Options = (FLsFullTime == asOn) ? FullTimeOption : L"";
ExecCommand(fsListFile,
ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options, DelimitStr(FileName))),
Params);
if (FOutput->Count)
{
int LineIndex = 0;
if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
{
LineIndex++;
}
File = CreateRemoteFile(FOutput->Strings[LineIndex], ALinkedByFile);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DeleteFile(const UnicodeString FileName,
const TRemoteFile * File, int Params, TRmSessionAction & Action)
{
DebugUsedParam(File);
DebugUsedParam(Params);
Action.Recursive();
DebugAssert(FLAGCLEAR(Params, dfNoRecursive) || (File && File->IsSymLink));
ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
const UnicodeString NewName)
{
ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
const UnicodeString NewName)
{
UnicodeString DelimitedFileName = DelimitStr(FileName);
UnicodeString DelimitedNewName = DelimitStr(NewName);
const UnicodeString AdditionalSwitches = L"-T";
try
{
ExecCommand(fsCopyFile, ARRAYOFCONST((AdditionalSwitches, DelimitedFileName, DelimitedNewName)));
}
catch (Exception & E)
{
if (FTerminal->Active)
{
// The -T is GNU switch and may not be available on all platforms.
// https://lists.gnu.org/archive/html/bug-coreutils/2004-07/msg00000.html
FTerminal->LogEvent(FORMAT(L"Attempt with %s failed, trying without", (AdditionalSwitches)));
ExecCommand(fsCopyFile, ARRAYOFCONST((L"", DelimitedFileName, DelimitedNewName)));
}
else
{
throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
{
ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CreateLink(const UnicodeString FileName,
const UnicodeString PointTo, bool Symbolic)
{
ExecCommand(fsCreateLink,
ARRAYOFCONST((Symbolic ? L"-s" : L"", DelimitStr(PointTo), DelimitStr(FileName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ChangeFileToken(const UnicodeString & DelimitedName,
const TRemoteToken & Token, TFSCommand Cmd, const UnicodeString & RecursiveStr)
{
UnicodeString Str;
if (Token.IDValid)
{
Str = IntToStr(int(Token.ID));
}
else if (Token.NameValid)
{
Str = Token.Name;
}
if (!Str.IsEmpty())
{
ExecCommand(Cmd, ARRAYOFCONST((RecursiveStr, Str, DelimitedName)));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ChangeFileProperties(const UnicodeString FileName,
const TRemoteFile * File, const TRemoteProperties * Properties,
TChmodSessionAction & Action)
{
DebugAssert(Properties);
bool IsDirectory = File && File->IsDirectory;
bool Recursive = Properties->Recursive && IsDirectory;
UnicodeString RecursiveStr = Recursive ? L"-R" : L"";
UnicodeString DelimitedName = DelimitStr(FileName);
// change group before permissions as chgrp change permissions
if (Properties->Valid.Contains(vpGroup))
{
ChangeFileToken(DelimitedName, Properties->Group, fsChangeGroup, RecursiveStr);
}
if (Properties->Valid.Contains(vpOwner))
{
ChangeFileToken(DelimitedName, Properties->Owner, fsChangeOwner, RecursiveStr);
}
if (Properties->Valid.Contains(vpRights))
{
TRights Rights = Properties->Rights;
// if we don't set modes recursively, we may add X at once with other
// options. Otherwise we have to add X after recursive command
if (!Recursive && IsDirectory && Properties->AddXToDirectories)
Rights.AddExecute();
Action.Rights(Rights);
if (Recursive)
{
Action.Recursive();
}
if ((Rights.NumberSet | Rights.NumberUnset) != TRights::rfNo)
{
ExecCommand(fsChangeMode,
ARRAYOFCONST((RecursiveStr, Rights.SimplestStr, DelimitedName)));
}
// if file is directory and we do recursive mode settings with
// add-x-to-directories option on, add those X
if (Recursive && IsDirectory && Properties->AddXToDirectories)
{
Rights.AddExecute();
ExecCommand(fsChangeMode,
ARRAYOFCONST((L"", Rights.SimplestStr, DelimitedName)));
}
}
else
{
Action.Cancel();
}
DebugAssert(!Properties->Valid.Contains(vpLastAccess));
DebugAssert(!Properties->Valid.Contains(vpModification));
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::LoadFilesProperties(TStrings * /*FileList*/ )
{
DebugFail();
return false;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
TStrings * /*FileList*/, TStrings * /*Checksums*/,
TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CustomCommandOnFile(const UnicodeString FileName,
const TRemoteFile * File, UnicodeString Command, int Params,
TCaptureOutputEvent OutputEvent)
{
DebugAssert(File);
bool Dir = File->IsDirectory && FTerminal->CanRecurseToDirectory(File);
if (Dir && (Params & ccRecursive))
{
TCustomCommandParams AParams;
AParams.Command = Command;
AParams.Params = Params;
AParams.OutputEvent = OutputEvent;
FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
&AParams);
}
if (!Dir || (Params & ccApplyToDirectories))
{
TCustomCommandData Data(FTerminal);
UnicodeString Cmd = TRemoteCustomCommand(
Data, FTerminal->CurrentDirectory, FileName, L"").
Complete(Command, true);
if (!FTerminal->DoOnCustomCommand(Cmd))
{
AnyCommand(Cmd, OutputEvent);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CaptureOutput(const UnicodeString & AddedLine, TCaptureOutputType OutputType)
{
int ReturnCode;
UnicodeString Line = AddedLine;
// TSecureShell never uses cotExitCode
DebugAssert((OutputType == cotOutput) || (OutputType == cotError));
if ((OutputType == cotError) || DebugAlwaysFalse(OutputType == cotExitCode) ||
!RemoveLastLine(Line, ReturnCode) ||
!Line.IsEmpty())
{
DebugAssert(FOnCaptureOutput != NULL);
FOnCaptureOutput(Line, OutputType);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::AnyCommand(const UnicodeString Command,
TCaptureOutputEvent OutputEvent)
{
DebugAssert(FSecureShell->OnCaptureOutput == NULL);
if (OutputEvent != NULL)
{
FSecureShell->OnCaptureOutput = CaptureOutput;
FOnCaptureOutput = OutputEvent;
}
try
{
ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)),
ecDefault | ecIgnoreWarnings);
}
__finally
{
FOnCaptureOutput = NULL;
FSecureShell->OnCaptureOutput = NULL;
}
}
//---------------------------------------------------------------------------
TStrings * __fastcall TSCPFileSystem::GetFixedPaths()
{
return NULL;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SpaceAvailable(const UnicodeString Path,
TSpaceAvailable & /*ASpaceAvailable*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
// transfer protocol
//---------------------------------------------------------------------------
unsigned int __fastcall TSCPFileSystem::ConfirmOverwrite(
const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName, TOperationSide Side,
const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
int Params, TFileOperationProgressType * OperationProgress)
{
TSuspendFileOperationProgress Suspend(OperationProgress);
TQueryButtonAlias Aliases[3];
Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
TQueryParams QueryParams(qpNeverAskAgainCheck);
QueryParams.Aliases = Aliases;
QueryParams.AliasesCount = LENOF(Aliases);
unsigned int Answer =
FTerminal->ConfirmFileOverwrite(
SourceFullFileName, TargetFileName, FileParams,
qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll,
&QueryParams, Side, CopyParam, Params, OperationProgress);
return Answer;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
{
// Taken from scp.c response() and modified
unsigned char Resp;
FSecureShell->Receive(&Resp, 1);
switch (Resp)
{
case 0: /* ok */
FTerminal->LogEvent(L"SCP remote side confirmation (0)");
return;
default:
case 1: /* error */
case 2: /* fatal error */
// pscp adds 'Resp' to 'Msg', why?
UnicodeString Msg = FSecureShell->ReceiveLine();
UnicodeString Line = UnicodeString(static_cast<char>(Resp)) + Msg;
if (IsLastLine(Line))
{
if (GotLastLine != NULL)
{
*GotLastLine = true;
}
/* TODO 1 : Show stderror to user? */
FSecureShell->ClearStdError();
try
{
ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
}
catch(...)
{
// when ReadCommandOutput() fails than remote SCP is terminated already
if (GotLastLine != NULL)
{
*GotLastLine = true;
}
throw;
}
}
else if (Resp == 1)
{
// While the OpenSSH scp client distinguishes the 1 for error and 2 for fatal errors,
// the OpenSSH scp server always sends 1 even for fatal errors. Using the error message to tell
// which errors are fatal and which are not.
// This error list is valid for OpenSSH 5.3p1 and 7.2p2
if (SameText(Msg, L"scp: ambiguous target") ||
StartsText(L"scp: error: unexpected filename: ", Msg) ||
StartsText(L"scp: protocol error: ", Msg))
{
FTerminal->LogEvent(L"SCP remote side error (1), fatal error detected from error message");
Resp = 2;
FScpFatalError = true;
}
else
{
FTerminal->LogEvent(L"SCP remote side error (1)");
}
}
else
{
FTerminal->LogEvent(L"SCP remote side fatal error (2)");
FScpFatalError = true;
}
if (Resp == 1)
{
throw EScpFileSkipped(NULL, Msg);
}
else
{
throw EScp(NULL, Msg);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
const UnicodeString TargetDir, const TCopyParamType * CopyParam,
int Params, TFileOperationProgressType * OperationProgress,
TOnceDoneOperation & OnceDoneOperation)
{
// scp.c: source(), toremote()
DebugAssert(FilesToCopy && OperationProgress);
Params &= ~(cpAppend | cpResume);
UnicodeString Options = L"";
bool CheckExistence = UnixSamePath(TargetDir, FTerminal->CurrentDirectory) &&
(FTerminal->FFiles != NULL) && FTerminal->FFiles->Loaded;
bool CopyBatchStarted = false;
bool Failed = true;
bool GotLastLine = false;
UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir);
if (CopyParam->PreserveRights) Options = L"-p";
if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
FScpFatalError = false;
SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
SkipFirstLine();
try
{
try
{
SCPResponse(&GotLastLine);
// This can happen only if SCP command is not executed and return code is 0
// It has never happened to me (return code is usually 127)
if (GotLastLine)
{
throw Exception(L"");
}
}
catch(Exception & E)
{
if (GotLastLine && FTerminal->Active)
{
FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
}
else
{
throw;
}
}
CopyBatchStarted = true;
for (int IFile = 0; (IFile < FilesToCopy->Count) &&
!OperationProgress->Cancel; IFile++)
{
UnicodeString FileName = FilesToCopy->Strings[IFile];
bool CanProceed;
UnicodeString FileNameOnly =
FTerminal->ChangeFileName(
CopyParam, ExtractFileName(FileName), osLocal, true);
if (CheckExistence)
{
// previously there was assertion on FTerminal->FFiles->Loaded, but it
// fails for scripting, if 'ls' is not issued before.
// formally we should call CheckRemoteFile here but as checking is for
// free here (almost) ...
TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
if (File != NULL)
{
unsigned int Answer;
if (File->IsDirectory)
{
UnicodeString Message = FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly));
TQueryParams QueryParams(qpNeverAskAgainCheck);
TSuspendFileOperationProgress Suspend(OperationProgress);
Answer = FTerminal->ConfirmFileOverwrite(
FileName, FileNameOnly, NULL,
qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll,
&QueryParams, osRemote, CopyParam, Params, OperationProgress, Message);
}
else
{
__int64 MTime;
TOverwriteFileParams FileParams;
FTerminal->OpenLocalFile(FileName, GENERIC_READ,
NULL, NULL, NULL, &MTime, NULL,
&FileParams.SourceSize);
FileParams.SourceTimestamp = UnixToDateTime(MTime,
FTerminal->SessionData->DSTMode);
FileParams.DestSize = File->Size;
FileParams.DestTimestamp = File->Modification;
Answer = ConfirmOverwrite(FileName, FileNameOnly, osRemote,
&FileParams, CopyParam, Params, OperationProgress);
}
switch (Answer)
{
case qaYes:
CanProceed = true;
break;
case qaCancel:
OperationProgress->SetCancelAtLeast(csCancel);
case qaNo:
CanProceed = false;
break;
default:
DebugFail();
break;
}
}
else
{
CanProceed = true;
}
}
else
{
CanProceed = true;
}
if (CanProceed)
{
if (FTerminal->SessionData->CacheDirectories)
{
FTerminal->DirectoryModified(TargetDir, false);
if (DirectoryExists(ApiPath(FileName)))
{
FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
FileNameOnly, true);
}
}
void * Item = static_cast<void *>(FilesToCopy->Objects[IFile]);
try
{
SCPSource(FileName, TargetDirFull,
CopyParam, Params, OperationProgress, 0);
FTerminal->OperationFinish(OperationProgress, Item, FileName, true, OnceDoneOperation);
}
catch (EScpFileSkipped &E)
{
TQueryParams Params(qpAllowContinueOnError);
TSuspendFileOperationProgress Suspend(OperationProgress);
if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
qaOK | qaAbort, &Params, qtError) == qaAbort)
{
OperationProgress->SetCancel(csCancel);
}
FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
if (!FTerminal->HandleException(&E))
{
throw;
}
}
catch (ESkipFile &E)
{
FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
{
TSuspendFileOperationProgress Suspend(OperationProgress);
// If ESkipFile occurs, just log it and continue with next file
if (!FTerminal->HandleException(&E))
{
throw;
}
}
}
catch (...)
{
FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
throw;
}
}
}
Failed = false;
}
__finally
{
// Tell remote side, that we're done.
if (FTerminal->Active)
{
try
{
if (!GotLastLine)
{
if (CopyBatchStarted && !FScpFatalError)
{
// What about case, remote side sends fatal error ???
// (Not sure, if it causes remote side to terminate scp)
FSecureShell->SendLine(L"E");
SCPResponse();
}
/* TODO 1 : Show stderror to user? */
FSecureShell->ClearStdError();
ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
(Failed ? 0 : coRaiseExcept));
}
}
catch (Exception &E)
{
// Only log error message (it should always succeed, but
// some pending error maybe in queue) }
FTerminal->Log->AddException(&E);
}
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Source(
TLocalFileHandle & /*Handle*/, const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/,
const TCopyParamType * /*CopyParam*/, int /*Params*/,
TFileOperationProgressType * /*OperationProgress*/, unsigned int /*Flags*/,
TUploadSessionAction & /*Action*/, bool & /*ChildError*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName,
const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
TFileOperationProgressType * OperationProgress, int Level)
{
UnicodeString DestFileName =
FTerminal->ChangeFileName(
CopyParam, ExtractFileName(FileName), osLocal, Level == 0);
FTerminal->LogEvent(FORMAT(L"File: \"%s\"", (FileName)));
OperationProgress->SetFile(FileName, false);
if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
{
throw ESkipFile();
}
TLocalFileHandle Handle;
FTerminal->OpenLocalFile(FileName, GENERIC_READ, Handle);
OperationProgress->SetFileInProgress();
if (Handle.Directory)
{
SCPDirectorySource(FileName, TargetDir, CopyParam, Params, OperationProgress, Level);
}
else
{
UnicodeString AbsoluteFileName = FTerminal->AbsolutePath(TargetDir + DestFileName, false);
DebugAssert(Handle.Handle);
std::unique_ptr<TStream> Stream(new TSafeHandleStream((THandle)Handle.Handle));
// File is regular file (not directory)
FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
OperationProgress->SetLocalSize(Handle.Size);
// Suppose same data size to transfer as to read
// (not true with ASCII transfer)
OperationProgress->SetTransferSize(OperationProgress->LocalSize);
OperationProgress->SetTransferringFile(false);
FTerminal->SelectSourceTransferMode(Handle, CopyParam);
TUploadSessionAction Action(FTerminal->ActionLog);
Action.FileName(ExpandUNCFileName(FileName));
Action.Destination(AbsoluteFileName);
TRights Rights = CopyParam->RemoteFileRights(Handle.Attrs);
try
{
// During ASCII transfer we will load whole file to this buffer
// than convert EOL and send it at once, because before converting EOL
// we can't know its size
TFileBuffer AsciiBuf;
bool ConvertToken = false;
do
{
// Buffer for one block of data
TFileBuffer BlockBuf;
// This is crucial, if it fails during file transfer, it's fatal error
FILE_OPERATION_LOOP_BEGIN
{
BlockBuf.LoadStream(Stream.get(), OperationProgress->LocalBlockSize(), true);
}
FILE_OPERATION_LOOP_END_EX(
FMTLOAD(READ_ERROR, (FileName)),
FLAGMASK(!OperationProgress->TransferringFile, folAllowSkip));
OperationProgress->AddLocallyUsed(BlockBuf.Size);
// We do ASCII transfer: convert EOL of current block
// (we don't convert whole buffer, cause it would produce
// huge memory-transfers while inserting/deleting EOL characters)
// Than we add current block to file buffer
if (OperationProgress->AsciiTransfer)
{
int ConvertParams =
FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
FTerminal->SessionData->EOLType,
ConvertParams, ConvertToken);
BlockBuf.Memory->Seek(0, soFromBeginning);
AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
// We don't need it any more
BlockBuf.Memory->Clear();
// Calculate total size to sent (assume that ratio between
// size of source and size of EOL-transformed data would remain same)
// First check if file contains anything (div by zero!)
if (OperationProgress->LocallyUsed)
{
__int64 X = OperationProgress->LocalSize;
X *= AsciiBuf.Size;
X /= OperationProgress->LocallyUsed;
OperationProgress->ChangeTransferSize(X);
}
else
{
OperationProgress->ChangeTransferSize(0);
}
}
// We send file information on first pass during BINARY transfer
// and on last pass during ASCII transfer
// BINARY: We succeeded reading first buffer from file, hopefully
// we will be able to read whole, so we send file info to remote side
// This is done, because when reading fails we can't interrupt sending
// (don't know how to tell other side that it failed)
if (!OperationProgress->TransferringFile &&
(!OperationProgress->AsciiTransfer || OperationProgress->IsLocallyDone()))
{
UnicodeString Buf;
if (CopyParam->PreserveTime)
{
// Send last file access and modification time
// TVarRec don't understand 'unsigned int' -> we use sprintf()
Buf.sprintf(L"T%lu 0 %lu 0", static_cast<unsigned long>(Handle.MTime),
static_cast<unsigned long>(Handle.ATime));
FSecureShell->SendLine(Buf);
SCPResponse();
}
// Send file modes (rights), filesize and file name
// TVarRec don't understand 'unsigned int' -> we use sprintf()
Buf.sprintf(L"C%s %Ld %s",
Rights.Octal.data(),
(OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
OperationProgress->LocalSize),
DestFileName.data());
FSecureShell->SendLine(Buf);
SCPResponse();
// Indicate we started transferring file, we need to finish it
// If not, it's fatal error
OperationProgress->SetTransferringFile(true);
// If we're doing ASCII transfer, this is last pass
// so we send whole file
/* TODO : We can't send file above 32bit size in ASCII mode! */
if (OperationProgress->AsciiTransfer)
{
FTerminal->LogEvent(FORMAT(L"Sending ASCII data (%u bytes)",
(AsciiBuf.Size)));
// Should be equal, just in case it's rounded (see above)
OperationProgress->ChangeTransferSize(AsciiBuf.Size);
while (!OperationProgress->IsTransferDone())
{
unsigned long BlockSize = OperationProgress->TransferBlockSize();
FSecureShell->Send(
reinterpret_cast<unsigned char *>(AsciiBuf.Data + (unsigned int)OperationProgress->TransferredSize),
BlockSize);
OperationProgress->AddTransferred(BlockSize);
if (OperationProgress->Cancel == csCancelTransfer)
{
throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
}
}
}
}
// At end of BINARY transfer pass, send current block
if (!OperationProgress->AsciiTransfer)
{
if (!OperationProgress->TransferredSize)
{
FTerminal->LogEvent(FORMAT(L"Sending BINARY data (first block, %u bytes)",
(BlockBuf.Size)));
}
else if (FTerminal->Configuration->ActualLogProtocol >= 1)
{
FTerminal->LogEvent(FORMAT(L"Sending BINARY data (%u bytes)",
(BlockBuf.Size)));
}
FSecureShell->Send(reinterpret_cast<const unsigned char *>(BlockBuf.Data), BlockBuf.Size);
OperationProgress->AddTransferred(BlockBuf.Size);
}
if ((OperationProgress->Cancel == csCancelTransfer) ||
(OperationProgress->Cancel == csCancel && !OperationProgress->TransferringFile))
{
throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
}
}
while (!OperationProgress->IsLocallyDone() || !OperationProgress->IsTransferDone());
FSecureShell->SendNull();
try
{
SCPResponse();
// If one of two following exceptions occurs, it means, that remote
// side already know, that file transfer finished, even if it failed
// so we don't have to throw EFatal
}
catch (EScp &E)
{
// SCP protocol fatal error
OperationProgress->SetTransferringFile(false);
throw;
}
catch (EScpFileSkipped &E)
{
// SCP protocol non-fatal error
OperationProgress->SetTransferringFile(false);
throw;
}
// We succeeded transferring file, from now we can handle exceptions
// normally -> no fatal error
OperationProgress->SetTransferringFile(false);
}
catch (Exception &E)
{
// EScpFileSkipped is derived from ESkipFile,
// but is does not indicate file skipped by user here
if (dynamic_cast<EScpFileSkipped *>(&E) != NULL)
{
Action.Rollback(&E);
}
else
{
FTerminal->RollbackAction(Action, OperationProgress, &E);
}
// Every exception during file transfer is fatal
if (OperationProgress->TransferringFile)
{
FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
}
else
{
throw;
}
}
// With SCP we are not able to distinguish reason for failure
// (upload itself, touch or chmod).
// So we always report error with upload action and
// log touch and chmod actions only if upload succeeds.
if (CopyParam->PreserveTime)
{
TTouchSessionAction(FTerminal->ActionLog, AbsoluteFileName, Handle.Modification);
}
if (CopyParam->PreserveRights)
{
TChmodSessionAction(FTerminal->ActionLog, AbsoluteFileName,
Rights);
}
FTerminal->LogFileDone(OperationProgress, AbsoluteFileName);
// Stream is disposed here
}
Handle.Release();
FTerminal->UpdateSource(Handle, CopyParam, Params);
FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory finished.", (FileName)));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPDirectorySource(const UnicodeString DirectoryName,
const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
TFileOperationProgressType * OperationProgress, int Level)
{
int Attrs;
FTerminal->LogEvent(FORMAT(L"Entering directory \"%s\".", (DirectoryName)));
OperationProgress->SetFile(DirectoryName);
UnicodeString DestFileName =
FTerminal->ChangeFileName(
CopyParam, ExtractFileName(DirectoryName), osLocal, Level == 0);
// Get directory attributes
FILE_OPERATION_LOOP_BEGIN
{
Attrs = FileGetAttrFix(ApiPath(DirectoryName));
if (Attrs < 0) RaiseLastOSError();
}
FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (DirectoryName)));
UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir + DestFileName);
UnicodeString Buf;
/* TODO 1: maybe send filetime */
// Send directory modes (rights), filesize and file name
Buf = FORMAT(L"D%s 0 %s",
(CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
FSecureShell->SendLine(Buf);
SCPResponse();
try
{
TSearchRecOwned SearchRec;
bool FindOK = FTerminal->LocalFindFirstLoop(IncludeTrailingBackslash(DirectoryName) + L"*.*", SearchRec);
while (FindOK && !OperationProgress->Cancel)
{
UnicodeString FileName = IncludeTrailingBackslash(DirectoryName) + SearchRec.Name;
try
{
if (SearchRec.IsRealFile())
{
SCPSource(FileName, TargetDirFull, CopyParam, Params, OperationProgress, Level + 1);
}
}
// Previously we caught ESkipFile, making error being displayed
// even when file was excluded by mask. Now the ESkipFile is special
// case without error message.
catch (EScpFileSkipped &E)
{
TQueryParams Params(qpAllowContinueOnError);
TSuspendFileOperationProgress Suspend(OperationProgress);
if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
qaOK | qaAbort, &Params, qtError) == qaAbort)
{
OperationProgress->SetCancel(csCancel);
}
if (!FTerminal->HandleException(&E))
{
throw;
}
}
catch (ESkipFile &E)
{
// If ESkipFile occurs, just log it and continue with next file
TSuspendFileOperationProgress Suspend(OperationProgress);
if (!FTerminal->HandleException(&E))
{
throw;
}
}
FindOK = FTerminal->LocalFindNextLoop(SearchRec);
}
SearchRec.Close();
/* TODO : Delete also read-only directories. */
/* TODO : Show error message on failure. */
if (!OperationProgress->Cancel)
{
if (FLAGSET(Params, cpDelete))
{
RemoveDir(ApiPath(DirectoryName));
}
else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
{
FILE_OPERATION_LOOP_BEGIN
{
THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
}
FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
}
}
}
__finally
{
if (FTerminal->Active)
{
// Tell remote side, that we're done.
FTerminal->LogEvent(FORMAT(L"Leaving directory \"%s\".", (DirectoryName)));
FSecureShell->SendLine(L"E");
SCPResponse();
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
const UnicodeString TargetDir, const TCopyParamType * CopyParam,
int Params, TFileOperationProgressType * OperationProgress,
TOnceDoneOperation & OnceDoneOperation)
{
bool CloseSCP = False;
Params &= ~(cpAppend | cpResume);
UnicodeString Options = L"";
if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = L"-p";
if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
FTerminal->LogEvent(FORMAT(L"Copying %d files/directories to local directory "
"\"%s\"", (FilesToCopy->Count, TargetDir)));
if (FTerminal->Configuration->ActualLogProtocol >= 0)
{
FTerminal->LogEvent(CopyParam->LogStr);
}
try
{
for (int IFile = 0; (IFile < FilesToCopy->Count) &&
!OperationProgress->Cancel; IFile++)
{
UnicodeString FileName = FilesToCopy->Strings[IFile];
TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
DebugAssert(File);
try
{
bool Success = true; // Have to be set to True (see ::SCPSink)
SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
ARRAYOFCONST((Options, DelimitStr(FileName)))));
SkipFirstLine();
// Filename is used for error messaging and excluding files only
// Send in full path to allow path-based excluding
UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
SCPSink(TargetDir, FullFileName, UnixExtractFilePath(FullFileName),
CopyParam, Success, OperationProgress, Params, 0);
// operation succeeded (no exception), so it's ok that
// remote side closed SCP, but we continue with next file
if (OperationProgress->Cancel == csRemoteAbort)
{
OperationProgress->SetCancel(csContinue);
}
// Move operation -> delete file/directory afterwards
// but only if copying succeeded
if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
{
try
{
FTerminal->ExceptionOnFail = true;
try
{
FILE_OPERATION_LOOP_BEGIN
{
// pass full file name in FileName, in case we are not moving
// from current directory
FTerminal->DeleteFile(FileName, File);
}
FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
}
__finally
{
FTerminal->ExceptionOnFail = false;
}
}
catch (EFatal &E)
{
throw;
}
catch (...)
{
// If user selects skip (or abort), nothing special actually occurs
// we just run DoFinished with Success = False, so file won't
// be deselected in panel (depends on assigned event handler)
// On csCancel we would later try to close remote SCP, but it
// is closed already
if (OperationProgress->Cancel == csCancel)
{
OperationProgress->SetCancel(csRemoteAbort);
}
Success = false;
}
}
FTerminal->OperationFinish(
OperationProgress, File, FileName, (!OperationProgress->Cancel && Success), OnceDoneOperation);
}
catch (...)
{
FTerminal->OperationFinish(OperationProgress, File, FileName, false, OnceDoneOperation);
CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
throw;
}
}
}
__finally
{
// In case that copying doesn't cause fatal error (ie. connection is
// still active) but wasn't successful (exception or user termination)
// we need to ensure, that SCP on remote side is closed
if (FTerminal->Active && (CloseSCP ||
(OperationProgress->Cancel == csCancel) ||
(OperationProgress->Cancel == csCancelTransfer)))
{
bool LastLineRead;
// If we get LastLine, it means that remote side 'scp' is already
// terminated, so we need not to terminate it. There is also
// possibility that remote side waits for confirmation, so it will hang.
// This should not happen (hope)
UnicodeString Line = FSecureShell->ReceiveLine();
LastLineRead = IsLastLine(Line);
if (!LastLineRead)
{
SCPSendError((OperationProgress->Cancel ? L"Terminated by user." : L"Exception"), true);
}
// Just in case, remote side already sent some more data (it's probable)
// but we don't want to raise exception (user asked to terminate, it's not error)
int ECParams = coOnlyReturnCode;
if (!LastLineRead) ECParams |= coWaitForLastLine;
ReadCommandOutput(ECParams);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Sink(
const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/,
const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/, int /*Attrs*/,
const TCopyParamType * /*CopyParam*/, int /*Params*/, TFileOperationProgressType * /*OperationProgress*/,
unsigned int /*Flags*/, TDownloadSessionAction & /*Action*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPError(const UnicodeString Message, bool Fatal)
{
SCPSendError(Message, Fatal);
throw EScpFileSkipped(NULL, Message);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPSendError(const UnicodeString Message, bool Fatal)
{
unsigned char ErrorLevel = (char)(Fatal ? 2 : 1);
FTerminal->LogEvent(FORMAT(L"Sending SCP error (%d) to remote side:",
((int)ErrorLevel)));
FSecureShell->Send(&ErrorLevel, 1);
// We don't send exact error message, because some unspecified
// characters can terminate remote scp
FSecureShell->SendLine(L"scp: error");
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir,
const UnicodeString FileName, const UnicodeString SourceDir,
const TCopyParamType * CopyParam, bool & Success,
TFileOperationProgressType * OperationProgress, int Params,
int Level)
{
struct
{
int SetTime;
TDateTime Modification;
TRights RemoteRights;
int Attrs;
bool Exists;
} FileData;
bool SkipConfirmed = false;
bool Initialized = (Level > 0);
FileData.SetTime = 0;
FSecureShell->SendNull();
while (!OperationProgress->Cancel)
{
// See (switch ... case 'T':)
if (FileData.SetTime) FileData.SetTime--;
// In case of error occurred before control record arrived.
// We can finally use full path here, as we get current path in FileName param
// (we used to set the file into OperationProgress->FileName, but it collided
// with progress outputting, particularly for scripting)
UnicodeString FullFileName = FileName;
try
{
// Receive control record
UnicodeString Line = FSecureShell->ReceiveLine();
if (Line.Length() == 0) FTerminal->FatalError(NULL, LoadStr(SCP_EMPTY_LINE));
if (IsLastLine(Line))
{
// Remote side finished copying, so remote SCP was closed
// and we don't need to terminate it manually, see CopyToLocal()
OperationProgress->SetCancel(csRemoteAbort);
/* TODO 1 : Show stderror to user? */
FSecureShell->ClearStdError();
try
{
// coIgnoreWarnings should allow batch transfer to continue when
// download of one the files fails (user denies overwriting
// of target local file, no read permissions...)
ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
coOnlyReturnCode | coIgnoreWarnings);
if (!Initialized)
{
throw Exception(L"");
}
}
catch(Exception & E)
{
if (!Initialized && FTerminal->Active)
{
FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
}
else
{
throw;
}
}
return;
}
else
{
Initialized = true;
// First character distinguish type of control record
wchar_t Ctrl = Line[1];
Line.Delete(1, 1);
switch (Ctrl) {
case 1:
// Error (already logged by ReceiveLine())
throw EScpFileSkipped(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
case 2:
// Fatal error, terminate copying
FTerminal->TerminalError(Line);
return; // Unreachable
case L'E': // Exit
FSecureShell->SendNull();
return;
case L'T':
unsigned long MTime, ATime;
if (swscanf(Line.c_str(), L"%ld %*d %ld %*d", &MTime, &ATime) == 2)
{
FileData.Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
FSecureShell->SendNull();
// File time is only valid until next pass
FileData.SetTime = 2;
continue;
}
else
{
SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
}
case L'C':
case L'D':
break; // continue pass switch{}
default:
FTerminal->FatalError(NULL, FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
}
TFileMasks::TParams MaskParams;
MaskParams.Modification = FileData.Modification;
// We reach this point only if control record was 'C' or 'D'
try
{
FileData.RemoteRights.Octal = CutToChar(Line, L' ', True);
// do not trim leading spaces of the filename
__int64 TSize = StrToInt64(CutToChar(Line, L' ', False).TrimRight());
MaskParams.Size = TSize;
// Security fix: ensure the file ends up where we asked for it.
// (accept only filename, not path)
UnicodeString OnlyFileName = UnixExtractFileName(Line);
if (Line != OnlyFileName)
{
FTerminal->LogEvent(FORMAT(L"Warning: Remote host set a compound pathname '%s'", (Line)));
}
FullFileName = SourceDir + OnlyFileName;
OperationProgress->SetFile(FullFileName);
OperationProgress->SetTransferSize(TSize);
}
catch (Exception &E)
{
{
TSuspendFileOperationProgress Suspend(OperationProgress);
FTerminal->Log->AddException(&E);
}
SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
}
// last possibility to cancel transfer before it starts
if (OperationProgress->Cancel)
{
throw ESkipFile(NULL, MainInstructions(LoadStr(USER_TERMINATED)));
}
bool Dir = (Ctrl == L'D');
UnicodeString BaseFileName = FTerminal->GetBaseFileName(FullFileName);
if (!CopyParam->AllowTransfer(BaseFileName, osRemote, Dir, MaskParams, IsUnixHiddenFile(BaseFileName)))
{
FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer",
(FullFileName)));
SkipConfirmed = true;
SCPError(L"", false);
}
if (CopyParam->SkipTransfer(FullFileName, Dir))
{
SkipConfirmed = true;
SCPError(L"", false);
OperationProgress->AddSkippedFileSize(MaskParams.Size);
}
FTerminal->LogFileDetails(FileName, FileData.Modification, MaskParams.Size);
UnicodeString DestFileNameOnly =
FTerminal->ChangeFileName(
CopyParam, OperationProgress->FileName, osRemote,
Level == 0);
UnicodeString DestFileName =
IncludeTrailingBackslash(TargetDir) + DestFileNameOnly;
FileData.Attrs = FileGetAttrFix(ApiPath(DestFileName));
// If getting attrs fails, we suppose, that file/folder doesn't exists
FileData.Exists = (FileData.Attrs != -1);
if (Dir)
{
if (FileData.Exists && !(FileData.Attrs & faDirectory))
{
SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
}
if (!FileData.Exists)
{
FILE_OPERATION_LOOP_BEGIN
{
THROWOSIFFALSE(ForceDirectories(ApiPath(DestFileName)));
}
FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFileName)));
/* SCP: can we set the timestamp for directories ? */
}
UnicodeString FullFileName = SourceDir + OperationProgress->FileName;
SCPSink(DestFileName, FullFileName, UnixIncludeTrailingBackslash(FullFileName),
CopyParam, Success, OperationProgress, Params, Level + 1);
continue;
}
else if (Ctrl == L'C')
{
TDownloadSessionAction Action(FTerminal->ActionLog);
Action.FileName(FTerminal->AbsolutePath(FullFileName, true));
try
{
HANDLE File = NULL;
TStream * FileStream = NULL;
/* TODO 1 : Turn off read-only attr */
try
{
try
{
if (FileExists(ApiPath(DestFileName)))
{
__int64 MTime;
TOverwriteFileParams FileParams;
FileParams.SourceSize = OperationProgress->TransferSize;
FileParams.SourceTimestamp = FileData.Modification;
FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
NULL, NULL, NULL, &MTime, NULL,
&FileParams.DestSize);
FileParams.DestTimestamp = UnixToDateTime(MTime,
FTerminal->SessionData->DSTMode);
unsigned int Answer =
ConfirmOverwrite(OperationProgress->FileName, DestFileNameOnly, osLocal,
&FileParams, CopyParam, Params, OperationProgress);
switch (Answer)
{
case qaCancel:
OperationProgress->SetCancel(csCancel); // continue on next case
case qaNo:
SkipConfirmed = true;
EXCEPTION;
}
}
Action.Destination(DestFileName);
if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress,
&File, FLAGSET(Params, cpNoConfirmation)))
{
SkipConfirmed = true;
EXCEPTION;
}
FileStream = new TSafeHandleStream((THandle)File);
}
catch (Exception &E)
{
// In this step we can still cancel transfer, so we do it
SCPError(E.Message, false);
throw;
}
// We succeeded, so we confirm transfer to remote side
FSecureShell->SendNull();
// From now we need to finish file transfer, if not it's fatal error
OperationProgress->SetTransferringFile(true);
// Suppose same data size to transfer as to write
// (not true with ASCII transfer)
OperationProgress->SetLocalSize(OperationProgress->TransferSize);
// Will we use ASCII of BINARY file transfer?
OperationProgress->SetAsciiTransfer(
CopyParam->UseAsciiTransfer(BaseFileName, osRemote, MaskParams));
if (FTerminal->Configuration->ActualLogProtocol >= 0)
{
FTerminal->LogEvent(UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
L" transfer mode selected.");
}
try
{
// Buffer for one block of data
TFileBuffer BlockBuf;
bool ConvertToken = false;
do
{
BlockBuf.Size = OperationProgress->TransferBlockSize();
BlockBuf.Position = 0;
FSecureShell->Receive(reinterpret_cast<unsigned char *>(BlockBuf.Data), BlockBuf.Size);
OperationProgress->AddTransferred(BlockBuf.Size);
if (OperationProgress->AsciiTransfer)
{
unsigned int PrevBlockSize = BlockBuf.Size;
BlockBuf.Convert(FTerminal->SessionData->EOLType,
FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
OperationProgress->SetLocalSize(
OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
}
// This is crucial, if it fails during file transfer, it's fatal error
FILE_OPERATION_LOOP_BEGIN
{
BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
}
FILE_OPERATION_LOOP_END_EX(FMTLOAD(WRITE_ERROR, (DestFileName)), folNone);
OperationProgress->AddLocallyUsed(BlockBuf.Size);
if (OperationProgress->Cancel == csCancelTransfer)
{
throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
}
}
while (!OperationProgress->IsLocallyDone() || !
OperationProgress->IsTransferDone());
}
catch (Exception &E)
{
// Every exception during file transfer is fatal
FTerminal->FatalError(&E,
FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
}
OperationProgress->SetTransferringFile(false);
try
{
SCPResponse();
// If one of following exception occurs, we still need
// to send confirmation to other side
}
catch (EScp &E)
{
FSecureShell->SendNull();
throw;
}
catch (EScpFileSkipped &E)
{
FSecureShell->SendNull();
throw;
}
FSecureShell->SendNull();
if (FileData.SetTime && CopyParam->PreserveTime)
{
FTerminal->UpdateTargetTime(File, FileData.Modification, FTerminal->SessionData->DSTMode);
}
}
__finally
{
if (File) CloseHandle(File);
if (FileStream) delete FileStream;
}
}
catch(Exception & E)
{
if (SkipConfirmed)
{
Action.Cancel();
}
else
{
FTerminal->RollbackAction(Action, OperationProgress, &E);
}
throw;
}
if (FileData.Attrs == -1) FileData.Attrs = faArchive;
int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
if ((NewAttrs & FileData.Attrs) != NewAttrs)
{
FILE_OPERATION_LOOP_BEGIN
{
THROWOSIFFALSE(FileSetAttr(ApiPath(DestFileName), FileData.Attrs | NewAttrs) == 0);
}
FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFileName)));
}
FTerminal->LogFileDone(OperationProgress, DestFileName);
}
}
}
catch (EScpFileSkipped &E)
{
if (!SkipConfirmed)
{
TSuspendFileOperationProgress Suspend(OperationProgress);
TQueryParams Params(qpAllowContinueOnError);
if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FullFileName)),
&E, qaOK | qaAbort, &Params, qtError) == qaAbort)
{
OperationProgress->SetCancel(csCancel);
}
FTerminal->Log->AddException(&E);
}
// this was inside above condition, but then transfer was considered
// successful, even when for example user refused to overwrite file
Success = false;
}
catch (ESkipFile &E)
{
SCPSendError(E.Message, false);
Success = false;
if (!FTerminal->HandleException(&E)) throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
{
// NOOP
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
{
// noop
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ClearCaches()
{
// noop
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_512_0 |
crossvul-cpp_data_bad_1442_1 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <znc/FileUtils.h>
#include <znc/Config.h>
#include <znc/IRCSock.h>
#include <znc/Server.h>
#include <znc/Chan.h>
#include <znc/Query.h>
#include <znc/Message.h>
#include <algorithm>
#include <memory>
using std::vector;
using std::set;
class CIRCNetworkPingTimer : public CCron {
public:
CIRCNetworkPingTimer(CIRCNetwork* pNetwork)
: CCron(), m_pNetwork(pNetwork) {
SetName("CIRCNetworkPingTimer::" +
m_pNetwork->GetUser()->GetUserName() + "::" +
m_pNetwork->GetName());
Start(m_pNetwork->GetUser()->GetPingSlack());
}
~CIRCNetworkPingTimer() override {}
CIRCNetworkPingTimer(const CIRCNetworkPingTimer&) = delete;
CIRCNetworkPingTimer& operator=(const CIRCNetworkPingTimer&) = delete;
protected:
void RunJob() override {
CIRCSock* pIRCSock = m_pNetwork->GetIRCSock();
auto uFrequency = m_pNetwork->GetUser()->GetPingFrequency();
if (pIRCSock &&
pIRCSock->GetTimeSinceLastDataTransaction() >= uFrequency) {
pIRCSock->PutIRC("PING :ZNC");
}
const vector<CClient*>& vClients = m_pNetwork->GetClients();
for (CClient* pClient : vClients) {
if (pClient->GetTimeSinceLastDataTransaction() >= uFrequency) {
pClient->PutClient("PING :ZNC");
}
}
// Restart timer for the case if the period had changed. Usually this is
// noop
Start(m_pNetwork->GetUser()->GetPingSlack());
}
private:
CIRCNetwork* m_pNetwork;
};
class CIRCNetworkJoinTimer : public CCron {
constexpr static int JOIN_FREQUENCY = 30 /* seconds */;
public:
CIRCNetworkJoinTimer(CIRCNetwork* pNetwork)
: CCron(), m_bDelayed(false), m_pNetwork(pNetwork) {
SetName("CIRCNetworkJoinTimer::" +
m_pNetwork->GetUser()->GetUserName() + "::" +
m_pNetwork->GetName());
Start(JOIN_FREQUENCY);
}
~CIRCNetworkJoinTimer() override {}
CIRCNetworkJoinTimer(const CIRCNetworkJoinTimer&) = delete;
CIRCNetworkJoinTimer& operator=(const CIRCNetworkJoinTimer&) = delete;
void Delay(unsigned short int uDelay) {
m_bDelayed = true;
Start(uDelay);
}
protected:
void RunJob() override {
if (m_bDelayed) {
m_bDelayed = false;
Start(JOIN_FREQUENCY);
}
if (m_pNetwork->IsIRCConnected()) {
m_pNetwork->JoinChans();
}
}
private:
bool m_bDelayed;
CIRCNetwork* m_pNetwork;
};
bool CIRCNetwork::IsValidNetwork(const CString& sNetwork) {
// ^[-\w]+$
if (sNetwork.empty()) {
return false;
}
const char* p = sNetwork.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
CIRCNetwork::CIRCNetwork(CUser* pUser, const CString& sName)
: m_sName(sName),
m_pUser(nullptr),
m_sNick(""),
m_sAltNick(""),
m_sIdent(""),
m_sRealName(""),
m_sBindHost(""),
m_sEncoding(""),
m_sQuitMsg(""),
m_ssTrustedFingerprints(),
m_pModules(new CModules),
m_vClients(),
m_pIRCSock(nullptr),
m_vChans(),
m_vQueries(),
m_sChanPrefixes(""),
m_bIRCConnectEnabled(true),
m_bTrustAllCerts(false),
m_bTrustPKI(true),
m_sIRCServer(""),
m_vServers(),
m_uServerIdx(0),
m_IRCNick(),
m_bIRCAway(false),
m_fFloodRate(2),
m_uFloodBurst(9),
m_RawBuffer(),
m_MotdBuffer(),
m_NoticeBuffer(),
m_pPingTimer(nullptr),
m_pJoinTimer(nullptr),
m_uJoinDelay(0),
m_uBytesRead(0),
m_uBytesWritten(0) {
SetUser(pUser);
// This should be more than enough raws, especially since we are buffering
// the MOTD separately
m_RawBuffer.SetLineCount(100, true);
// This should be more than enough motd lines
m_MotdBuffer.SetLineCount(200, true);
m_NoticeBuffer.SetLineCount(250, true);
m_pPingTimer = new CIRCNetworkPingTimer(this);
CZNC::Get().GetManager().AddCron(m_pPingTimer);
m_pJoinTimer = new CIRCNetworkJoinTimer(this);
CZNC::Get().GetManager().AddCron(m_pJoinTimer);
SetIRCConnectEnabled(true);
}
CIRCNetwork::CIRCNetwork(CUser* pUser, const CIRCNetwork& Network)
: CIRCNetwork(pUser, "") {
Clone(Network);
}
void CIRCNetwork::Clone(const CIRCNetwork& Network, bool bCloneName) {
if (bCloneName) {
m_sName = Network.GetName();
}
m_fFloodRate = Network.GetFloodRate();
m_uFloodBurst = Network.GetFloodBurst();
m_uJoinDelay = Network.GetJoinDelay();
SetNick(Network.GetNick());
SetAltNick(Network.GetAltNick());
SetIdent(Network.GetIdent());
SetRealName(Network.GetRealName());
SetBindHost(Network.GetBindHost());
SetEncoding(Network.GetEncoding());
SetQuitMsg(Network.GetQuitMsg());
m_ssTrustedFingerprints = Network.m_ssTrustedFingerprints;
// Servers
const vector<CServer*>& vServers = Network.GetServers();
CString sServer;
CServer* pCurServ = GetCurrentServer();
if (pCurServ) {
sServer = pCurServ->GetName();
}
DelServers();
for (CServer* pServer : vServers) {
AddServer(pServer->GetName(), pServer->GetPort(), pServer->GetPass(),
pServer->IsSSL());
}
m_uServerIdx = 0;
for (size_t a = 0; a < m_vServers.size(); a++) {
if (sServer.Equals(m_vServers[a]->GetName())) {
m_uServerIdx = a + 1;
break;
}
}
if (m_uServerIdx == 0) {
m_uServerIdx = m_vServers.size();
CIRCSock* pSock = GetIRCSock();
if (pSock) {
PutStatus(
t_s("Jumping servers because this server is no longer in the "
"list"));
pSock->Quit();
}
}
// !Servers
// Chans
const vector<CChan*>& vChans = Network.GetChans();
for (CChan* pNewChan : vChans) {
CChan* pChan = FindChan(pNewChan->GetName());
if (pChan) {
pChan->SetInConfig(pNewChan->InConfig());
} else {
AddChan(pNewChan->GetName(), pNewChan->InConfig());
}
}
for (CChan* pChan : m_vChans) {
CChan* pNewChan = Network.FindChan(pChan->GetName());
if (!pNewChan) {
pChan->SetInConfig(false);
} else {
pChan->Clone(*pNewChan);
}
}
// !Chans
// Modules
set<CString> ssUnloadMods;
CModules& vCurMods = GetModules();
const CModules& vNewMods = Network.GetModules();
for (CModule* pNewMod : vNewMods) {
CString sModRet;
CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName());
if (!pCurMod) {
vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
CModInfo::NetworkModule, m_pUser, this,
sModRet);
} else if (pNewMod->GetArgs() != pCurMod->GetArgs()) {
vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
m_pUser, this, sModRet);
}
}
for (CModule* pCurMod : vCurMods) {
CModule* pNewMod = vNewMods.FindModule(pCurMod->GetModName());
if (!pNewMod) {
ssUnloadMods.insert(pCurMod->GetModName());
}
}
for (const CString& sMod : ssUnloadMods) {
vCurMods.UnloadModule(sMod);
}
// !Modules
SetIRCConnectEnabled(Network.GetIRCConnectEnabled());
}
CIRCNetwork::~CIRCNetwork() {
if (m_pIRCSock) {
CZNC::Get().GetManager().DelSockByAddr(m_pIRCSock);
m_pIRCSock = nullptr;
}
// Delete clients
while (!m_vClients.empty()) {
CZNC::Get().GetManager().DelSockByAddr(m_vClients[0]);
}
m_vClients.clear();
// Delete servers
DelServers();
// Delete modules (this unloads all modules)
delete m_pModules;
m_pModules = nullptr;
// Delete Channels
for (CChan* pChan : m_vChans) {
delete pChan;
}
m_vChans.clear();
// Delete Queries
for (CQuery* pQuery : m_vQueries) {
delete pQuery;
}
m_vQueries.clear();
CUser* pUser = GetUser();
SetUser(nullptr);
// Make sure we are not in the connection queue
CZNC::Get().GetConnectionQueue().remove(this);
CZNC::Get().GetManager().DelCronByAddr(m_pPingTimer);
CZNC::Get().GetManager().DelCronByAddr(m_pJoinTimer);
if (pUser) {
pUser->AddBytesRead(m_uBytesRead);
pUser->AddBytesWritten(m_uBytesWritten);
} else {
CZNC::Get().AddBytesRead(m_uBytesRead);
CZNC::Get().AddBytesWritten(m_uBytesWritten);
}
}
void CIRCNetwork::DelServers() {
for (CServer* pServer : m_vServers) {
delete pServer;
}
m_vServers.clear();
}
CString CIRCNetwork::GetNetworkPath() const {
CString sNetworkPath = m_pUser->GetUserPath() + "/networks/" + m_sName;
if (!CFile::Exists(sNetworkPath)) {
CDir::MakeDir(sNetworkPath);
}
return sNetworkPath;
}
template <class T>
struct TOption {
const char* name;
void (CIRCNetwork::*pSetter)(T);
};
bool CIRCNetwork::ParseConfig(CConfig* pConfig, CString& sError,
bool bUpgrade) {
VCString vsList;
if (!bUpgrade) {
TOption<const CString&> StringOptions[] = {
{"nick", &CIRCNetwork::SetNick},
{"altnick", &CIRCNetwork::SetAltNick},
{"ident", &CIRCNetwork::SetIdent},
{"realname", &CIRCNetwork::SetRealName},
{"bindhost", &CIRCNetwork::SetBindHost},
{"encoding", &CIRCNetwork::SetEncoding},
{"quitmsg", &CIRCNetwork::SetQuitMsg},
};
TOption<bool> BoolOptions[] = {
{"ircconnectenabled", &CIRCNetwork::SetIRCConnectEnabled},
{"trustallcerts", &CIRCNetwork::SetTrustAllCerts},
{"trustpki", &CIRCNetwork::SetTrustPKI},
};
TOption<double> DoubleOptions[] = {
{"floodrate", &CIRCNetwork::SetFloodRate},
};
TOption<short unsigned int> SUIntOptions[] = {
{"floodburst", &CIRCNetwork::SetFloodBurst},
{"joindelay", &CIRCNetwork::SetJoinDelay},
};
for (const auto& Option : StringOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue);
}
for (const auto& Option : BoolOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue.ToBool());
}
for (const auto& Option : DoubleOptions) {
double fValue;
if (pConfig->FindDoubleEntry(Option.name, fValue))
(this->*Option.pSetter)(fValue);
}
for (const auto& Option : SUIntOptions) {
unsigned short value;
if (pConfig->FindUShortEntry(Option.name, value))
(this->*Option.pSetter)(value);
}
pConfig->FindStringVector("loadmodule", vsList);
for (const CString& sValue : vsList) {
CString sModName = sValue.Token(0);
CString sNotice = "Loading network module [" + sModName + "]";
// XXX Legacy crap, added in ZNC 0.203, modified in 0.207
// Note that 0.203 == 0.207
if (sModName == "away") {
sNotice =
"NOTICE: [away] was renamed, loading [awaystore] instead";
sModName = "awaystore";
}
// XXX Legacy crap, added in ZNC 0.207
if (sModName == "autoaway") {
sNotice =
"NOTICE: [autoaway] was renamed, loading [awaystore] "
"instead";
sModName = "awaystore";
}
// XXX Legacy crap, added in 1.1; fakeonline module was dropped in
// 1.0 and returned in 1.1
if (sModName == "fakeonline") {
sNotice =
"NOTICE: [fakeonline] was renamed, loading "
"[modules_online] instead";
sModName = "modules_online";
}
CString sModRet;
CString sArgs = sValue.Token(1, true);
bool bModRet = LoadModule(sModName, sArgs, sNotice, sModRet);
if (!bModRet) {
// XXX The awaynick module was retired in 1.6 (still available
// as external module)
if (sModName == "awaynick") {
// load simple_away instead, unless it's already on the list
bool bFound = false;
for (const CString& sLoadMod : vsList) {
if (sLoadMod.Token(0).Equals("simple_away")) {
bFound = true;
}
}
if (!bFound) {
sNotice =
"NOTICE: awaynick was retired, loading network "
"module [simple_away] instead; if you still need "
"awaynick, install it as an external module";
sModName = "simple_away";
// not a fatal error if simple_away is not available
LoadModule(sModName, sArgs, sNotice, sModRet);
}
} else {
sError = sModRet;
return false;
}
}
}
}
pConfig->FindStringVector("server", vsList);
for (const CString& sServer : vsList) {
CUtils::PrintAction("Adding server [" + sServer + "]");
CUtils::PrintStatus(AddServer(sServer));
}
pConfig->FindStringVector("trustedserverfingerprint", vsList);
for (const CString& sFP : vsList) {
AddTrustedFingerprint(sFP);
}
pConfig->FindStringVector("chan", vsList);
for (const CString& sChan : vsList) {
AddChan(sChan, true);
}
CConfig::SubConfig subConf;
CConfig::SubConfig::const_iterator subIt;
pConfig->FindSubConfig("chan", subConf);
for (subIt = subConf.begin(); subIt != subConf.end(); ++subIt) {
const CString& sChanName = subIt->first;
CConfig* pSubConf = subIt->second.m_pSubConfig;
CChan* pChan = new CChan(sChanName, this, true, pSubConf);
if (!pSubConf->empty()) {
sError = "Unhandled lines in config for User [" +
m_pUser->GetUserName() + "], Network [" + GetName() +
"], Channel [" + sChanName + "]!";
CUtils::PrintError(sError);
CZNC::DumpConfig(pSubConf);
delete pChan;
return false;
}
// Save the channel name, because AddChan
// deletes the CChannel*, if adding fails
sError = pChan->GetName();
if (!AddChan(pChan)) {
sError = "Channel [" + sError + "] defined more than once";
CUtils::PrintError(sError);
return false;
}
sError.clear();
}
return true;
}
CConfig CIRCNetwork::ToConfig() const {
CConfig config;
if (!m_sNick.empty()) {
config.AddKeyValuePair("Nick", m_sNick);
}
if (!m_sAltNick.empty()) {
config.AddKeyValuePair("AltNick", m_sAltNick);
}
if (!m_sIdent.empty()) {
config.AddKeyValuePair("Ident", m_sIdent);
}
if (!m_sRealName.empty()) {
config.AddKeyValuePair("RealName", m_sRealName);
}
if (!m_sBindHost.empty()) {
config.AddKeyValuePair("BindHost", m_sBindHost);
}
config.AddKeyValuePair("IRCConnectEnabled",
CString(GetIRCConnectEnabled()));
config.AddKeyValuePair("TrustAllCerts", CString(GetTrustAllCerts()));
config.AddKeyValuePair("TrustPKI", CString(GetTrustPKI()));
config.AddKeyValuePair("FloodRate", CString(GetFloodRate()));
config.AddKeyValuePair("FloodBurst", CString(GetFloodBurst()));
config.AddKeyValuePair("JoinDelay", CString(GetJoinDelay()));
config.AddKeyValuePair("Encoding", m_sEncoding);
if (!m_sQuitMsg.empty()) {
config.AddKeyValuePair("QuitMsg", m_sQuitMsg);
}
// Modules
const CModules& Mods = GetModules();
if (!Mods.empty()) {
for (CModule* pMod : Mods) {
CString sArgs = pMod->GetArgs();
if (!sArgs.empty()) {
sArgs = " " + sArgs;
}
config.AddKeyValuePair("LoadModule", pMod->GetModName() + sArgs);
}
}
// Servers
for (CServer* pServer : m_vServers) {
config.AddKeyValuePair("Server", pServer->GetString());
}
for (const CString& sFP : m_ssTrustedFingerprints) {
config.AddKeyValuePair("TrustedServerFingerprint", sFP);
}
// Chans
for (CChan* pChan : m_vChans) {
if (pChan->InConfig()) {
config.AddSubConfig("Chan", pChan->GetName(), pChan->ToConfig());
}
}
return config;
}
void CIRCNetwork::BounceAllClients() {
for (CClient* pClient : m_vClients) {
pClient->BouncedOff();
}
m_vClients.clear();
}
bool CIRCNetwork::IsUserOnline() const {
for (CClient* pClient : m_vClients) {
if (!pClient->IsAway()) {
return true;
}
}
return false;
}
void CIRCNetwork::ClientConnected(CClient* pClient) {
if (!m_pUser->MultiClients()) {
BounceAllClients();
}
m_vClients.push_back(pClient);
size_t uIdx, uSize;
if (m_pIRCSock) {
pClient->NotifyServerDependentCaps(m_pIRCSock->GetAcceptedCaps());
}
pClient->SetPlaybackActive(true);
if (m_RawBuffer.IsEmpty()) {
pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() +
" :" + t_s("Welcome to ZNC"));
} else {
const CString& sClientNick = pClient->GetNick(false);
MCString msParams;
msParams["target"] = sClientNick;
uSize = m_RawBuffer.Size();
for (uIdx = 0; uIdx < uSize; uIdx++) {
pClient->PutClient(m_RawBuffer.GetLine(uIdx, *pClient, msParams));
}
const CNick& Nick = GetIRCNick();
if (sClientNick != Nick.GetNick()) { // case-sensitive match
pClient->PutClient(":" + sClientNick + "!" + Nick.GetIdent() + "@" +
Nick.GetHost() + " NICK :" + Nick.GetNick());
pClient->SetNick(Nick.GetNick());
}
}
MCString msParams;
msParams["target"] = GetIRCNick().GetNick();
// Send the cached MOTD
uSize = m_MotdBuffer.Size();
if (uSize > 0) {
for (uIdx = 0; uIdx < uSize; uIdx++) {
pClient->PutClient(m_MotdBuffer.GetLine(uIdx, *pClient, msParams));
}
}
if (GetIRCSock() != nullptr) {
CString sUserMode("");
const set<char>& scUserModes = GetIRCSock()->GetUserModes();
for (char cMode : scUserModes) {
sUserMode += cMode;
}
if (!sUserMode.empty()) {
pClient->PutClient(":" + GetIRCNick().GetNickMask() + " MODE " +
GetIRCNick().GetNick() + " :+" + sUserMode);
}
}
if (m_bIRCAway) {
// If they want to know their away reason they'll have to whois
// themselves. At least we can tell them their away status...
pClient->PutClient(":irc.znc.in 306 " + GetIRCNick().GetNick() +
" :You have been marked as being away");
}
const vector<CChan*>& vChans = GetChans();
for (CChan* pChan : vChans) {
if ((pChan->IsOn()) && (!pChan->IsDetached())) {
pChan->AttachUser(pClient);
}
}
bool bClearQuery = m_pUser->AutoClearQueryBuffer();
for (CQuery* pQuery : m_vQueries) {
pQuery->SendBuffer(pClient);
if (bClearQuery) {
delete pQuery;
}
}
if (bClearQuery) {
m_vQueries.clear();
}
uSize = m_NoticeBuffer.Size();
for (uIdx = 0; uIdx < uSize; uIdx++) {
const CBufLine& BufLine = m_NoticeBuffer.GetBufLine(uIdx);
CMessage Message(BufLine.GetLine(*pClient, msParams));
Message.SetNetwork(this);
Message.SetClient(pClient);
Message.SetTime(BufLine.GetTime());
Message.SetTags(BufLine.GetTags());
bool bContinue = false;
NETWORKMODULECALL(OnPrivBufferPlayMessage(Message), m_pUser, this,
nullptr, &bContinue);
if (bContinue) continue;
pClient->PutClient(Message);
}
m_NoticeBuffer.Clear();
pClient->SetPlaybackActive(false);
// Tell them why they won't connect
if (!GetIRCConnectEnabled())
pClient->PutStatus(
t_s("You are currently disconnected from IRC. Use 'connect' to "
"reconnect."));
}
void CIRCNetwork::ClientDisconnected(CClient* pClient) {
auto it = std::find(m_vClients.begin(), m_vClients.end(), pClient);
if (it != m_vClients.end()) {
m_vClients.erase(it);
}
}
CUser* CIRCNetwork::GetUser() const { return m_pUser; }
const CString& CIRCNetwork::GetName() const { return m_sName; }
std::vector<CClient*> CIRCNetwork::FindClients(
const CString& sIdentifier) const {
std::vector<CClient*> vClients;
for (CClient* pClient : m_vClients) {
if (pClient->GetIdentifier().Equals(sIdentifier)) {
vClients.push_back(pClient);
}
}
return vClients;
}
void CIRCNetwork::SetUser(CUser* pUser) {
for (CClient* pClient : m_vClients) {
pClient->PutStatus(
t_s("This network is being deleted or moved to another user."));
pClient->SetNetwork(nullptr);
}
m_vClients.clear();
if (m_pUser) {
m_pUser->RemoveNetwork(this);
}
m_pUser = pUser;
if (m_pUser) {
m_pUser->AddNetwork(this);
}
}
bool CIRCNetwork::SetName(const CString& sName) {
if (IsValidNetwork(sName)) {
m_sName = sName;
return true;
}
return false;
}
bool CIRCNetwork::PutUser(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutClient(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CIRCNetwork::PutUser(const CMessage& Message, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutClient(Message);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CIRCNetwork::PutStatus(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutStatus(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CIRCNetwork::PutModule(const CString& sModule, const CString& sLine,
CClient* pClient, CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutModule(sModule, sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
// Channels
const vector<CChan*>& CIRCNetwork::GetChans() const { return m_vChans; }
CChan* CIRCNetwork::FindChan(CString sName) const {
if (GetIRCSock()) {
// See
// https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.16
sName.TrimLeft(GetIRCSock()->GetISupport("STATUSMSG", ""));
}
for (CChan* pChan : m_vChans) {
if (sName.Equals(pChan->GetName())) {
return pChan;
}
}
return nullptr;
}
std::vector<CChan*> CIRCNetwork::FindChans(const CString& sWild) const {
std::vector<CChan*> vChans;
vChans.reserve(m_vChans.size());
const CString sLower = sWild.AsLower();
for (CChan* pChan : m_vChans) {
if (pChan->GetName().AsLower().WildCmp(sLower)) vChans.push_back(pChan);
}
return vChans;
}
bool CIRCNetwork::AddChan(CChan* pChan) {
if (!pChan) {
return false;
}
for (CChan* pEachChan : m_vChans) {
if (pEachChan->GetName().Equals(pChan->GetName())) {
delete pChan;
return false;
}
}
m_vChans.push_back(pChan);
return true;
}
bool CIRCNetwork::AddChan(const CString& sName, bool bInConfig) {
if (sName.empty() || FindChan(sName)) {
return false;
}
CChan* pChan = new CChan(sName, this, bInConfig);
m_vChans.push_back(pChan);
return true;
}
bool CIRCNetwork::DelChan(const CString& sName) {
for (vector<CChan*>::iterator a = m_vChans.begin(); a != m_vChans.end();
++a) {
if (sName.Equals((*a)->GetName())) {
delete *a;
m_vChans.erase(a);
return true;
}
}
return false;
}
void CIRCNetwork::JoinChans() {
// Avoid divsion by zero, it's bad!
if (m_vChans.empty()) return;
// We start at a random offset into the channel list so that if your
// first 3 channels are invite-only and you got MaxJoins == 3, ZNC will
// still be able to join the rest of your channels.
unsigned int start = rand() % m_vChans.size();
unsigned int uJoins = m_pUser->MaxJoins();
set<CChan*> sChans;
for (unsigned int a = 0; a < m_vChans.size(); a++) {
unsigned int idx = (start + a) % m_vChans.size();
CChan* pChan = m_vChans[idx];
if (!pChan->IsOn() && !pChan->IsDisabled()) {
if (!JoinChan(pChan)) continue;
sChans.insert(pChan);
// Limit the number of joins
if (uJoins != 0 && --uJoins == 0) {
// Reset the timer.
m_pJoinTimer->Reset();
break;
}
}
}
while (!sChans.empty()) JoinChans(sChans);
}
void CIRCNetwork::JoinChans(set<CChan*>& sChans) {
CString sKeys, sJoin;
bool bHaveKey = false;
size_t uiJoinLength = strlen("JOIN ");
while (!sChans.empty()) {
set<CChan*>::iterator it = sChans.begin();
const CString& sName = (*it)->GetName();
const CString& sKey = (*it)->GetKey();
size_t len = sName.length() + sKey.length();
len += 2; // two comma
if (!sKeys.empty() && uiJoinLength + len >= 512) break;
if (!sJoin.empty()) {
sJoin += ",";
sKeys += ",";
}
uiJoinLength += len;
sJoin += sName;
if (!sKey.empty()) {
sKeys += sKey;
bHaveKey = true;
}
sChans.erase(it);
}
if (bHaveKey)
PutIRC("JOIN " + sJoin + " " + sKeys);
else
PutIRC("JOIN " + sJoin);
}
bool CIRCNetwork::JoinChan(CChan* pChan) {
bool bReturn = false;
NETWORKMODULECALL(OnJoining(*pChan), m_pUser, this, nullptr, &bReturn);
if (bReturn) return false;
if (m_pUser->JoinTries() != 0 &&
pChan->GetJoinTries() >= m_pUser->JoinTries()) {
PutStatus(t_f("The channel {1} could not be joined, disabling it.")(
pChan->GetName()));
pChan->Disable();
} else {
pChan->IncJoinTries();
bool bFailed = false;
NETWORKMODULECALL(OnTimerAutoJoin(*pChan), m_pUser, this, nullptr,
&bFailed);
if (bFailed) return false;
return true;
}
return false;
}
bool CIRCNetwork::IsChan(const CString& sChan) const {
if (sChan.empty()) return false; // There is no way this is a chan
if (GetChanPrefixes().empty())
return true; // We can't know, so we allow everything
// Thanks to the above if (empty), we can do sChan[0]
return GetChanPrefixes().find(sChan[0]) != CString::npos;
}
// Queries
const vector<CQuery*>& CIRCNetwork::GetQueries() const { return m_vQueries; }
CQuery* CIRCNetwork::FindQuery(const CString& sName) const {
for (CQuery* pQuery : m_vQueries) {
if (sName.Equals(pQuery->GetName())) {
return pQuery;
}
}
return nullptr;
}
std::vector<CQuery*> CIRCNetwork::FindQueries(const CString& sWild) const {
std::vector<CQuery*> vQueries;
vQueries.reserve(m_vQueries.size());
const CString sLower = sWild.AsLower();
for (CQuery* pQuery : m_vQueries) {
if (pQuery->GetName().AsLower().WildCmp(sLower))
vQueries.push_back(pQuery);
}
return vQueries;
}
CQuery* CIRCNetwork::AddQuery(const CString& sName) {
if (sName.empty()) {
return nullptr;
}
CQuery* pQuery = FindQuery(sName);
if (!pQuery) {
pQuery = new CQuery(sName, this);
m_vQueries.push_back(pQuery);
if (m_pUser->MaxQueryBuffers() > 0) {
while (m_vQueries.size() > m_pUser->MaxQueryBuffers()) {
delete *m_vQueries.begin();
m_vQueries.erase(m_vQueries.begin());
}
}
}
return pQuery;
}
bool CIRCNetwork::DelQuery(const CString& sName) {
for (vector<CQuery*>::iterator a = m_vQueries.begin();
a != m_vQueries.end(); ++a) {
if (sName.Equals((*a)->GetName())) {
delete *a;
m_vQueries.erase(a);
return true;
}
}
return false;
}
// Server list
const vector<CServer*>& CIRCNetwork::GetServers() const { return m_vServers; }
CServer* CIRCNetwork::FindServer(const CString& sName) const {
for (CServer* pServer : m_vServers) {
if (sName.Equals(pServer->GetName())) {
return pServer;
}
}
return nullptr;
}
bool CIRCNetwork::DelServer(const CString& sName, unsigned short uPort,
const CString& sPass) {
if (sName.empty()) {
return false;
}
unsigned int a = 0;
bool bSawCurrentServer = false;
CServer* pCurServer = GetCurrentServer();
for (vector<CServer*>::iterator it = m_vServers.begin();
it != m_vServers.end(); ++it, a++) {
CServer* pServer = *it;
if (pServer == pCurServer) bSawCurrentServer = true;
if (!pServer->GetName().Equals(sName)) continue;
if (uPort != 0 && pServer->GetPort() != uPort) continue;
if (!sPass.empty() && pServer->GetPass() != sPass) continue;
m_vServers.erase(it);
if (pServer == pCurServer) {
CIRCSock* pIRCSock = GetIRCSock();
// Make sure we don't skip the next server in the list!
if (m_uServerIdx) {
m_uServerIdx--;
}
if (pIRCSock) {
pIRCSock->Quit();
PutStatus(t_s("Your current server was removed, jumping..."));
}
} else if (!bSawCurrentServer) {
// Our current server comes after the server which we
// are removing. This means that it now got a different
// index in m_vServers!
m_uServerIdx--;
}
delete pServer;
return true;
}
return false;
}
bool CIRCNetwork::AddServer(const CString& sName) {
if (sName.empty()) {
return false;
}
bool bSSL = false;
CString sLine = sName;
sLine.Trim();
CString sHost = sLine.Token(0);
CString sPort = sLine.Token(1);
if (sPort.TrimPrefix("+")) {
bSSL = true;
}
unsigned short uPort = sPort.ToUShort();
CString sPass = sLine.Token(2, true);
return AddServer(sHost, uPort, sPass, bSSL);
}
bool CIRCNetwork::AddServer(const CString& sName, unsigned short uPort,
const CString& sPass, bool bSSL) {
#ifndef HAVE_LIBSSL
if (bSSL) {
return false;
}
#endif
if (sName.empty()) {
return false;
}
if (!uPort) {
uPort = 6667;
}
// Check if server is already added
for (CServer* pServer : m_vServers) {
if (!sName.Equals(pServer->GetName())) continue;
if (uPort != pServer->GetPort()) continue;
if (sPass != pServer->GetPass()) continue;
if (bSSL != pServer->IsSSL()) continue;
// Server is already added
return false;
}
CServer* pServer = new CServer(sName, uPort, sPass, bSSL);
m_vServers.push_back(pServer);
CheckIRCConnect();
return true;
}
CServer* CIRCNetwork::GetNextServer(bool bAdvance) {
if (m_vServers.empty()) {
return nullptr;
}
if (m_uServerIdx >= m_vServers.size()) {
m_uServerIdx = 0;
}
if (bAdvance) {
return m_vServers[m_uServerIdx++];
} else {
return m_vServers[m_uServerIdx];
}
}
CServer* CIRCNetwork::GetCurrentServer() const {
size_t uIdx = (m_uServerIdx) ? m_uServerIdx - 1 : 0;
if (uIdx >= m_vServers.size()) {
return nullptr;
}
return m_vServers[uIdx];
}
void CIRCNetwork::SetIRCServer(const CString& s) { m_sIRCServer = s; }
bool CIRCNetwork::SetNextServer(const CServer* pServer) {
for (unsigned int a = 0; a < m_vServers.size(); a++) {
if (m_vServers[a] == pServer) {
m_uServerIdx = a;
return true;
}
}
return false;
}
bool CIRCNetwork::IsLastServer() const {
return (m_uServerIdx >= m_vServers.size());
}
const CString& CIRCNetwork::GetIRCServer() const { return m_sIRCServer; }
const CNick& CIRCNetwork::GetIRCNick() const { return m_IRCNick; }
void CIRCNetwork::SetIRCNick(const CNick& n) {
m_IRCNick = n;
for (CClient* pClient : m_vClients) {
pClient->SetNick(n.GetNick());
}
}
CString CIRCNetwork::GetCurNick() const {
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
return pIRCSock->GetNick();
}
if (!m_vClients.empty()) {
return m_vClients[0]->GetNick();
}
return "";
}
bool CIRCNetwork::Connect() {
if (!GetIRCConnectEnabled() || m_pIRCSock || !HasServers()) return false;
CServer* pServer = GetNextServer();
if (!pServer) return false;
if (CZNC::Get().GetServerThrottle(pServer->GetName())) {
// Can't connect right now, schedule retry later
CZNC::Get().AddNetworkToQueue(this);
return false;
}
CZNC::Get().AddServerThrottle(pServer->GetName());
bool bSSL = pServer->IsSSL();
#ifndef HAVE_LIBSSL
if (bSSL) {
PutStatus(
t_f("Cannot connect to {1}, because ZNC is not compiled with SSL "
"support.")(pServer->GetString(false)));
CZNC::Get().AddNetworkToQueue(this);
return false;
}
#endif
CIRCSock* pIRCSock = new CIRCSock(this);
pIRCSock->SetPass(pServer->GetPass());
pIRCSock->SetSSLTrustedPeerFingerprints(m_ssTrustedFingerprints);
pIRCSock->SetTrustAllCerts(GetTrustAllCerts());
pIRCSock->SetTrustPKI(GetTrustPKI());
DEBUG("Connecting user/network [" << m_pUser->GetUserName() << "/"
<< m_sName << "]");
bool bAbort = false;
NETWORKMODULECALL(OnIRCConnecting(pIRCSock), m_pUser, this, nullptr,
&bAbort);
if (bAbort) {
DEBUG("Some module aborted the connection attempt");
PutStatus(t_s("Some module aborted the connection attempt"));
delete pIRCSock;
CZNC::Get().AddNetworkToQueue(this);
return false;
}
CString sSockName = "IRC::" + m_pUser->GetUserName() + "::" + m_sName;
CZNC::Get().GetManager().Connect(pServer->GetName(), pServer->GetPort(),
sSockName, 120, bSSL, GetBindHost(),
pIRCSock);
return true;
}
bool CIRCNetwork::IsIRCConnected() const {
const CIRCSock* pSock = GetIRCSock();
return (pSock && pSock->IsAuthed());
}
void CIRCNetwork::SetIRCSocket(CIRCSock* pIRCSock) { m_pIRCSock = pIRCSock; }
void CIRCNetwork::IRCConnected() {
const SCString& ssCaps = m_pIRCSock->GetAcceptedCaps();
for (CClient* pClient : m_vClients) {
pClient->NotifyServerDependentCaps(ssCaps);
}
if (m_uJoinDelay > 0) {
m_pJoinTimer->Delay(m_uJoinDelay);
} else {
JoinChans();
}
}
void CIRCNetwork::IRCDisconnected() {
for (CClient* pClient : m_vClients) {
pClient->ClearServerDependentCaps();
}
m_pIRCSock = nullptr;
SetIRCServer("");
m_bIRCAway = false;
// Get the reconnect going
CheckIRCConnect();
}
void CIRCNetwork::SetIRCConnectEnabled(bool b) {
m_bIRCConnectEnabled = b;
if (m_bIRCConnectEnabled) {
CheckIRCConnect();
} else if (GetIRCSock()) {
if (GetIRCSock()->IsConnected()) {
GetIRCSock()->Quit();
} else {
GetIRCSock()->Close();
}
}
}
void CIRCNetwork::CheckIRCConnect() {
// Do we want to connect?
if (GetIRCConnectEnabled() && GetIRCSock() == nullptr)
CZNC::Get().AddNetworkToQueue(this);
}
bool CIRCNetwork::PutIRC(const CString& sLine) {
CIRCSock* pIRCSock = GetIRCSock();
if (!pIRCSock) {
return false;
}
pIRCSock->PutIRC(sLine);
return true;
}
bool CIRCNetwork::PutIRC(const CMessage& Message) {
CIRCSock* pIRCSock = GetIRCSock();
if (!pIRCSock) {
return false;
}
pIRCSock->PutIRC(Message);
return true;
}
void CIRCNetwork::ClearQueryBuffer() {
std::for_each(m_vQueries.begin(), m_vQueries.end(),
std::default_delete<CQuery>());
m_vQueries.clear();
}
const CString& CIRCNetwork::GetNick(const bool bAllowDefault) const {
if (m_sNick.empty()) {
return m_pUser->GetNick(bAllowDefault);
}
return m_sNick;
}
const CString& CIRCNetwork::GetAltNick(const bool bAllowDefault) const {
if (m_sAltNick.empty()) {
return m_pUser->GetAltNick(bAllowDefault);
}
return m_sAltNick;
}
const CString& CIRCNetwork::GetIdent(const bool bAllowDefault) const {
if (m_sIdent.empty()) {
return m_pUser->GetIdent(bAllowDefault);
}
return m_sIdent;
}
CString CIRCNetwork::GetRealName() const {
if (m_sRealName.empty()) {
return m_pUser->GetRealName();
}
return m_sRealName;
}
const CString& CIRCNetwork::GetBindHost() const {
if (m_sBindHost.empty()) {
return m_pUser->GetBindHost();
}
return m_sBindHost;
}
const CString& CIRCNetwork::GetEncoding() const { return m_sEncoding; }
CString CIRCNetwork::GetQuitMsg() const {
if (m_sQuitMsg.empty()) {
return m_pUser->GetQuitMsg();
}
return m_sQuitMsg;
}
void CIRCNetwork::SetNick(const CString& s) {
if (m_pUser->GetNick().Equals(s)) {
m_sNick = "";
} else {
m_sNick = s;
}
}
void CIRCNetwork::SetAltNick(const CString& s) {
if (m_pUser->GetAltNick().Equals(s)) {
m_sAltNick = "";
} else {
m_sAltNick = s;
}
}
void CIRCNetwork::SetIdent(const CString& s) {
if (m_pUser->GetIdent().Equals(s)) {
m_sIdent = "";
} else {
m_sIdent = s;
}
}
void CIRCNetwork::SetRealName(const CString& s) {
if (m_pUser->GetRealName().Equals(s)) {
m_sRealName = "";
} else {
m_sRealName = s;
}
}
void CIRCNetwork::SetBindHost(const CString& s) {
if (m_pUser->GetBindHost().Equals(s)) {
m_sBindHost = "";
} else {
m_sBindHost = s;
}
}
void CIRCNetwork::SetEncoding(const CString& s) {
m_sEncoding = s;
if (GetIRCSock()) {
GetIRCSock()->SetEncoding(s);
}
}
void CIRCNetwork::SetQuitMsg(const CString& s) {
if (m_pUser->GetQuitMsg().Equals(s)) {
m_sQuitMsg = "";
} else {
m_sQuitMsg = s;
}
}
CString CIRCNetwork::ExpandString(const CString& sStr) const {
CString sRet;
return ExpandString(sStr, sRet);
}
CString& CIRCNetwork::ExpandString(const CString& sStr, CString& sRet) const {
sRet = sStr;
sRet.Replace("%altnick%", GetAltNick());
sRet.Replace("%bindhost%", GetBindHost());
sRet.Replace("%defnick%", GetNick());
sRet.Replace("%ident%", GetIdent());
sRet.Replace("%network%", GetName());
sRet.Replace("%nick%", GetCurNick());
sRet.Replace("%realname%", GetRealName());
return m_pUser->ExpandString(sRet, sRet);
}
bool CIRCNetwork::LoadModule(const CString& sModName, const CString& sArgs,
const CString& sNotice, CString& sError) {
CUtils::PrintAction(sNotice);
CString sModRet;
bool bModRet = GetModules().LoadModule(
sModName, sArgs, CModInfo::NetworkModule, GetUser(), this, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
sError = sModRet;
}
return bModRet;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1442_1 |
crossvul-cpp_data_good_239_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Query.h>
using std::set;
using std::map;
using std::vector;
#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \
{ \
CModule* pModule = nullptr; \
if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
pModule->SetClient(CLIENT); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(NETWORK)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(USER)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
CUser* pOldUser = pModule->GetUser(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->SetUser(USER); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
pModule->SetUser(pOldUser); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
CZNC::Get().GetModules().UnloadModule(MOD); \
} \
} \
} else { \
PutStatus(t_f("No such module {1}")(MOD)); \
} \
}
CClient::~CClient() {
if (m_spAuth) {
CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth);
pAuth->Invalidate();
}
if (m_pUser != nullptr) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CClient::SendRequiredPasswordNotice() {
PutClient(":irc.znc.in 464 " + GetNick() + " :Password required");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"You need to send your password. "
"Configure your client to send a server password.");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"To connect now, you can use /quote PASS <username>:<password>, "
"or /quote PASS <username>/<network>:<password> to connect to a "
"specific network.");
}
void CClient::ReadLine(const CString& sData) {
CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : "");
CString sLine = sData;
sLine.Replace("\n", "");
sLine.Replace("\r", "");
DEBUG("(" << GetFullName() << ") CLI -> ZNC ["
<< CDebug::Filter(sLine) << "]");
bool bReturn = false;
if (IsAttached()) {
NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn);
}
if (bReturn) return;
CMessage Message(sLine);
Message.SetClient(this);
if (IsAttached()) {
NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn);
}
if (bReturn) return;
CString sCommand = Message.GetCommand();
if (!IsAttached()) {
// The following commands happen before authentication with ZNC
if (sCommand.Equals("PASS")) {
m_bGotPass = true;
CString sAuthLine = Message.GetParam(0);
ParsePass(sAuthLine);
AuthUser();
// Don't forward this msg. ZNC has already registered us.
return;
} else if (sCommand.Equals("NICK")) {
CString sNick = Message.GetParam(0);
m_sNick = sNick;
m_bGotNick = true;
AuthUser();
// Don't forward this msg. ZNC will handle nick changes until auth
// is complete
return;
} else if (sCommand.Equals("USER")) {
CString sAuthLine = Message.GetParam(0);
if (m_sUser.empty() && !sAuthLine.empty()) {
ParseUser(sAuthLine);
}
m_bGotUser = true;
if (m_bGotPass) {
AuthUser();
} else if (!m_bInCap) {
SendRequiredPasswordNotice();
}
// Don't forward this msg. ZNC has already registered us.
return;
}
}
if (Message.GetType() == CMessage::Type::Capability) {
HandleCap(Message);
// Don't let the client talk to the server directly about CAP,
// we don't want anything enabled that ZNC does not support.
return;
}
if (!m_pUser) {
// Only CAP, NICK, USER and PASS are allowed before login
return;
}
switch (Message.GetType()) {
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
default:
bReturn = OnOtherMessage(Message);
break;
}
if (bReturn) return;
PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags));
}
void CClient::SetNick(const CString& s) { m_sNick = s; }
void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect,
bool bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientDisconnected(this);
if (bDisconnect) {
ClearServerDependentCaps();
// Tell the client they are no longer in these channels.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (const CChan* pChan : vChans) {
if (!(pChan->IsDetached())) {
PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" PART " + pChan->GetName());
}
}
}
} else if (m_pUser) {
m_pUser->UserDisconnected(this);
}
m_pNetwork = pNetwork;
if (bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientConnected(this);
} else if (m_pUser) {
m_pUser->UserConnected(this);
}
}
}
const vector<CClient*>& CClient::GetClients() const {
if (m_pNetwork) {
return m_pNetwork->GetClients();
}
return m_pUser->GetUserClients();
}
const CIRCSock* CClient::GetIRCSock() const {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
CIRCSock* CClient::GetIRCSock() {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
void CClient::StatusCTCP(const CString& sLine) {
CString sCommand = sLine.Token(0);
if (sCommand.Equals("PING")) {
PutStatusNotice("\001PING " + sLine.Token(1, true) + "\001");
} else if (sCommand.Equals("VERSION")) {
PutStatusNotice("\001VERSION " + CZNC::GetTag() + "\001");
}
}
bool CClient::SendMotd() {
const VCString& vsMotd = CZNC::Get().GetMotd();
if (!vsMotd.size()) {
return false;
}
for (const CString& sLine : vsMotd) {
if (m_pNetwork) {
PutStatusNotice(m_pNetwork->ExpandString(sLine));
} else {
PutStatusNotice(m_pUser->ExpandString(sLine));
}
}
return true;
}
void CClient::AuthUser() {
if (!m_bGotNick || !m_bGotUser || !m_bGotPass || m_bInCap || IsAttached())
return;
m_spAuth = std::make_shared<CClientAuth>(this, m_sUser, m_sPass);
CZNC::Get().AuthUser(m_spAuth);
}
CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername,
const CString& sPassword)
: CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {}
void CClientAuth::RefusedLogin(const CString& sReason) {
if (m_pClient) {
m_pClient->RefuseLogin(sReason);
}
}
CString CAuthBase::GetRemoteIP() const {
if (m_pSock) return m_pSock->GetRemoteIP();
return "";
}
void CAuthBase::Invalidate() { m_pSock = nullptr; }
void CAuthBase::AcceptLogin(CUser& User) {
if (m_pSock) {
AcceptedLogin(User);
Invalidate();
}
}
void CAuthBase::RefuseLogin(const CString& sReason) {
if (!m_pSock) return;
CUser* pUser = CZNC::Get().FindUser(GetUsername());
// If the username is valid, notify that user that someone tried to
// login. Use sReason because there are other reasons than "wrong
// password" for a login to be rejected (e.g. fail2ban).
if (pUser) {
pUser->PutStatusNotice(t_f(
"A client from {1} attempted to login as you, but was rejected: "
"{2}")(GetRemoteIP(), sReason));
}
GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING);
RefusedLogin(sReason);
Invalidate();
}
void CClient::RefuseLogin(const CString& sReason) {
PutStatus("Bad username and/or password.");
PutClient(":irc.znc.in 464 " + GetNick() + " :" + sReason);
Close(Csock::CLT_AFTERWRITE);
}
void CClientAuth::AcceptedLogin(CUser& User) {
if (m_pClient) {
m_pClient->AcceptLogin(User);
}
}
void CClient::AcceptLogin(CUser& User) {
m_sPass = "";
m_pUser = &User;
// Set our proper timeout and set back our proper timeout mode
// (constructor set a different timeout and mode)
SetTimeout(User.GetNoTrafficTimeout(), TMO_READ);
SetSockName("USR::" + m_pUser->GetUserName());
SetEncoding(m_pUser->GetClientEncoding());
if (!m_sNetwork.empty()) {
m_pNetwork = m_pUser->FindNetwork(m_sNetwork);
if (!m_pNetwork) {
PutStatus(t_f("Network {1} doesn't exist.")(m_sNetwork));
}
} else if (!m_pUser->GetNetworks().empty()) {
// If a user didn't supply a network, and they have a network called
// "default" then automatically use this network.
m_pNetwork = m_pUser->FindNetwork("default");
// If no "default" network, try "user" network. It's for compatibility
// with early network stuff in ZNC, which converted old configs to
// "user" network.
if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user");
// Otherwise, just try any network of the user.
if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin();
if (m_pNetwork && m_pUser->GetNetworks().size() > 1) {
PutStatusNotice(
t_s("You have several networks configured, but no network was "
"specified for the connection."));
PutStatusNotice(
t_f("Selecting network {1}. To see list of all configured "
"networks, use /znc ListNetworks")(m_pNetwork->GetName()));
PutStatusNotice(t_f(
"If you want to choose another network, use /znc JumpNetwork "
"<network>, or connect to ZNC with username {1}/<network> "
"(instead of just {1})")(m_pUser->GetUserName()));
}
} else {
PutStatusNotice(
t_s("You have no networks configured. Use /znc AddNetwork "
"<network> to add one."));
}
SetNetwork(m_pNetwork, false);
SendMotd();
NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING);
}
void CClient::Timeout() { PutClient("ERROR :" + t_s("Closing link: Timeout")); }
void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); }
void CClient::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
}
void CClient::Disconnected() {
DEBUG(GetSockName() << " == Disconnected()");
CIRCNetwork* pNetwork = m_pNetwork;
SetNetwork(nullptr, false, false);
if (m_pUser) {
NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this,
NOTHING);
}
}
void CClient::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (IsAttached()) {
PutClient("ERROR :" + t_s("Closing link: Too long raw line"));
}
Close();
}
void CClient::BouncedOff() {
PutStatusNotice(
t_s("You are being disconnected because another user just "
"authenticated as you."));
Close(Csock::CLT_AFTERWRITE);
}
void CClient::PutIRC(const CString& sLine) {
if (m_pNetwork) {
m_pNetwork->PutIRC(sLine);
}
}
CString CClient::GetFullName() const {
if (!m_pUser) return GetRemoteIP();
CString sFullName = m_pUser->GetUserName();
if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier;
if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName();
return sFullName;
}
void CClient::PutClient(const CString& sLine) {
PutClient(CMessage(sLine));
}
bool CClient::PutClient(const CMessage& Message) {
if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
return false;
} else if (!m_bAccountNotify &&
Message.GetType() == CMessage::Type::Account) {
return false;
}
CMessage Msg(Message);
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
if (Msg.GetType() == CMessage::Type::Numeric) {
unsigned int uCode = Msg.As<CNumericMessage>().GetCode();
if (uCode == 352) { // RPL_WHOREPLY
if (!m_bNamesx && pIRCSock->HasNamesx()) {
// The server has NAMESX, but the client doesn't, so we need
// to remove extra prefixes
CString sNick = Msg.GetParam(6);
if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
CString sNewNick = sNick;
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNewNick = sNick[0] + sNick.substr(pos);
}
Msg.SetParam(6, sNewNick);
}
}
} else if (uCode == 353) { // RPL_NAMES
if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
(!m_bUHNames && pIRCSock->HasUHNames())) {
// The server has either UHNAMES or NAMESX, but the client
// is missing either or both
CString sNicks = Msg.GetParam(3);
VCString vsNicks;
sNicks.Split(" ", vsNicks, false);
for (CString& sNick : vsNicks) {
if (sNick.empty()) break;
if (!m_bNamesx && pIRCSock->HasNamesx() &&
pIRCSock->IsPermChar(sNick[0])) {
// The server has NAMESX, but the client doesn't, so
// we just use the first perm char
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNick = sNick[0] + sNick.substr(pos);
}
}
if (!m_bUHNames && pIRCSock->HasUHNames()) {
// The server has UHNAMES, but the client doesn't,
// so we strip away ident and host
sNick = sNick.Token(0, false, "!");
}
}
Msg.SetParam(
3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
}
}
} else if (Msg.GetType() == CMessage::Type::Join) {
if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
}
}
}
MCString mssTags;
for (const auto& it : Msg.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
if (HasServerTime()) {
// If the server didn't set the time tag, manually set it
mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
}
Msg.SetTags(mssTags);
Msg.SetClient(this);
Msg.SetNetwork(m_pNetwork);
bool bReturn = false;
NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
return PutClientRaw(Msg.ToString());
}
bool CClient::PutClientRaw(const CString& sLine) {
CString sCopy = sLine;
bool bReturn = false;
NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
return true;
}
void CClient::PutStatusNotice(const CString& sLine) {
PutModNotice("status", sLine);
}
unsigned int CClient::PutStatus(const CTable& table) {
unsigned int idx = 0;
CString sLine;
while (table.GetLine(idx++, sLine)) PutStatus(sLine);
return idx - 1;
}
void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); }
void CClient::PutModNotice(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in NOTICE " << GetNick() << " :" << sLine
<< "]");
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " +
GetNick() + " :" + sLine + "\r\n");
}
void CClient::PutModule(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine
<< "]");
VCString vsLines;
sLine.Split("\n", vsLines);
for (const CString& s : vsLines) {
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n");
}
}
CString CClient::GetNick(bool bAllowIRCNick) const {
CString sRet;
const CIRCSock* pSock = GetIRCSock();
if (bAllowIRCNick && pSock && pSock->IsAuthed()) {
sRet = pSock->GetNick();
}
return (sRet.empty()) ? m_sNick : sRet;
}
CString CClient::GetNickMask() const {
if (GetIRCSock() && GetIRCSock()->IsAuthed()) {
return GetIRCSock()->GetNickMask();
}
CString sHost =
m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost();
if (sHost.empty()) {
sHost = "irc.znc.in";
}
return GetNick() + "!" +
(m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" +
sHost;
}
bool CClient::IsValidIdentifier(const CString& sIdentifier) {
// ^[-\w]+$
if (sIdentifier.empty()) {
return false;
}
const char* p = sIdentifier.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
void CClient::RespondCap(const CString& sResponse) {
PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse);
}
void CClient::HandleCap(const CMessage& Message) {
CString sSubCmd = Message.GetParam(0);
if (sSubCmd.Equals("LS")) {
SCString ssOfferCaps;
for (const auto& it : m_mCoreCaps) {
bool bServerDependent = std::get<0>(it.second);
if (!bServerDependent ||
m_ssServerDependentCaps.count(it.first) > 0)
ssOfferCaps.insert(it.first);
}
GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING);
CString sRes =
CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end());
RespondCap("LS :" + sRes);
m_bInCap = true;
if (Message.GetParam(1).ToInt() >= 302) {
m_bCapNotify = true;
}
} else if (sSubCmd.Equals("END")) {
m_bInCap = false;
if (!IsAttached()) {
if (!m_pUser && m_bGotUser && !m_bGotPass) {
SendRequiredPasswordNotice();
} else {
AuthUser();
}
}
} else if (sSubCmd.Equals("REQ")) {
VCString vsTokens;
Message.GetParam(1).Split(" ", vsTokens, false);
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
bool bAccepted = false;
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
bAccepted = !bServerDependent ||
m_ssServerDependentCaps.count(sCap) > 0;
}
GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal),
&bAccepted);
if (!bAccepted) {
// Some unsupported capability is requested
RespondCap("NAK :" + Message.GetParam(1));
return;
}
}
// All is fine, we support what was requested
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
auto handler_it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != handler_it) {
const auto& handler = std::get<1>(handler_it->second);
handler(bVal);
}
GLOBALMODULECALL(OnClientCapRequest(this, sCap, bVal), NOTHING);
if (bVal) {
m_ssAcceptedCaps.insert(sCap);
} else {
m_ssAcceptedCaps.erase(sCap);
}
}
RespondCap("ACK :" + Message.GetParam(1));
} else if (sSubCmd.Equals("LIST")) {
CString sList =
CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end());
RespondCap("LIST :" + sList);
} else {
PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd +
" :Invalid CAP subcommand");
}
}
void CClient::ParsePass(const CString& sAuthLine) {
// [user[@identifier][/network]:]password
const size_t uColon = sAuthLine.find(":");
if (uColon != CString::npos) {
m_sPass = sAuthLine.substr(uColon + 1);
ParseUser(sAuthLine.substr(0, uColon));
} else {
m_sPass = sAuthLine;
}
}
void CClient::ParseUser(const CString& sAuthLine) {
// user[@identifier][/network]
const size_t uSlash = sAuthLine.rfind("/");
if (uSlash != CString::npos) {
m_sNetwork = sAuthLine.substr(uSlash + 1);
ParseIdentifier(sAuthLine.substr(0, uSlash));
} else {
ParseIdentifier(sAuthLine);
}
}
void CClient::ParseIdentifier(const CString& sAuthLine) {
// user[@identifier]
const size_t uAt = sAuthLine.rfind("@");
if (uAt != CString::npos) {
const CString sId = sAuthLine.substr(uAt + 1);
if (IsValidIdentifier(sId)) {
m_sIdentifier = sId;
m_sUser = sAuthLine.substr(0, uAt);
} else {
m_sUser = sAuthLine;
}
} else {
m_sUser = sAuthLine;
}
}
void CClient::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
void CClient::NotifyServerDependentCaps(const SCString& ssCaps) {
for (const CString& sCap : ssCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
if (bServerDependent) {
m_ssServerDependentCaps.insert(sCap);
}
}
}
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps);
}
}
void CClient::ClearServerDependentCaps() {
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps);
for (const CString& sCap : m_ssServerDependentCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
const auto& handler = std::get<1>(it->second);
handler(false);
}
}
}
m_ssServerDependentCaps.clear();
}
template <typename T>
void CClient::AddBuffer(const T& Message) {
const CString sTarget = Message.GetTarget();
T Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(GetNickMask())));
Format.SetTarget(_NAMEDFMT(sTarget));
Format.SetText("{text}");
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline()) {
pChan->AddBuffer(Format, Message.GetText());
}
} else if (Message.GetType() != CMessage::Type::Notice) {
if (!m_pUser->AutoClearQueryBuffer() || !m_pNetwork->IsUserOnline()) {
CQuery* pQuery = m_pNetwork->AddQuery(sTarget);
if (pQuery) {
pQuery->AddBuffer(Format, Message.GetText());
}
}
}
}
void CClient::EchoMessage(const CMessage& Message) {
CMessage EchoedMessage = Message;
for (CClient* pClient : GetClients()) {
if (pClient->HasEchoMessage() ||
(pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||
pClient->HasSelfMessage()))) {
EchoedMessage.SetNick(GetNickMask());
pClient->PutClient(EchoedMessage);
}
}
}
set<CChan*> CClient::MatchChans(const CString& sPatterns) const {
VCString vsPatterns;
sPatterns.Replace_n(",", " ")
.Split(" ", vsPatterns, false, "", "", true, true);
set<CChan*> sChans;
for (const CString& sPattern : vsPatterns) {
vector<CChan*> vChans = m_pNetwork->FindChans(sPattern);
sChans.insert(vChans.begin(), vChans.end());
}
return sChans;
}
unsigned int CClient::AttachChans(const std::set<CChan*>& sChans) {
unsigned int uAttached = 0;
for (CChan* pChan : sChans) {
if (!pChan->IsDetached()) continue;
uAttached++;
pChan->AttachUser();
}
return uAttached;
}
unsigned int CClient::DetachChans(const std::set<CChan*>& sChans) {
unsigned int uDetached = 0;
for (CChan* pChan : sChans) {
if (pChan->IsDetached()) continue;
uDetached++;
pChan->DetachUser();
}
return uDetached;
}
bool CClient::OnActionMessage(CActionMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnCTCPMessage(CCTCPMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
if (Message.IsReply()) {
CString sCTCP = Message.GetText();
if (sCTCP.Token(0) == "VERSION") {
// There are 2 different scenarios:
//
// a) CTCP reply for VERSION is not set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC forwards CTCP VERSION to client
// 3. Client replies with something
// 4. ZNC adds itself to the reply
// 5. ZNC sends the modified reply to whoever asked
//
// b) CTCP reply for VERSION is set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC replies with the configured reply (or just drops it if
// empty), without forwarding anything to client
// 3. Client does not see any CTCP request, and does not reply
//
// So, if user doesn't want "via ZNC" in CTCP VERSION reply, they
// can set custom reply.
//
// See more bikeshedding at github issues #820 and #1012
Message.SetText(sCTCP + " via " + CZNC::GetTag(false));
}
}
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
if (Message.IsReply()) {
NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser,
m_pNetwork, this, &bContinue);
} else {
NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
}
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(t_f(
"Your CTCP to {1} got lost, you are not connected to IRC!")(
Message.GetTarget()));
continue;
}
if (m_pNetwork) {
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnJoinMessage(CJoinMessage& Message) {
CString sChans = Message.GetTarget();
CString sKeys = Message.GetKey();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
VCString vsKeys;
sKeys.Split(",", vsKeys, true);
sKeys.clear();
for (unsigned int a = 0; a < vsChans.size(); a++) {
Message.SetTarget(vsChans[a]);
Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : "");
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(vsChans[a]));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
CString sChannel = Message.GetTarget();
CString sKey = Message.GetKey();
if (m_pNetwork) {
CChan* pChan = m_pNetwork->FindChan(sChannel);
if (pChan) {
if (pChan->IsDetached())
pChan->AttachUser(this);
else
pChan->JoinUser(sKey);
continue;
} else if (!sChannel.empty()) {
pChan = new CChan(sChannel, m_pNetwork, false);
if (m_pNetwork->AddChan(pChan)) {
pChan->SetKey(sKey);
}
}
}
if (!sChannel.empty()) {
sChans += (sChans.empty()) ? sChannel : CString("," + sChannel);
if (!vsKeys.empty()) {
sKeys += (sKeys.empty()) ? sKey : CString("," + sKey);
}
}
}
Message.SetTarget(sChans);
Message.SetKey(sKeys);
return sChans.empty();
}
bool CClient::OnModeMessage(CModeMessage& Message) {
CString sTarget = Message.GetTarget();
CString sModes = Message.GetModes();
if (m_pNetwork && m_pNetwork->IsChan(sTarget) && sModes.empty()) {
// If we are on that channel and already received a
// /mode reply from the server, we can answer this
// request ourself.
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
" " + sTarget + " " + pChan->GetModeString());
if (pChan->GetCreationDate() > 0) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
GetNick() + " " + sTarget + " " +
CString(pChan->GetCreationDate()));
}
return true;
}
}
return false;
}
bool CClient::OnNoticeMessage(CNoticeMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (!sTarget.Equals("status")) {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModNotice(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your notice to {1} got lost, you are not connected to "
"IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnPartMessage(CPartMessage& Message) {
CString sChans = Message.GetTarget();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
for (CString& sChan : vsChans) {
bool bContinue = false;
Message.SetTarget(sChan);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
sChan = Message.GetTarget();
CChan* pChan = m_pNetwork ? m_pNetwork->FindChan(sChan) : nullptr;
if (pChan && !pChan->IsOn()) {
PutStatusNotice(t_f("Removing channel {1}")(sChan));
m_pNetwork->DelChan(sChan);
} else {
sChans += (sChans.empty()) ? sChan : CString("," + sChan);
}
}
if (sChans.empty()) {
return true;
}
Message.SetTarget(sChans);
return false;
}
bool CClient::OnPingMessage(CMessage& Message) {
// All PONGs are generated by ZNC. We will still forward this to
// the ircd, but all PONGs from irc will be blocked.
if (!Message.GetParams().empty())
PutClient(":irc.znc.in PONG irc.znc.in " + Message.GetParamsColon(0));
else
PutClient(":irc.znc.in PONG irc.znc.in");
return false;
}
bool CClient::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CClient::OnQuitMessage(CQuitMessage& Message) {
bool bReturn = false;
NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
if (!bReturn) {
Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach
}
// Don't forward this msg. We don't want the client getting us
// disconnected.
return true;
}
bool CClient::OnTextMessage(CTextMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (sTarget.Equals("status")) {
CString sMsg = Message.GetText();
UserCommand(sMsg);
} else {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a PRIVMSG to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your message to {1} got lost, you are not connected "
"to IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnTopicMessage(CTopicMessage& Message) {
bool bReturn = false;
CString sChan = Message.GetTarget();
CString sTopic = Message.GetTopic();
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
if (!sTopic.empty()) {
NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork,
this, &bReturn);
} else {
NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this,
&bReturn);
Message.SetTarget(sChan);
}
return bReturn;
}
bool CClient::OnOtherMessage(CMessage& Message) {
const CString& sCommand = Message.GetCommand();
if (sCommand.Equals("ZNC")) {
CString sTarget = Message.GetParam(0);
CString sModCommand;
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
sModCommand = Message.GetParamsColon(1);
} else {
sTarget = "status";
sModCommand = Message.GetParamsColon(0);
}
if (sTarget.Equals("status")) {
if (sModCommand.empty())
PutStatus(t_s("Hello. How may I help you?"));
else
UserCommand(sModCommand);
} else {
if (sModCommand.empty())
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
PutModule(t_s("Hello. How may I help you?")))
else
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(sModCommand))
}
return true;
} else if (sCommand.Equals("ATTACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /attach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uAttachedChans = AttachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Attached {1} channel", "Attached {1} channels",
uAttachedChans)(uAttachedChans));
return true;
} else if (sCommand.Equals("DETACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /detach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uDetached = DetachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Detached {1} channel", "Detached {1} channels",
uDetached)(uDetached));
return true;
} else if (sCommand.Equals("PROTOCTL")) {
for (const CString& sParam : Message.GetParams()) {
if (sParam == "NAMESX") {
m_bNamesx = true;
} else if (sParam == "UHNAMES") {
m_bUHNames = true;
}
}
return true; // If the server understands it, we already enabled namesx
// / uhnames
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_239_0 |
crossvul-cpp_data_good_1442_2 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/User.h>
#include <znc/Config.h>
#include <znc/FileUtils.h>
#include <znc/IRCNetwork.h>
#include <znc/IRCSock.h>
#include <znc/Chan.h>
#include <znc/Query.h>
#include <math.h>
#include <time.h>
#include <algorithm>
using std::vector;
using std::set;
class CUserTimer : public CCron {
public:
CUserTimer(CUser* pUser) : CCron(), m_pUser(pUser) {
SetName("CUserTimer::" + m_pUser->GetUserName());
Start(m_pUser->GetPingSlack());
}
~CUserTimer() override {}
CUserTimer(const CUserTimer&) = delete;
CUserTimer& operator=(const CUserTimer&) = delete;
private:
protected:
void RunJob() override {
const vector<CClient*>& vUserClients = m_pUser->GetUserClients();
for (CClient* pUserClient : vUserClients) {
if (pUserClient->GetTimeSinceLastDataTransaction() >=
m_pUser->GetPingFrequency()) {
pUserClient->PutClient("PING :ZNC");
}
}
// Restart timer for the case if the period had changed. Usually this is
// noop
Start(m_pUser->GetPingSlack());
}
CUser* m_pUser;
};
CUser::CUser(const CString& sUserName)
: m_sUserName(sUserName),
m_sCleanUserName(MakeCleanUserName(sUserName)),
m_sNick(m_sCleanUserName),
m_sAltNick(""),
m_sIdent(m_sCleanUserName),
m_sRealName(""),
m_sBindHost(""),
m_sDCCBindHost(""),
m_sPass(""),
m_sPassSalt(""),
m_sStatusPrefix("*"),
m_sDefaultChanModes(""),
m_sClientEncoding(""),
m_sQuitMsg(""),
m_mssCTCPReplies(),
m_sTimestampFormat("[%H:%M:%S]"),
m_sTimezone(""),
m_eHashType(HASH_NONE),
m_sUserPath(CZNC::Get().GetUserPath() + "/" + sUserName),
m_bMultiClients(true),
m_bDenyLoadMod(false),
m_bAdmin(false),
m_bDenySetBindHost(false),
m_bAutoClearChanBuffer(true),
m_bAutoClearQueryBuffer(true),
m_bBeingDeleted(false),
m_bAppendTimestamp(false),
m_bPrependTimestamp(true),
m_bAuthOnlyViaModule(false),
m_pUserTimer(nullptr),
m_vIRCNetworks(),
m_vClients(),
m_ssAllowedHosts(),
m_uChanBufferSize(50),
m_uQueryBufferSize(50),
m_uBytesRead(0),
m_uBytesWritten(0),
m_uMaxJoinTries(10),
m_uMaxNetworks(1),
m_uMaxQueryBuffers(50),
m_uMaxJoins(0),
m_uNoTrafficTimeout(180),
m_sSkinName(""),
m_pModules(new CModules) {
m_pUserTimer = new CUserTimer(this);
CZNC::Get().GetManager().AddCron(m_pUserTimer);
}
CUser::~CUser() {
// Delete networks
while (!m_vIRCNetworks.empty()) {
delete *m_vIRCNetworks.begin();
}
// Delete clients
while (!m_vClients.empty()) {
CZNC::Get().GetManager().DelSockByAddr(m_vClients[0]);
}
m_vClients.clear();
// Delete modules (unloads all modules!)
delete m_pModules;
m_pModules = nullptr;
CZNC::Get().GetManager().DelCronByAddr(m_pUserTimer);
CZNC::Get().AddBytesRead(m_uBytesRead);
CZNC::Get().AddBytesWritten(m_uBytesWritten);
}
template <class T>
struct TOption {
const char* name;
void (CUser::*pSetter)(T);
};
bool CUser::ParseConfig(CConfig* pConfig, CString& sError) {
TOption<const CString&> StringOptions[] = {
{"nick", &CUser::SetNick},
{"quitmsg", &CUser::SetQuitMsg},
{"altnick", &CUser::SetAltNick},
{"ident", &CUser::SetIdent},
{"realname", &CUser::SetRealName},
{"chanmodes", &CUser::SetDefaultChanModes},
{"bindhost", &CUser::SetBindHost},
{"vhost", &CUser::SetBindHost},
{"dccbindhost", &CUser::SetDCCBindHost},
{"dccvhost", &CUser::SetDCCBindHost},
{"timestampformat", &CUser::SetTimestampFormat},
{"skin", &CUser::SetSkinName},
{"clientencoding", &CUser::SetClientEncoding},
};
TOption<unsigned int> UIntOptions[] = {
{"jointries", &CUser::SetJoinTries},
{"maxnetworks", &CUser::SetMaxNetworks},
{"maxquerybuffers", &CUser::SetMaxQueryBuffers},
{"maxjoins", &CUser::SetMaxJoins},
{"notraffictimeout", &CUser::SetNoTrafficTimeout},
};
TOption<bool> BoolOptions[] = {
{"keepbuffer",
&CUser::SetKeepBuffer}, // XXX compatibility crap from pre-0.207
{"autoclearchanbuffer", &CUser::SetAutoClearChanBuffer},
{"autoclearquerybuffer", &CUser::SetAutoClearQueryBuffer},
{"multiclients", &CUser::SetMultiClients},
{"denyloadmod", &CUser::SetDenyLoadMod},
{"admin", &CUser::SetAdmin},
{"denysetbindhost", &CUser::SetDenySetBindHost},
{"denysetvhost", &CUser::SetDenySetBindHost},
{"appendtimestamp", &CUser::SetTimestampAppend},
{"prependtimestamp", &CUser::SetTimestampPrepend},
{"authonlyviamodule", &CUser::SetAuthOnlyViaModule},
};
for (const auto& Option : StringOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue);
}
for (const auto& Option : UIntOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue.ToUInt());
}
for (const auto& Option : BoolOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue.ToBool());
}
VCString vsList;
pConfig->FindStringVector("allow", vsList);
for (const CString& sHost : vsList) {
AddAllowedHost(sHost);
}
pConfig->FindStringVector("ctcpreply", vsList);
for (const CString& sReply : vsList) {
AddCTCPReply(sReply.Token(0), sReply.Token(1, true));
}
CString sValue;
CString sDCCLookupValue;
pConfig->FindStringEntry("dcclookupmethod", sDCCLookupValue);
if (pConfig->FindStringEntry("bouncedccs", sValue)) {
if (sValue.ToBool()) {
CUtils::PrintAction("Loading Module [bouncedcc]");
CString sModRet;
bool bModRet = GetModules().LoadModule(
"bouncedcc", "", CModInfo::UserModule, this, nullptr, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
sError = sModRet;
return false;
}
if (sDCCLookupValue.Equals("Client")) {
GetModules().FindModule("bouncedcc")->SetNV("UseClientIP", "1");
}
}
}
if (pConfig->FindStringEntry("buffer", sValue))
SetBufferCount(sValue.ToUInt(), true);
if (pConfig->FindStringEntry("chanbuffersize", sValue))
SetChanBufferSize(sValue.ToUInt(), true);
if (pConfig->FindStringEntry("querybuffersize", sValue))
SetQueryBufferSize(sValue.ToUInt(), true);
if (pConfig->FindStringEntry("awaysuffix", sValue)) {
CUtils::PrintMessage(
"WARNING: AwaySuffix has been deprecated, instead try -> "
"LoadModule = awaynick %nick%_" +
sValue);
}
if (pConfig->FindStringEntry("autocycle", sValue)) {
if (sValue.Equals("true"))
CUtils::PrintError(
"WARNING: AutoCycle has been removed, instead try -> "
"LoadModule = autocycle");
}
if (pConfig->FindStringEntry("keepnick", sValue)) {
if (sValue.Equals("true"))
CUtils::PrintError(
"WARNING: KeepNick has been deprecated, instead try -> "
"LoadModule = keepnick");
}
if (pConfig->FindStringEntry("statusprefix", sValue)) {
if (!SetStatusPrefix(sValue)) {
sError = "Invalid StatusPrefix [" + sValue +
"] Must be 1-5 chars, no spaces.";
CUtils::PrintError(sError);
return false;
}
}
if (pConfig->FindStringEntry("timezone", sValue)) {
SetTimezone(sValue);
}
if (pConfig->FindStringEntry("timezoneoffset", sValue)) {
if (fabs(sValue.ToDouble()) > 0.1) {
CUtils::PrintError(
"WARNING: TimezoneOffset has been deprecated, now you can set "
"your timezone by name");
}
}
if (pConfig->FindStringEntry("timestamp", sValue)) {
if (!sValue.Trim_n().Equals("true")) {
if (sValue.Trim_n().Equals("append")) {
SetTimestampAppend(true);
SetTimestampPrepend(false);
} else if (sValue.Trim_n().Equals("prepend")) {
SetTimestampAppend(false);
SetTimestampPrepend(true);
} else if (sValue.Trim_n().Equals("false")) {
SetTimestampAppend(false);
SetTimestampPrepend(false);
} else {
SetTimestampFormat(sValue);
}
}
}
if (pConfig->FindStringEntry("language", sValue)) {
SetLanguage(sValue);
}
pConfig->FindStringEntry("pass", sValue);
// There are different formats for this available:
// Pass = <plain text>
// Pass = <md5 hash> -
// Pass = plain#<plain text>
// Pass = <hash name>#<hash>
// Pass = <hash name>#<salted hash>#<salt>#
// 'Salted hash' means hash of 'password' + 'salt'
// Possible hashes are md5 and sha256
if (sValue.TrimSuffix("-")) {
SetPass(sValue.Trim_n(), CUser::HASH_MD5);
} else {
CString sMethod = sValue.Token(0, false, "#");
CString sPass = sValue.Token(1, true, "#");
if (sMethod == "md5" || sMethod == "sha256") {
CUser::eHashType type = CUser::HASH_MD5;
if (sMethod == "sha256") type = CUser::HASH_SHA256;
CString sSalt = sPass.Token(1, false, "#");
sPass = sPass.Token(0, false, "#");
SetPass(sPass, type, sSalt);
} else if (sMethod == "plain") {
SetPass(sPass, CUser::HASH_NONE);
} else {
SetPass(sValue, CUser::HASH_NONE);
}
}
CConfig::SubConfig subConf;
CConfig::SubConfig::const_iterator subIt;
pConfig->FindSubConfig("pass", subConf);
if (!sValue.empty() && !subConf.empty()) {
sError = "Password defined more than once";
CUtils::PrintError(sError);
return false;
}
subIt = subConf.begin();
if (subIt != subConf.end()) {
CConfig* pSubConf = subIt->second.m_pSubConfig;
CString sHash;
CString sMethod;
CString sSalt;
CUser::eHashType method;
pSubConf->FindStringEntry("hash", sHash);
pSubConf->FindStringEntry("method", sMethod);
pSubConf->FindStringEntry("salt", sSalt);
if (sMethod.empty() || sMethod.Equals("plain"))
method = CUser::HASH_NONE;
else if (sMethod.Equals("md5"))
method = CUser::HASH_MD5;
else if (sMethod.Equals("sha256"))
method = CUser::HASH_SHA256;
else {
sError = "Invalid hash method";
CUtils::PrintError(sError);
return false;
}
SetPass(sHash, method, sSalt);
if (!pSubConf->empty()) {
sError = "Unhandled lines in config!";
CUtils::PrintError(sError);
CZNC::DumpConfig(pSubConf);
return false;
}
++subIt;
}
if (subIt != subConf.end()) {
sError = "Password defined more than once";
CUtils::PrintError(sError);
return false;
}
pConfig->FindSubConfig("network", subConf);
for (subIt = subConf.begin(); subIt != subConf.end(); ++subIt) {
const CString& sNetworkName = subIt->first;
CUtils::PrintMessage("Loading network [" + sNetworkName + "]");
CIRCNetwork* pNetwork = FindNetwork(sNetworkName);
if (!pNetwork) {
pNetwork = new CIRCNetwork(this, sNetworkName);
}
if (!pNetwork->ParseConfig(subIt->second.m_pSubConfig, sError)) {
return false;
}
}
if (pConfig->FindStringVector("server", vsList, false) ||
pConfig->FindStringVector("chan", vsList, false) ||
pConfig->FindSubConfig("chan", subConf, false)) {
CIRCNetwork* pNetwork = FindNetwork("default");
if (!pNetwork) {
CString sErrorDummy;
pNetwork = AddNetwork("default", sErrorDummy);
}
if (pNetwork) {
CUtils::PrintMessage(
"NOTICE: Found deprecated config, upgrading to a network");
if (!pNetwork->ParseConfig(pConfig, sError, true)) {
return false;
}
}
}
pConfig->FindStringVector("loadmodule", vsList);
for (const CString& sMod : vsList) {
CString sModName = sMod.Token(0);
CString sNotice = "Loading user module [" + sModName + "]";
// XXX Legacy crap, added in ZNC 0.089
if (sModName == "discon_kick") {
sNotice =
"NOTICE: [discon_kick] was renamed, loading [disconkick] "
"instead";
sModName = "disconkick";
}
// XXX Legacy crap, added in ZNC 0.099
if (sModName == "fixfreenode") {
sNotice =
"NOTICE: [fixfreenode] doesn't do anything useful anymore, "
"ignoring it";
CUtils::PrintMessage(sNotice);
continue;
}
// XXX Legacy crap, added in ZNC 0.207
if (sModName == "admin") {
sNotice =
"NOTICE: [admin] module was renamed, loading [controlpanel] "
"instead";
sModName = "controlpanel";
}
// XXX Legacy crap, should have been added ZNC 0.207, but added only in
// 1.1 :(
if (sModName == "away") {
sNotice = "NOTICE: [away] was renamed, loading [awaystore] instead";
sModName = "awaystore";
}
// XXX Legacy crap, added in 1.1; fakeonline module was dropped in 1.0
// and returned in 1.1
if (sModName == "fakeonline") {
sNotice =
"NOTICE: [fakeonline] was renamed, loading [modules_online] "
"instead";
sModName = "modules_online";
}
// XXX Legacy crap, added in 1.3
if (sModName == "charset") {
CUtils::PrintAction(
"NOTICE: Charset support was moved to core, importing old "
"charset module settings");
size_t uIndex = 1;
if (sMod.Token(uIndex).Equals("-force")) {
uIndex++;
}
VCString vsClient, vsServer;
sMod.Token(uIndex).Split(",", vsClient);
sMod.Token(uIndex + 1).Split(",", vsServer);
if (vsClient.empty() || vsServer.empty()) {
CUtils::PrintStatus(
false, "charset module was loaded with wrong parameters.");
continue;
}
SetClientEncoding(vsClient[0]);
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
pNetwork->SetEncoding(vsServer[0]);
}
CUtils::PrintStatus(true, "Using [" + vsClient[0] +
"] for clients, and [" + vsServer[0] +
"] for servers");
continue;
}
CString sModRet;
CString sArgs = sMod.Token(1, true);
bool bModRet = LoadModule(sModName, sArgs, sNotice, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
// XXX The awaynick module was retired in 1.6 (still available as
// external module)
if (sModName == "awaynick") {
// load simple_away instead, unless it's already on the list
if (std::find(vsList.begin(), vsList.end(), "simple_away") ==
vsList.end()) {
sNotice = "Loading [simple_away] module instead";
sModName = "simple_away";
// not a fatal error if simple_away is not available
LoadModule(sModName, sArgs, sNotice, sModRet);
}
} else {
sError = sModRet;
return false;
}
}
continue;
}
// Move ircconnectenabled to the networks
if (pConfig->FindStringEntry("ircconnectenabled", sValue)) {
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
pNetwork->SetIRCConnectEnabled(sValue.ToBool());
}
}
return true;
}
CIRCNetwork* CUser::AddNetwork(const CString& sNetwork, CString& sErrorRet) {
if (!CIRCNetwork::IsValidNetwork(sNetwork)) {
sErrorRet =
t_s("Invalid network name. It should be alphanumeric. Not to be "
"confused with server name");
return nullptr;
} else if (FindNetwork(sNetwork)) {
sErrorRet = t_f("Network {1} already exists")(sNetwork);
return nullptr;
}
CIRCNetwork* pNetwork = new CIRCNetwork(this, sNetwork);
bool bCancel = false;
USERMODULECALL(OnAddNetwork(*pNetwork, sErrorRet), this, nullptr, &bCancel);
if (bCancel) {
RemoveNetwork(pNetwork);
delete pNetwork;
return nullptr;
}
return pNetwork;
}
bool CUser::AddNetwork(CIRCNetwork* pNetwork) {
if (FindNetwork(pNetwork->GetName())) {
return false;
}
m_vIRCNetworks.push_back(pNetwork);
return true;
}
void CUser::RemoveNetwork(CIRCNetwork* pNetwork) {
auto it = std::find(m_vIRCNetworks.begin(), m_vIRCNetworks.end(), pNetwork);
if (it != m_vIRCNetworks.end()) {
m_vIRCNetworks.erase(it);
}
}
bool CUser::DeleteNetwork(const CString& sNetwork) {
CIRCNetwork* pNetwork = FindNetwork(sNetwork);
if (pNetwork) {
bool bCancel = false;
USERMODULECALL(OnDeleteNetwork(*pNetwork), this, nullptr, &bCancel);
if (!bCancel) {
delete pNetwork;
return true;
}
}
return false;
}
CIRCNetwork* CUser::FindNetwork(const CString& sNetwork) const {
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (pNetwork->GetName().Equals(sNetwork)) {
return pNetwork;
}
}
return nullptr;
}
const vector<CIRCNetwork*>& CUser::GetNetworks() const {
return m_vIRCNetworks;
}
CString CUser::ExpandString(const CString& sStr) const {
CString sRet;
return ExpandString(sStr, sRet);
}
CString& CUser::ExpandString(const CString& sStr, CString& sRet) const {
CString sTime = CUtils::CTime(time(nullptr), m_sTimezone);
sRet = sStr;
sRet.Replace("%altnick%", GetAltNick());
sRet.Replace("%bindhost%", GetBindHost());
sRet.Replace("%defnick%", GetNick());
sRet.Replace("%ident%", GetIdent());
sRet.Replace("%nick%", GetNick());
sRet.Replace("%realname%", GetRealName());
sRet.Replace("%time%", sTime);
sRet.Replace("%uptime%", CZNC::Get().GetUptime());
sRet.Replace("%user%", GetUserName());
sRet.Replace("%version%", CZNC::GetVersion());
sRet.Replace("%vhost%", GetBindHost());
sRet.Replace("%znc%", CZNC::GetTag(false));
// Allows for escaping ExpandString if necessary, or to prevent
// defaults from kicking in if you don't want them.
sRet.Replace("%empty%", "");
// The following lines do not exist. You must be on DrUgS!
sRet.Replace("%irc%", "All your IRC are belong to ZNC");
// Chosen by fair zocchihedron dice roll by SilverLeo
sRet.Replace("%rand%", "42");
return sRet;
}
CString CUser::AddTimestamp(const CString& sStr) const {
timeval tv;
gettimeofday(&tv, nullptr);
return AddTimestamp(tv, sStr);
}
CString CUser::AddTimestamp(time_t tm, const CString& sStr) const {
timeval tv;
tv.tv_sec = tm;
tv.tv_usec = 0;
return AddTimestamp(tv, sStr);
}
CString CUser::AddTimestamp(timeval tv, const CString& sStr) const {
CString sRet = sStr;
if (!GetTimestampFormat().empty() &&
(m_bAppendTimestamp || m_bPrependTimestamp)) {
CString sTimestamp =
CUtils::FormatTime(tv, GetTimestampFormat(), m_sTimezone);
if (sTimestamp.empty()) {
return sRet;
}
if (m_bPrependTimestamp) {
sRet = sTimestamp;
sRet += " " + sStr;
}
if (m_bAppendTimestamp) {
// From http://www.mirc.com/colors.html
// The Control+O key combination in mIRC inserts ascii character 15,
// which turns off all previous attributes, including color, bold,
// underline, and italics.
//
// \x02 bold
// \x03 mIRC-compatible color
// \x04 RRGGBB color
// \x0F normal/reset (turn off bold, colors, etc.)
// \x12 reverse (weechat)
// \x16 reverse (mirc, kvirc)
// \x1D italic
// \x1F underline
// Also see http://www.visualirc.net/tech-attrs.php
//
// Keep in sync with CIRCSocket::IcuExt__UCallback
if (CString::npos !=
sRet.find_first_of("\x02\x03\x04\x0F\x12\x16\x1D\x1F")) {
sRet += "\x0F";
}
sRet += " " + sTimestamp;
}
}
return sRet;
}
void CUser::BounceAllClients() {
for (CClient* pClient : m_vClients) {
pClient->BouncedOff();
}
m_vClients.clear();
}
void CUser::UserConnected(CClient* pClient) {
if (!MultiClients()) {
BounceAllClients();
}
pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() + " :" +
t_s("Welcome to ZNC"));
m_vClients.push_back(pClient);
}
void CUser::UserDisconnected(CClient* pClient) {
auto it = std::find(m_vClients.begin(), m_vClients.end(), pClient);
if (it != m_vClients.end()) {
m_vClients.erase(it);
}
}
void CUser::CloneNetworks(const CUser& User) {
const vector<CIRCNetwork*>& vNetworks = User.GetNetworks();
for (CIRCNetwork* pUserNetwork : vNetworks) {
CIRCNetwork* pNetwork = FindNetwork(pUserNetwork->GetName());
if (pNetwork) {
pNetwork->Clone(*pUserNetwork);
} else {
new CIRCNetwork(this, *pUserNetwork);
}
}
set<CString> ssDeleteNetworks;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (!(User.FindNetwork(pNetwork->GetName()))) {
ssDeleteNetworks.insert(pNetwork->GetName());
}
}
for (const CString& sNetwork : ssDeleteNetworks) {
// The following will move all the clients to the user.
// So the clients are not disconnected. The client could
// have requested the rehash. Then when we do
// client->PutStatus("Rehashing succeeded!") we would
// crash if there was no client anymore.
const vector<CClient*>& vClients = FindNetwork(sNetwork)->GetClients();
while (vClients.begin() != vClients.end()) {
CClient* pClient = vClients.front();
// This line will remove pClient from vClients,
// because it's a reference to the internal Network's vector.
pClient->SetNetwork(nullptr);
}
DeleteNetwork(sNetwork);
}
}
bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks) {
sErrorRet.clear();
if (!User.IsValid(sErrorRet, true)) {
return false;
}
// user names can only specified for the constructor, changing it later
// on breaks too much stuff (e.g. lots of paths depend on the user name)
if (GetUserName() != User.GetUserName()) {
DEBUG("Ignoring username in CUser::Clone(), old username ["
<< GetUserName() << "]; New username [" << User.GetUserName()
<< "]");
}
if (!User.GetPass().empty()) {
SetPass(User.GetPass(), User.GetPassHashType(), User.GetPassSalt());
}
SetNick(User.GetNick(false));
SetAltNick(User.GetAltNick(false));
SetIdent(User.GetIdent(false));
SetRealName(User.GetRealName());
SetStatusPrefix(User.GetStatusPrefix());
SetBindHost(User.GetBindHost());
SetDCCBindHost(User.GetDCCBindHost());
SetQuitMsg(User.GetQuitMsg());
SetSkinName(User.GetSkinName());
SetDefaultChanModes(User.GetDefaultChanModes());
SetChanBufferSize(User.GetChanBufferSize(), true);
SetQueryBufferSize(User.GetQueryBufferSize(), true);
SetJoinTries(User.JoinTries());
SetMaxNetworks(User.MaxNetworks());
SetMaxQueryBuffers(User.MaxQueryBuffers());
SetMaxJoins(User.MaxJoins());
SetNoTrafficTimeout(User.GetNoTrafficTimeout());
SetClientEncoding(User.GetClientEncoding());
SetLanguage(User.GetLanguage());
// Allowed Hosts
m_ssAllowedHosts.clear();
const set<CString>& ssHosts = User.GetAllowedHosts();
for (const CString& sHost : ssHosts) {
AddAllowedHost(sHost);
}
for (CClient* pSock : m_vClients) {
if (!IsHostAllowed(pSock->GetRemoteIP())) {
pSock->PutStatusNotice(
t_s("You are being disconnected because your IP is no longer "
"allowed to connect to this user"));
pSock->Close();
}
}
// !Allowed Hosts
// Networks
if (bCloneNetworks) {
CloneNetworks(User);
}
// !Networks
// CTCP Replies
m_mssCTCPReplies.clear();
const MCString& msReplies = User.GetCTCPReplies();
for (const auto& it : msReplies) {
AddCTCPReply(it.first, it.second);
}
// !CTCP Replies
// Flags
SetAutoClearChanBuffer(User.AutoClearChanBuffer());
SetAutoClearQueryBuffer(User.AutoClearQueryBuffer());
SetMultiClients(User.MultiClients());
SetDenyLoadMod(User.DenyLoadMod());
SetAdmin(User.IsAdmin());
SetDenySetBindHost(User.DenySetBindHost());
SetAuthOnlyViaModule(User.AuthOnlyViaModule());
SetTimestampAppend(User.GetTimestampAppend());
SetTimestampPrepend(User.GetTimestampPrepend());
SetTimestampFormat(User.GetTimestampFormat());
SetTimezone(User.GetTimezone());
// !Flags
// Modules
set<CString> ssUnloadMods;
CModules& vCurMods = GetModules();
const CModules& vNewMods = User.GetModules();
for (CModule* pNewMod : vNewMods) {
CString sModRet;
CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName());
if (!pCurMod) {
vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
CModInfo::UserModule, this, nullptr, sModRet);
} else if (pNewMod->GetArgs() != pCurMod->GetArgs()) {
vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
this, nullptr, sModRet);
}
}
for (CModule* pCurMod : vCurMods) {
CModule* pNewMod = vNewMods.FindModule(pCurMod->GetModName());
if (!pNewMod) {
ssUnloadMods.insert(pCurMod->GetModName());
}
}
for (const CString& sMod : ssUnloadMods) {
vCurMods.UnloadModule(sMod);
}
// !Modules
return true;
}
const set<CString>& CUser::GetAllowedHosts() const { return m_ssAllowedHosts; }
bool CUser::AddAllowedHost(const CString& sHostMask) {
if (sHostMask.empty() ||
m_ssAllowedHosts.find(sHostMask) != m_ssAllowedHosts.end()) {
return false;
}
m_ssAllowedHosts.insert(sHostMask);
return true;
}
bool CUser::RemAllowedHost(const CString& sHostMask) {
return m_ssAllowedHosts.erase(sHostMask) > 0;
}
void CUser::ClearAllowedHosts() { m_ssAllowedHosts.clear(); }
bool CUser::IsHostAllowed(const CString& sHost) const {
if (m_ssAllowedHosts.empty()) {
return true;
}
for (const CString& sAllowedHost : m_ssAllowedHosts) {
if (CUtils::CheckCIDR(sHost, sAllowedHost)) {
return true;
}
}
return false;
}
const CString& CUser::GetTimestampFormat() const { return m_sTimestampFormat; }
bool CUser::GetTimestampAppend() const { return m_bAppendTimestamp; }
bool CUser::GetTimestampPrepend() const { return m_bPrependTimestamp; }
bool CUser::IsValidUserName(const CString& sUserName) {
// /^[a-zA-Z][a-zA-Z@._\-]*$/
const char* p = sUserName.c_str();
if (sUserName.empty()) {
return false;
}
if ((*p < 'a' || *p > 'z') && (*p < 'A' || *p > 'Z')) {
return false;
}
while (*p) {
if (*p != '@' && *p != '.' && *p != '-' && *p != '_' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
bool CUser::IsValid(CString& sErrMsg, bool bSkipPass) const {
sErrMsg.clear();
if (!bSkipPass && m_sPass.empty()) {
sErrMsg = t_s("Password is empty");
return false;
}
if (m_sUserName.empty()) {
sErrMsg = t_s("Username is empty");
return false;
}
if (!CUser::IsValidUserName(m_sUserName)) {
sErrMsg = t_s("Username is invalid");
return false;
}
return true;
}
CConfig CUser::ToConfig() const {
CConfig config;
CConfig passConfig;
CString sHash;
switch (m_eHashType) {
case HASH_NONE:
sHash = "Plain";
break;
case HASH_MD5:
sHash = "MD5";
break;
case HASH_SHA256:
sHash = "SHA256";
break;
}
passConfig.AddKeyValuePair("Salt", m_sPassSalt);
passConfig.AddKeyValuePair("Method", sHash);
passConfig.AddKeyValuePair("Hash", GetPass());
config.AddSubConfig("Pass", "password", passConfig);
config.AddKeyValuePair("Nick", GetNick());
config.AddKeyValuePair("AltNick", GetAltNick());
config.AddKeyValuePair("Ident", GetIdent());
config.AddKeyValuePair("RealName", GetRealName());
config.AddKeyValuePair("BindHost", GetBindHost());
config.AddKeyValuePair("DCCBindHost", GetDCCBindHost());
config.AddKeyValuePair("QuitMsg", GetQuitMsg());
if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
config.AddKeyValuePair("StatusPrefix", GetStatusPrefix());
config.AddKeyValuePair("Skin", GetSkinName());
config.AddKeyValuePair("ChanModes", GetDefaultChanModes());
config.AddKeyValuePair("ChanBufferSize", CString(GetChanBufferSize()));
config.AddKeyValuePair("QueryBufferSize", CString(GetQueryBufferSize()));
config.AddKeyValuePair("AutoClearChanBuffer",
CString(AutoClearChanBuffer()));
config.AddKeyValuePair("AutoClearQueryBuffer",
CString(AutoClearQueryBuffer()));
config.AddKeyValuePair("MultiClients", CString(MultiClients()));
config.AddKeyValuePair("DenyLoadMod", CString(DenyLoadMod()));
config.AddKeyValuePair("Admin", CString(IsAdmin()));
config.AddKeyValuePair("DenySetBindHost", CString(DenySetBindHost()));
config.AddKeyValuePair("TimestampFormat", GetTimestampFormat());
config.AddKeyValuePair("AppendTimestamp", CString(GetTimestampAppend()));
config.AddKeyValuePair("PrependTimestamp", CString(GetTimestampPrepend()));
config.AddKeyValuePair("AuthOnlyViaModule", CString(AuthOnlyViaModule()));
config.AddKeyValuePair("Timezone", m_sTimezone);
config.AddKeyValuePair("JoinTries", CString(m_uMaxJoinTries));
config.AddKeyValuePair("MaxNetworks", CString(m_uMaxNetworks));
config.AddKeyValuePair("MaxQueryBuffers", CString(m_uMaxQueryBuffers));
config.AddKeyValuePair("MaxJoins", CString(m_uMaxJoins));
config.AddKeyValuePair("ClientEncoding", GetClientEncoding());
config.AddKeyValuePair("Language", GetLanguage());
config.AddKeyValuePair("NoTrafficTimeout", CString(GetNoTrafficTimeout()));
// Allow Hosts
if (!m_ssAllowedHosts.empty()) {
for (const CString& sHost : m_ssAllowedHosts) {
config.AddKeyValuePair("Allow", sHost);
}
}
// CTCP Replies
if (!m_mssCTCPReplies.empty()) {
for (const auto& itb : m_mssCTCPReplies) {
config.AddKeyValuePair("CTCPReply",
itb.first.AsUpper() + " " + itb.second);
}
}
// Modules
const CModules& Mods = GetModules();
if (!Mods.empty()) {
for (CModule* pMod : Mods) {
CString sArgs = pMod->GetArgs();
if (!sArgs.empty()) {
sArgs = " " + sArgs;
}
config.AddKeyValuePair("LoadModule", pMod->GetModName() + sArgs);
}
}
// Networks
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
config.AddSubConfig("Network", pNetwork->GetName(),
pNetwork->ToConfig());
}
return config;
}
bool CUser::CheckPass(const CString& sPass) const {
if(AuthOnlyViaModule() || CZNC::Get().GetAuthOnlyViaModule()) {
return false;
}
switch (m_eHashType) {
case HASH_MD5:
return m_sPass.Equals(CUtils::SaltedMD5Hash(sPass, m_sPassSalt));
case HASH_SHA256:
return m_sPass.Equals(CUtils::SaltedSHA256Hash(sPass, m_sPassSalt));
case HASH_NONE:
default:
return (sPass == m_sPass);
}
}
/*CClient* CUser::GetClient() {
// Todo: optimize this by saving a pointer to the sock
CSockManager& Manager = CZNC::Get().GetManager();
CString sSockName = "USR::" + m_sUserName;
for (unsigned int a = 0; a < Manager.size(); a++) {
Csock* pSock = Manager[a];
if (pSock->GetSockName().Equals(sSockName)) {
if (!pSock->IsClosed()) {
return (CClient*) pSock;
}
}
}
return (CClient*) CZNC::Get().GetManager().FindSockByName(sSockName);
}*/
CString CUser::GetLocalDCCIP() const {
if (!GetDCCBindHost().empty()) return GetDCCBindHost();
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
CIRCSock* pIRCSock = pNetwork->GetIRCSock();
if (pIRCSock) {
return pIRCSock->GetLocalIP();
}
}
if (!GetAllClients().empty()) {
return GetAllClients()[0]->GetLocalIP();
}
return "";
}
bool CUser::PutUser(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutClient(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutAllUser(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
PutUser(sLine, pClient, pSkipClient);
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (pNetwork->PutUser(sLine, pClient, pSkipClient)) {
return true;
}
}
return (pClient == nullptr);
}
bool CUser::PutStatus(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
vector<CClient*> vClients = GetAllClients();
for (CClient* pEachClient : vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutStatus(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutStatusNotice(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
vector<CClient*> vClients = GetAllClients();
for (CClient* pEachClient : vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutStatusNotice(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutModule(const CString& sModule, const CString& sLine,
CClient* pClient, CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutModule(sModule, sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutModNotice(const CString& sModule, const CString& sLine,
CClient* pClient, CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutModNotice(sModule, sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
CString CUser::MakeCleanUserName(const CString& sUserName) {
return sUserName.Token(0, false, "@").Replace_n(".", "");
}
bool CUser::IsUserAttached() const {
if (!m_vClients.empty()) {
return true;
}
for (const CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (pNetwork->IsUserAttached()) {
return true;
}
}
return false;
}
bool CUser::LoadModule(const CString& sModName, const CString& sArgs,
const CString& sNotice, CString& sError) {
bool bModRet = true;
CString sModRet;
CModInfo ModInfo;
if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sModName, sModRet)) {
sError = t_f("Unable to find modinfo {1}: {2}")(sModName, sModRet);
return false;
}
CUtils::PrintAction(sNotice);
if (!ModInfo.SupportsType(CModInfo::UserModule) &&
ModInfo.SupportsType(CModInfo::NetworkModule)) {
CUtils::PrintMessage(
"NOTICE: Module [" + sModName +
"] is a network module, loading module for all networks in user.");
// Do they have old NV?
CFile fNVFile =
CFile(GetUserPath() + "/moddata/" + sModName + "/.registry");
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
// Check whether the network already has this module loaded (#954)
if (pNetwork->GetModules().FindModule(sModName)) {
continue;
}
if (fNVFile.Exists()) {
CString sNetworkModPath =
pNetwork->GetNetworkPath() + "/moddata/" + sModName;
if (!CFile::Exists(sNetworkModPath)) {
CDir::MakeDir(sNetworkModPath);
}
fNVFile.Copy(sNetworkModPath + "/.registry");
}
bModRet = pNetwork->GetModules().LoadModule(
sModName, sArgs, CModInfo::NetworkModule, this, pNetwork,
sModRet);
if (!bModRet) {
break;
}
}
} else {
bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule,
this, nullptr, sModRet);
}
if (!bModRet) {
sError = sModRet;
}
return bModRet;
}
// Setters
void CUser::SetNick(const CString& s) { m_sNick = s; }
void CUser::SetAltNick(const CString& s) { m_sAltNick = s; }
void CUser::SetIdent(const CString& s) { m_sIdent = s; }
void CUser::SetRealName(const CString& s) { m_sRealName = s; }
void CUser::SetBindHost(const CString& s) { m_sBindHost = s; }
void CUser::SetDCCBindHost(const CString& s) { m_sDCCBindHost = s; }
void CUser::SetPass(const CString& s, eHashType eHash, const CString& sSalt) {
m_sPass = s;
m_eHashType = eHash;
m_sPassSalt = sSalt;
}
void CUser::SetMultiClients(bool b) { m_bMultiClients = b; }
void CUser::SetDenyLoadMod(bool b) { m_bDenyLoadMod = b; }
void CUser::SetAdmin(bool b) { m_bAdmin = b; }
void CUser::SetDenySetBindHost(bool b) { m_bDenySetBindHost = b; }
void CUser::SetDefaultChanModes(const CString& s) { m_sDefaultChanModes = s; }
void CUser::SetClientEncoding(const CString& s) {
m_sClientEncoding = CZNC::Get().FixupEncoding(s);
for (CClient* pClient : GetAllClients()) {
pClient->SetEncoding(m_sClientEncoding);
}
}
void CUser::SetQuitMsg(const CString& s) { m_sQuitMsg = s; }
void CUser::SetAutoClearChanBuffer(bool b) {
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CChan* pChan : pNetwork->GetChans()) {
pChan->InheritAutoClearChanBuffer(b);
}
}
m_bAutoClearChanBuffer = b;
}
void CUser::SetAutoClearQueryBuffer(bool b) { m_bAutoClearQueryBuffer = b; }
bool CUser::SetBufferCount(unsigned int u, bool bForce) {
return SetChanBufferSize(u, bForce);
}
bool CUser::SetChanBufferSize(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) return false;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CChan* pChan : pNetwork->GetChans()) {
pChan->InheritBufferCount(u, bForce);
}
}
m_uChanBufferSize = u;
return true;
}
bool CUser::SetQueryBufferSize(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) return false;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CQuery* pQuery : pNetwork->GetQueries()) {
pQuery->SetBufferCount(u, bForce);
}
}
m_uQueryBufferSize = u;
return true;
}
bool CUser::AddCTCPReply(const CString& sCTCP, const CString& sReply) {
// Reject CTCP requests containing spaces
if (sCTCP.find_first_of(' ') != CString::npos) {
return false;
}
// Reject empty CTCP requests
if (sCTCP.empty()) {
return false;
}
m_mssCTCPReplies[sCTCP.AsUpper()] = sReply;
return true;
}
bool CUser::DelCTCPReply(const CString& sCTCP) {
return m_mssCTCPReplies.erase(sCTCP.AsUpper()) > 0;
}
bool CUser::SetStatusPrefix(const CString& s) {
if ((!s.empty()) && (s.length() < 6) && (!s.Contains(" "))) {
m_sStatusPrefix = (s.empty()) ? "*" : s;
return true;
}
return false;
}
bool CUser::SetLanguage(const CString& s) {
// They look like ru-RU
for (char c : s) {
if (isalpha(c) || c == '-' || c == '_') {
} else {
return false;
}
}
m_sLanguage = s;
// 1.7.0 accidentally used _ instead of -, which made language
// non-selectable. But it's possible that someone put _ to znc.conf
// manually.
// TODO: cleanup _ some time later.
m_sLanguage.Replace("_", "-");
return true;
}
// !Setters
// Getters
vector<CClient*> CUser::GetAllClients() const {
vector<CClient*> vClients;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CClient* pClient : pNetwork->GetClients()) {
vClients.push_back(pClient);
}
}
for (CClient* pClient : m_vClients) {
vClients.push_back(pClient);
}
return vClients;
}
const CString& CUser::GetUserName() const { return m_sUserName; }
const CString& CUser::GetCleanUserName() const { return m_sCleanUserName; }
const CString& CUser::GetNick(bool bAllowDefault) const {
return (bAllowDefault && m_sNick.empty()) ? GetCleanUserName() : m_sNick;
}
const CString& CUser::GetAltNick(bool bAllowDefault) const {
return (bAllowDefault && m_sAltNick.empty()) ? GetCleanUserName()
: m_sAltNick;
}
const CString& CUser::GetIdent(bool bAllowDefault) const {
return (bAllowDefault && m_sIdent.empty()) ? GetCleanUserName() : m_sIdent;
}
CString CUser::GetRealName() const {
// Not include version number via GetTag() because of
// https://github.com/znc/znc/issues/818#issuecomment-70402820
return (!m_sRealName.Trim_n().empty()) ? m_sRealName
: "ZNC - https://znc.in";
}
const CString& CUser::GetBindHost() const { return m_sBindHost; }
const CString& CUser::GetDCCBindHost() const { return m_sDCCBindHost; }
const CString& CUser::GetPass() const { return m_sPass; }
CUser::eHashType CUser::GetPassHashType() const { return m_eHashType; }
const CString& CUser::GetPassSalt() const { return m_sPassSalt; }
bool CUser::DenyLoadMod() const { return m_bDenyLoadMod; }
bool CUser::IsAdmin() const { return m_bAdmin; }
bool CUser::DenySetBindHost() const { return m_bDenySetBindHost; }
bool CUser::MultiClients() const { return m_bMultiClients; }
bool CUser::AuthOnlyViaModule() const { return m_bAuthOnlyViaModule; }
const CString& CUser::GetStatusPrefix() const { return m_sStatusPrefix; }
const CString& CUser::GetDefaultChanModes() const {
return m_sDefaultChanModes;
}
const CString& CUser::GetClientEncoding() const { return m_sClientEncoding; }
bool CUser::HasSpaceForNewNetwork() const {
return GetNetworks().size() < MaxNetworks();
}
CString CUser::GetQuitMsg() const {
return (!m_sQuitMsg.Trim_n().empty()) ? m_sQuitMsg : "%znc%";
}
const MCString& CUser::GetCTCPReplies() const { return m_mssCTCPReplies; }
unsigned int CUser::GetBufferCount() const { return GetChanBufferSize(); }
unsigned int CUser::GetChanBufferSize() const { return m_uChanBufferSize; }
unsigned int CUser::GetQueryBufferSize() const { return m_uQueryBufferSize; }
bool CUser::AutoClearChanBuffer() const { return m_bAutoClearChanBuffer; }
bool CUser::AutoClearQueryBuffer() const { return m_bAutoClearQueryBuffer; }
// CString CUser::GetSkinName() const { return (!m_sSkinName.empty()) ?
// m_sSkinName : CZNC::Get().GetSkinName(); }
CString CUser::GetSkinName() const { return m_sSkinName; }
CString CUser::GetLanguage() const { return m_sLanguage; }
const CString& CUser::GetUserPath() const {
if (!CFile::Exists(m_sUserPath)) {
CDir::MakeDir(m_sUserPath);
}
return m_sUserPath;
}
// !Getters
unsigned long long CUser::BytesRead() const {
unsigned long long uBytes = m_uBytesRead;
for (const CIRCNetwork* pNetwork : m_vIRCNetworks) {
uBytes += pNetwork->BytesRead();
}
return uBytes;
}
unsigned long long CUser::BytesWritten() const {
unsigned long long uBytes = m_uBytesWritten;
for (const CIRCNetwork* pNetwork : m_vIRCNetworks) {
uBytes += pNetwork->BytesWritten();
}
return uBytes;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1442_2 |
crossvul-cpp_data_good_3220_0 | /*
Audio File Library
Copyright (C) 1998-2000, 2003-2004, 2010-2013, Michael Pruett <michael@68k.org>
Copyright (C) 2000-2002, Silicon Graphics, Inc.
Copyright (C) 2002-2003, Davy Durham
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301 USA
*/
/*
WAVE.cpp
This file contains code for reading and writing RIFF WAVE format
sound files.
*/
#include "config.h"
#include "WAVE.h"
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "File.h"
#include "Instrument.h"
#include "Marker.h"
#include "Setup.h"
#include "Tag.h"
#include "Track.h"
#include "UUID.h"
#include "byteorder.h"
#include "util.h"
/* These constants are from RFC 2361. */
enum
{
WAVE_FORMAT_UNKNOWN = 0x0000, /* Microsoft Unknown Wave Format */
WAVE_FORMAT_PCM = 0x0001, /* Microsoft PCM Format */
WAVE_FORMAT_ADPCM = 0x0002, /* Microsoft ADPCM Format */
WAVE_FORMAT_IEEE_FLOAT = 0x0003, /* IEEE Float */
WAVE_FORMAT_VSELP = 0x0004, /* Compaq Computer's VSELP */
WAVE_FORMAT_IBM_CVSD = 0x0005, /* IBM CVSD */
WAVE_FORMAT_ALAW = 0x0006, /* Microsoft ALAW */
WAVE_FORMAT_MULAW = 0x0007, /* Microsoft MULAW */
WAVE_FORMAT_OKI_ADPCM = 0x0010, /* OKI ADPCM */
WAVE_FORMAT_DVI_ADPCM = 0x0011, /* Intel's DVI ADPCM */
WAVE_FORMAT_MEDIASPACE_ADPCM = 0x0012, /* Videologic's MediaSpace ADPCM */
WAVE_FORMAT_SIERRA_ADPCM = 0x0013, /* Sierra ADPCM */
WAVE_FORMAT_G723_ADPCM = 0x0014, /* G.723 ADPCM */
WAVE_FORMAT_DIGISTD = 0x0015, /* DSP Solutions' DIGISTD */
WAVE_FORMAT_DIGIFIX = 0x0016, /* DSP Solutions' DIGIFIX */
WAVE_FORMAT_DIALOGIC_OKI_ADPCM = 0x0017, /* Dialogic OKI ADPCM */
WAVE_FORMAT_MEDIAVISION_ADPCM = 0x0018, /* MediaVision ADPCM */
WAVE_FORMAT_CU_CODEC = 0x0019, /* HP CU */
WAVE_FORMAT_YAMAHA_ADPCM = 0x0020, /* Yamaha ADPCM */
WAVE_FORMAT_SONARC = 0x0021, /* Speech Compression's Sonarc */
WAVE_FORMAT_DSP_TRUESPEECH = 0x0022, /* DSP Group's True Speech */
WAVE_FORMAT_ECHOSC1 = 0x0023, /* Echo Speech's EchoSC1 */
WAVE_FORMAT_AUDIOFILE_AF36 = 0x0024, /* Audiofile AF36 */
WAVE_FORMAT_APTX = 0x0025, /* APTX */
WAVE_FORMAT_DOLBY_AC2 = 0x0030, /* Dolby AC2 */
WAVE_FORMAT_GSM610 = 0x0031, /* GSM610 */
WAVE_FORMAT_MSNAUDIO = 0x0032, /* MSNAudio */
WAVE_FORMAT_ANTEX_ADPCME = 0x0033, /* Antex ADPCME */
WAVE_FORMAT_MPEG = 0x0050, /* MPEG */
WAVE_FORMAT_MPEGLAYER3 = 0x0055, /* MPEG layer 3 */
WAVE_FORMAT_LUCENT_G723 = 0x0059, /* Lucent G.723 */
WAVE_FORMAT_G726_ADPCM = 0x0064, /* G.726 ADPCM */
WAVE_FORMAT_G722_ADPCM = 0x0065, /* G.722 ADPCM */
IBM_FORMAT_MULAW = 0x0101,
IBM_FORMAT_ALAW = 0x0102,
IBM_FORMAT_ADPCM = 0x0103,
WAVE_FORMAT_CREATIVE_ADPCM = 0x0200,
WAVE_FORMAT_EXTENSIBLE = 0xfffe
};
const int _af_wave_compression_types[_AF_WAVE_NUM_COMPTYPES] =
{
AF_COMPRESSION_G711_ULAW,
AF_COMPRESSION_G711_ALAW,
AF_COMPRESSION_IMA,
AF_COMPRESSION_MS_ADPCM
};
const InstParamInfo _af_wave_inst_params[_AF_WAVE_NUM_INSTPARAMS] =
{
{ AF_INST_MIDI_BASENOTE, AU_PVTYPE_LONG, "MIDI base note", {60} },
{ AF_INST_NUMCENTS_DETUNE, AU_PVTYPE_LONG, "Detune in cents", {0} },
{ AF_INST_MIDI_LOVELOCITY, AU_PVTYPE_LONG, "Low velocity", {1} },
{ AF_INST_MIDI_HIVELOCITY, AU_PVTYPE_LONG, "High velocity", {127} },
{ AF_INST_MIDI_LONOTE, AU_PVTYPE_LONG, "Low note", {0} },
{ AF_INST_MIDI_HINOTE, AU_PVTYPE_LONG, "High note", {127} },
{ AF_INST_NUMDBS_GAIN, AU_PVTYPE_LONG, "Gain in dB", {0} }
};
static const _AFfilesetup waveDefaultFileSetup =
{
_AF_VALID_FILESETUP, /* valid */
AF_FILE_WAVE, /* fileFormat */
true, /* trackSet */
true, /* instrumentSet */
true, /* miscellaneousSet */
1, /* trackCount */
NULL, /* tracks */
0, /* instrumentCount */
NULL, /* instruments */
0, /* miscellaneousCount */
NULL /* miscellaneous */
};
static const UUID _af_wave_guid_pcm =
{{
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
}};
static const UUID _af_wave_guid_ieee_float =
{{
0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
}};
static const UUID _af_wave_guid_ulaw =
{{
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
}};
static const UUID _af_wave_guid_alaw =
{{
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
}};
WAVEFile::WAVEFile()
{
setFormatByteOrder(AF_BYTEORDER_LITTLEENDIAN);
m_factOffset = 0;
m_miscellaneousOffset = 0;
m_markOffset = 0;
m_dataSizeOffset = 0;
m_msadpcmNumCoefficients = 0;
}
status WAVEFile::parseFrameCount(const Tag &id, uint32_t size)
{
Track *track = getTrack();
uint32_t totalFrames;
readU32(&totalFrames);
track->totalfframes = totalFrames;
return AF_SUCCEED;
}
status WAVEFile::parseFormat(const Tag &id, uint32_t size)
{
Track *track = getTrack();
uint16_t formatTag;
readU16(&formatTag);
uint16_t channelCount;
readU16(&channelCount);
uint32_t sampleRate;
readU32(&sampleRate);
uint32_t averageBytesPerSecond;
readU32(&averageBytesPerSecond);
uint16_t blockAlign;
readU16(&blockAlign);
if (!channelCount)
{
_af_error(AF_BAD_CHANNELS, "invalid file with 0 channels");
return AF_FAIL;
}
track->f.channelCount = channelCount;
track->f.sampleRate = sampleRate;
track->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN;
/* Default to uncompressed audio data. */
track->f.compressionType = AF_COMPRESSION_NONE;
track->f.framesPerPacket = 1;
switch (formatTag)
{
case WAVE_FORMAT_PCM:
{
uint16_t bitsPerSample;
readU16(&bitsPerSample);
track->f.sampleWidth = bitsPerSample;
if (bitsPerSample == 0 || bitsPerSample > 32)
{
_af_error(AF_BAD_WIDTH,
"bad sample width of %d bits",
bitsPerSample);
return AF_FAIL;
}
if (bitsPerSample <= 8)
track->f.sampleFormat = AF_SAMPFMT_UNSIGNED;
else
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
}
break;
case WAVE_FORMAT_MULAW:
case IBM_FORMAT_MULAW:
track->f.sampleWidth = 16;
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
track->f.byteOrder = _AF_BYTEORDER_NATIVE;
track->f.compressionType = AF_COMPRESSION_G711_ULAW;
track->f.bytesPerPacket = track->f.channelCount;
break;
case WAVE_FORMAT_ALAW:
case IBM_FORMAT_ALAW:
track->f.sampleWidth = 16;
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
track->f.byteOrder = _AF_BYTEORDER_NATIVE;
track->f.compressionType = AF_COMPRESSION_G711_ALAW;
track->f.bytesPerPacket = track->f.channelCount;
break;
case WAVE_FORMAT_IEEE_FLOAT:
{
uint16_t bitsPerSample;
readU16(&bitsPerSample);
if (bitsPerSample == 64)
{
track->f.sampleWidth = 64;
track->f.sampleFormat = AF_SAMPFMT_DOUBLE;
}
else
{
track->f.sampleWidth = 32;
track->f.sampleFormat = AF_SAMPFMT_FLOAT;
}
}
break;
case WAVE_FORMAT_ADPCM:
{
uint16_t bitsPerSample, extraByteCount,
samplesPerBlock, numCoefficients;
if (track->f.channelCount != 1 &&
track->f.channelCount != 2)
{
_af_error(AF_BAD_CHANNELS,
"WAVE file with MS ADPCM compression "
"must have 1 or 2 channels");
}
readU16(&bitsPerSample);
readU16(&extraByteCount);
readU16(&samplesPerBlock);
readU16(&numCoefficients);
/* numCoefficients should be at least 7. */
assert(numCoefficients >= 7 && numCoefficients <= 255);
if (numCoefficients < 7 || numCoefficients > 255)
{
_af_error(AF_BAD_HEADER,
"Bad number of coefficients");
return AF_FAIL;
}
m_msadpcmNumCoefficients = numCoefficients;
for (int i=0; i<m_msadpcmNumCoefficients; i++)
{
readS16(&m_msadpcmCoefficients[i][0]);
readS16(&m_msadpcmCoefficients[i][1]);
}
track->f.sampleWidth = 16;
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
track->f.compressionType = AF_COMPRESSION_MS_ADPCM;
track->f.byteOrder = _AF_BYTEORDER_NATIVE;
track->f.framesPerPacket = samplesPerBlock;
track->f.bytesPerPacket = blockAlign;
// Create the parameter list.
AUpvlist pv = AUpvnew(2);
AUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS);
AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);
long l = m_msadpcmNumCoefficients;
AUpvsetval(pv, 0, &l);
AUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS);
AUpvsetvaltype(pv, 1, AU_PVTYPE_PTR);
void *v = m_msadpcmCoefficients;
AUpvsetval(pv, 1, &v);
track->f.compressionParams = pv;
}
break;
case WAVE_FORMAT_DVI_ADPCM:
{
uint16_t bitsPerSample, extraByteCount, samplesPerBlock;
readU16(&bitsPerSample);
readU16(&extraByteCount);
readU16(&samplesPerBlock);
if (bitsPerSample != 4)
{
_af_error(AF_BAD_NOT_IMPLEMENTED,
"IMA ADPCM compression supports only 4 bits per sample");
}
int bytesPerBlock = (samplesPerBlock + 14) / 8 * 4 * channelCount;
if (bytesPerBlock > blockAlign || (samplesPerBlock % 8) != 1)
{
_af_error(AF_BAD_CODEC_CONFIG,
"Invalid samples per block for IMA ADPCM compression");
}
track->f.sampleWidth = 16;
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
track->f.compressionType = AF_COMPRESSION_IMA;
track->f.byteOrder = _AF_BYTEORDER_NATIVE;
initIMACompressionParams();
track->f.framesPerPacket = samplesPerBlock;
track->f.bytesPerPacket = blockAlign;
}
break;
case WAVE_FORMAT_EXTENSIBLE:
{
uint16_t bitsPerSample;
readU16(&bitsPerSample);
uint16_t extraByteCount;
readU16(&extraByteCount);
uint16_t reserved;
readU16(&reserved);
uint32_t channelMask;
readU32(&channelMask);
UUID subformat;
readUUID(&subformat);
if (subformat == _af_wave_guid_pcm)
{
track->f.sampleWidth = bitsPerSample;
if (bitsPerSample == 0 || bitsPerSample > 32)
{
_af_error(AF_BAD_WIDTH,
"bad sample width of %d bits",
bitsPerSample);
return AF_FAIL;
}
// Use valid bits per sample if bytes per sample is the same.
if (reserved <= bitsPerSample &&
(reserved + 7) / 8 == (bitsPerSample + 7) / 8)
track->f.sampleWidth = reserved;
if (bitsPerSample <= 8)
track->f.sampleFormat = AF_SAMPFMT_UNSIGNED;
else
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
}
else if (subformat == _af_wave_guid_ieee_float)
{
if (bitsPerSample == 64)
{
track->f.sampleWidth = 64;
track->f.sampleFormat = AF_SAMPFMT_DOUBLE;
}
else
{
track->f.sampleWidth = 32;
track->f.sampleFormat = AF_SAMPFMT_FLOAT;
}
}
else if (subformat == _af_wave_guid_alaw ||
subformat == _af_wave_guid_ulaw)
{
track->f.compressionType = subformat == _af_wave_guid_alaw ?
AF_COMPRESSION_G711_ALAW : AF_COMPRESSION_G711_ULAW;
track->f.sampleWidth = 16;
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
track->f.byteOrder = _AF_BYTEORDER_NATIVE;
track->f.bytesPerPacket = channelCount;
}
else
{
_af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE extensible data format %s is not currently supported", subformat.name().c_str());
return AF_FAIL;
}
}
break;
case WAVE_FORMAT_YAMAHA_ADPCM:
case WAVE_FORMAT_OKI_ADPCM:
case WAVE_FORMAT_CREATIVE_ADPCM:
case IBM_FORMAT_ADPCM:
_af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE ADPCM data format 0x%x is not currently supported", formatTag);
return AF_FAIL;
break;
case WAVE_FORMAT_MPEG:
_af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG data format is not supported");
return AF_FAIL;
break;
case WAVE_FORMAT_MPEGLAYER3:
_af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG layer 3 data format is not supported");
return AF_FAIL;
break;
default:
_af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE file data format 0x%x not currently supported != 0xfffe ? %d, != EXTENSIBLE? %d", formatTag, formatTag != 0xfffe, formatTag != WAVE_FORMAT_EXTENSIBLE);
return AF_FAIL;
break;
}
if (track->f.isUncompressed())
track->f.computeBytesPerPacketPCM();
_af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth);
return AF_SUCCEED;
}
status WAVEFile::parseData(const Tag &id, uint32_t size)
{
Track *track = getTrack();
track->fpos_first_frame = m_fh->tell();
track->data_size = size;
return AF_SUCCEED;
}
status WAVEFile::parsePlayList(const Tag &id, uint32_t size)
{
uint32_t segmentCount;
readU32(&segmentCount);
if (segmentCount == 0)
{
m_instrumentCount = 0;
m_instruments = NULL;
return AF_SUCCEED;
}
for (unsigned segment=0; segment<segmentCount; segment++)
{
uint32_t startMarkID, loopLength, loopCount;
readU32(&startMarkID);
readU32(&loopLength);
readU32(&loopCount);
}
return AF_SUCCEED;
}
status WAVEFile::parseCues(const Tag &id, uint32_t size)
{
Track *track = getTrack();
uint32_t markerCount;
readU32(&markerCount);
track->markerCount = markerCount;
if (markerCount == 0)
{
track->markers = NULL;
return AF_SUCCEED;
}
if ((track->markers = _af_marker_new(markerCount)) == NULL)
return AF_FAIL;
for (unsigned i=0; i<markerCount; i++)
{
uint32_t id, position, chunkid;
uint32_t chunkByteOffset, blockByteOffset;
uint32_t sampleFrameOffset;
Marker *marker = &track->markers[i];
readU32(&id);
readU32(&position);
readU32(&chunkid);
readU32(&chunkByteOffset);
readU32(&blockByteOffset);
/*
sampleFrameOffset represents the position of
the mark in units of frames.
*/
readU32(&sampleFrameOffset);
marker->id = id;
marker->position = sampleFrameOffset;
marker->name = _af_strdup("");
marker->comment = _af_strdup("");
}
return AF_SUCCEED;
}
/* Parse an adtl sub-chunk within a LIST chunk. */
status WAVEFile::parseADTLSubChunk(const Tag &id, uint32_t size)
{
Track *track = getTrack();
AFfileoffset endPos = m_fh->tell() + size;
while (m_fh->tell() < endPos)
{
Tag chunkID;
uint32_t chunkSize;
readTag(&chunkID);
readU32(&chunkSize);
if (chunkID == "labl" || chunkID == "note")
{
uint32_t id;
long length=chunkSize-4;
char *p = (char *) _af_malloc(length);
readU32(&id);
m_fh->read(p, length);
Marker *marker = track->getMarker(id);
if (marker)
{
if (chunkID == "labl")
{
free(marker->name);
marker->name = p;
}
else if (chunkID == "note")
{
free(marker->comment);
marker->comment = p;
}
else
free(p);
}
else
free(p);
/*
If chunkSize is odd, skip an extra byte
at the end of the chunk.
*/
if ((chunkSize % 2) != 0)
m_fh->seek(1, File::SeekFromCurrent);
}
else
{
/* If chunkSize is odd, skip an extra byte. */
m_fh->seek(chunkSize + (chunkSize % 2), File::SeekFromCurrent);
}
}
return AF_SUCCEED;
}
/* Parse an INFO sub-chunk within a LIST chunk. */
status WAVEFile::parseINFOSubChunk(const Tag &id, uint32_t size)
{
AFfileoffset endPos = m_fh->tell() + size;
while (m_fh->tell() < endPos)
{
int misctype = AF_MISC_UNRECOGNIZED;
Tag miscid;
uint32_t miscsize;
readTag(&miscid);
readU32(&miscsize);
if (miscid == "IART")
misctype = AF_MISC_AUTH;
else if (miscid == "INAM")
misctype = AF_MISC_NAME;
else if (miscid == "ICOP")
misctype = AF_MISC_COPY;
else if (miscid == "ICMT")
misctype = AF_MISC_ICMT;
else if (miscid == "ICRD")
misctype = AF_MISC_ICRD;
else if (miscid == "ISFT")
misctype = AF_MISC_ISFT;
if (misctype != AF_MISC_UNRECOGNIZED)
{
char *string = (char *) _af_malloc(miscsize);
m_fh->read(string, miscsize);
m_miscellaneousCount++;
m_miscellaneous = (Miscellaneous *) _af_realloc(m_miscellaneous, sizeof (Miscellaneous) * m_miscellaneousCount);
m_miscellaneous[m_miscellaneousCount-1].id = m_miscellaneousCount;
m_miscellaneous[m_miscellaneousCount-1].type = misctype;
m_miscellaneous[m_miscellaneousCount-1].size = miscsize;
m_miscellaneous[m_miscellaneousCount-1].position = 0;
m_miscellaneous[m_miscellaneousCount-1].buffer = string;
}
else
{
m_fh->seek(miscsize, File::SeekFromCurrent);
}
/* Make the current position an even number of bytes. */
if (miscsize % 2 != 0)
m_fh->seek(1, File::SeekFromCurrent);
}
return AF_SUCCEED;
}
status WAVEFile::parseList(const Tag &id, uint32_t size)
{
Tag typeID;
readTag(&typeID);
size-=4;
if (typeID == "adtl")
{
/* Handle adtl sub-chunks. */
return parseADTLSubChunk(typeID, size);
}
else if (typeID == "INFO")
{
/* Handle INFO sub-chunks. */
return parseINFOSubChunk(typeID, size);
}
else
{
/* Skip unhandled sub-chunks. */
m_fh->seek(size, File::SeekFromCurrent);
return AF_SUCCEED;
}
return AF_SUCCEED;
}
status WAVEFile::parseInstrument(const Tag &id, uint32_t size)
{
uint8_t baseNote;
int8_t detune, gain;
uint8_t lowNote, highNote, lowVelocity, highVelocity;
uint8_t padByte;
readU8(&baseNote);
readS8(&detune);
readS8(&gain);
readU8(&lowNote);
readU8(&highNote);
readU8(&lowVelocity);
readU8(&highVelocity);
readU8(&padByte);
return AF_SUCCEED;
}
bool WAVEFile::recognize(File *fh)
{
uint8_t buffer[8];
fh->seek(0, File::SeekFromBeginning);
if (fh->read(buffer, 8) != 8 || memcmp(buffer, "RIFF", 4) != 0)
return false;
if (fh->read(buffer, 4) != 4 || memcmp(buffer, "WAVE", 4) != 0)
return false;
return true;
}
status WAVEFile::readInit(AFfilesetup setup)
{
Tag type, formtype;
uint32_t size;
uint32_t index = 0;
bool hasFormat = false;
bool hasData = false;
bool hasFrameCount = false;
Track *track = allocateTrack();
m_fh->seek(0, File::SeekFromBeginning);
readTag(&type);
readU32(&size);
readTag(&formtype);
assert(type == "RIFF");
assert(formtype == "WAVE");
/* Include the offset of the form type. */
index += 4;
while (index < size)
{
Tag chunkid;
uint32_t chunksize = 0;
status result;
readTag(&chunkid);
readU32(&chunksize);
if (chunkid == "fmt ")
{
result = parseFormat(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
hasFormat = true;
}
else if (chunkid == "data")
{
/* The format chunk must precede the data chunk. */
if (!hasFormat)
{
_af_error(AF_BAD_HEADER, "missing format chunk in WAVE file");
return AF_FAIL;
}
result = parseData(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
hasData = true;
}
else if (chunkid == "inst")
{
result = parseInstrument(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
}
else if (chunkid == "fact")
{
hasFrameCount = true;
result = parseFrameCount(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
}
else if (chunkid == "cue ")
{
result = parseCues(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
}
else if (chunkid == "LIST" || chunkid == "list")
{
result = parseList(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
}
else if (chunkid == "INST")
{
result = parseInstrument(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
}
else if (chunkid == "plst")
{
result = parsePlayList(chunkid, chunksize);
if (result == AF_FAIL)
return AF_FAIL;
}
index += chunksize + 8;
/* All chunks must be aligned on an even number of bytes */
if ((index % 2) != 0)
index++;
m_fh->seek(index + 8, File::SeekFromBeginning);
}
/* The format chunk and the data chunk are required. */
if (!hasFormat || !hasData)
{
return AF_FAIL;
}
/*
At this point we know that the file has a format chunk and a
data chunk, so we can assume that track->f and track->data_size
have been initialized.
*/
if (!hasFrameCount)
{
if (track->f.bytesPerPacket && track->f.framesPerPacket)
{
track->computeTotalFileFrames();
}
else
{
_af_error(AF_BAD_HEADER, "Frame count required but not found");
return AF_FAIL;
}
}
return AF_SUCCEED;
}
AFfilesetup WAVEFile::completeSetup(AFfilesetup setup)
{
if (setup->trackSet && setup->trackCount != 1)
{
_af_error(AF_BAD_NUMTRACKS, "WAVE file must have 1 track");
return AF_NULL_FILESETUP;
}
TrackSetup *track = setup->getTrack();
if (!track)
return AF_NULL_FILESETUP;
if (track->f.isCompressed())
{
if (!track->sampleFormatSet)
_af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, 16);
else
_af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth);
}
else if (track->sampleFormatSet)
{
switch (track->f.sampleFormat)
{
case AF_SAMPFMT_FLOAT:
if (track->sampleWidthSet &&
track->f.sampleWidth != 32)
{
_af_error(AF_BAD_WIDTH,
"Warning: invalid sample width for floating-point WAVE file: %d (must be 32 bits)\n",
track->f.sampleWidth);
_af_set_sample_format(&track->f, AF_SAMPFMT_FLOAT, 32);
}
break;
case AF_SAMPFMT_DOUBLE:
if (track->sampleWidthSet &&
track->f.sampleWidth != 64)
{
_af_error(AF_BAD_WIDTH,
"Warning: invalid sample width for double-precision floating-point WAVE file: %d (must be 64 bits)\n",
track->f.sampleWidth);
_af_set_sample_format(&track->f, AF_SAMPFMT_DOUBLE, 64);
}
break;
case AF_SAMPFMT_UNSIGNED:
if (track->sampleWidthSet)
{
if (track->f.sampleWidth < 1 || track->f.sampleWidth > 32)
{
_af_error(AF_BAD_WIDTH, "invalid sample width for WAVE file: %d (must be 1-32 bits)\n", track->f.sampleWidth);
return AF_NULL_FILESETUP;
}
if (track->f.sampleWidth > 8)
{
_af_error(AF_BAD_SAMPFMT, "WAVE integer data of more than 8 bits must be two's complement signed");
_af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, track->f.sampleWidth);
}
}
else
/*
If the sample width is not set but the user requests
unsigned data, set the width to 8 bits.
*/
_af_set_sample_format(&track->f, track->f.sampleFormat, 8);
break;
case AF_SAMPFMT_TWOSCOMP:
if (track->sampleWidthSet)
{
if (track->f.sampleWidth < 1 || track->f.sampleWidth > 32)
{
_af_error(AF_BAD_WIDTH, "invalid sample width %d for WAVE file (must be 1-32)", track->f.sampleWidth);
return AF_NULL_FILESETUP;
}
else if (track->f.sampleWidth <= 8)
{
_af_error(AF_BAD_SAMPFMT, "Warning: WAVE format integer data of 1-8 bits must be unsigned; setting sample format to unsigned");
_af_set_sample_format(&track->f, AF_SAMPFMT_UNSIGNED, track->f.sampleWidth);
}
}
else
/*
If no sample width was specified, we default to 16 bits
for signed integer data.
*/
_af_set_sample_format(&track->f, track->f.sampleFormat, 16);
break;
}
}
/*
Otherwise set the sample format depending on the sample
width or set completely to default.
*/
else
{
if (!track->sampleWidthSet)
{
track->f.sampleWidth = 16;
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
}
else
{
if (track->f.sampleWidth < 1 || track->f.sampleWidth > 32)
{
_af_error(AF_BAD_WIDTH, "invalid sample width %d for WAVE file (must be 1-32)", track->f.sampleWidth);
return AF_NULL_FILESETUP;
}
else if (track->f.sampleWidth > 8)
/* Here track->f.sampleWidth is in {1..32}. */
track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
else
/* Here track->f.sampleWidth is in {1..8}. */
track->f.sampleFormat = AF_SAMPFMT_UNSIGNED;
}
}
if (track->f.compressionType != AF_COMPRESSION_NONE &&
track->f.compressionType != AF_COMPRESSION_G711_ULAW &&
track->f.compressionType != AF_COMPRESSION_G711_ALAW &&
track->f.compressionType != AF_COMPRESSION_IMA &&
track->f.compressionType != AF_COMPRESSION_MS_ADPCM)
{
_af_error(AF_BAD_NOT_IMPLEMENTED, "compression format not supported in WAVE format");
return AF_NULL_FILESETUP;
}
if (track->f.isUncompressed() &&
track->byteOrderSet &&
track->f.byteOrder != AF_BYTEORDER_LITTLEENDIAN &&
track->f.isByteOrderSignificant())
{
_af_error(AF_BAD_BYTEORDER, "WAVE format only supports little-endian data");
return AF_NULL_FILESETUP;
}
if (track->f.isUncompressed())
track->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN;
if (track->aesDataSet)
{
_af_error(AF_BAD_FILESETUP, "WAVE files cannot have AES data");
return AF_NULL_FILESETUP;
}
if (setup->instrumentSet)
{
if (setup->instrumentCount > 1)
{
_af_error(AF_BAD_NUMINSTS, "WAVE files can have 0 or 1 instrument");
return AF_NULL_FILESETUP;
}
else if (setup->instrumentCount == 1)
{
if (setup->instruments[0].loopSet &&
setup->instruments[0].loopCount > 0 &&
(!track->markersSet || track->markerCount == 0))
{
_af_error(AF_BAD_NUMMARKS, "WAVE files with loops must contain at least 1 marker");
return AF_NULL_FILESETUP;
}
}
}
/* Make sure the miscellaneous data is of an acceptable type. */
if (setup->miscellaneousSet)
{
for (int i=0; i<setup->miscellaneousCount; i++)
{
switch (setup->miscellaneous[i].type)
{
case AF_MISC_COPY:
case AF_MISC_AUTH:
case AF_MISC_NAME:
case AF_MISC_ICRD:
case AF_MISC_ISFT:
case AF_MISC_ICMT:
break;
default:
_af_error(AF_BAD_MISCTYPE, "illegal miscellaneous type [%d] for WAVE file", setup->miscellaneous[i].type);
return AF_NULL_FILESETUP;
}
}
}
/*
Allocate an AFfilesetup and make all the unset fields correct.
*/
AFfilesetup newsetup = _af_filesetup_copy(setup, &waveDefaultFileSetup, false);
/* Make sure we do not copy loops if they are not specified in setup. */
if (setup->instrumentSet && setup->instrumentCount > 0 &&
setup->instruments[0].loopSet)
{
free(newsetup->instruments[0].loops);
newsetup->instruments[0].loopCount = 0;
}
return newsetup;
}
bool WAVEFile::isInstrumentParameterValid(AUpvlist list, int i)
{
int param, type;
AUpvgetparam(list, i, ¶m);
AUpvgetvaltype(list, i, &type);
if (type != AU_PVTYPE_LONG)
return false;
long lval;
AUpvgetval(list, i, &lval);
switch (param)
{
case AF_INST_MIDI_BASENOTE:
return ((lval >= 0) && (lval <= 127));
case AF_INST_NUMCENTS_DETUNE:
return ((lval >= -50) && (lval <= 50));
case AF_INST_MIDI_LOVELOCITY:
return ((lval >= 1) && (lval <= 127));
case AF_INST_MIDI_HIVELOCITY:
return ((lval >= 1) && (lval <= 127));
case AF_INST_MIDI_LONOTE:
return ((lval >= 0) && (lval <= 127));
case AF_INST_MIDI_HINOTE:
return ((lval >= 0) && (lval <= 127));
case AF_INST_NUMDBS_GAIN:
return true;
default:
return false;
}
return true;
}
status WAVEFile::writeFormat()
{
uint16_t formatTag, channelCount;
uint32_t sampleRate, averageBytesPerSecond;
uint16_t blockAlign;
uint32_t chunkSize;
uint16_t bitsPerSample;
Track *track = getTrack();
m_fh->write("fmt ", 4);
switch (track->f.compressionType)
{
case AF_COMPRESSION_NONE:
chunkSize = 16;
if (track->f.sampleFormat == AF_SAMPFMT_FLOAT ||
track->f.sampleFormat == AF_SAMPFMT_DOUBLE)
{
formatTag = WAVE_FORMAT_IEEE_FLOAT;
}
else if (track->f.sampleFormat == AF_SAMPFMT_TWOSCOMP ||
track->f.sampleFormat == AF_SAMPFMT_UNSIGNED)
{
formatTag = WAVE_FORMAT_PCM;
}
else
{
_af_error(AF_BAD_COMPTYPE, "bad sample format");
return AF_FAIL;
}
blockAlign = _af_format_frame_size(&track->f, false);
bitsPerSample = 8 * _af_format_sample_size(&track->f, false);
break;
/*
G.711 compression uses eight bits per sample.
*/
case AF_COMPRESSION_G711_ULAW:
chunkSize = 18;
formatTag = IBM_FORMAT_MULAW;
blockAlign = track->f.channelCount;
bitsPerSample = 8;
break;
case AF_COMPRESSION_G711_ALAW:
chunkSize = 18;
formatTag = IBM_FORMAT_ALAW;
blockAlign = track->f.channelCount;
bitsPerSample = 8;
break;
case AF_COMPRESSION_IMA:
chunkSize = 20;
formatTag = WAVE_FORMAT_DVI_ADPCM;
blockAlign = track->f.bytesPerPacket;
bitsPerSample = 4;
break;
case AF_COMPRESSION_MS_ADPCM:
chunkSize = 50;
formatTag = WAVE_FORMAT_ADPCM;
blockAlign = track->f.bytesPerPacket;
bitsPerSample = 4;
break;
default:
_af_error(AF_BAD_COMPTYPE, "bad compression type");
return AF_FAIL;
}
writeU32(&chunkSize);
writeU16(&formatTag);
channelCount = track->f.channelCount;
writeU16(&channelCount);
sampleRate = track->f.sampleRate;
writeU32(&sampleRate);
averageBytesPerSecond =
track->f.sampleRate * _af_format_frame_size(&track->f, false);
if (track->f.compressionType == AF_COMPRESSION_IMA ||
track->f.compressionType == AF_COMPRESSION_MS_ADPCM)
averageBytesPerSecond = track->f.sampleRate * track->f.bytesPerPacket /
track->f.framesPerPacket;
writeU32(&averageBytesPerSecond);
writeU16(&blockAlign);
writeU16(&bitsPerSample);
if (track->f.compressionType == AF_COMPRESSION_G711_ULAW ||
track->f.compressionType == AF_COMPRESSION_G711_ALAW)
{
uint16_t zero = 0;
writeU16(&zero);
}
else if (track->f.compressionType == AF_COMPRESSION_IMA)
{
uint16_t extraByteCount = 2;
writeU16(&extraByteCount);
uint16_t samplesPerBlock = track->f.framesPerPacket;
writeU16(&samplesPerBlock);
}
else if (track->f.compressionType == AF_COMPRESSION_MS_ADPCM)
{
uint16_t extraByteCount = 2 + 2 + m_msadpcmNumCoefficients * 4;
writeU16(&extraByteCount);
uint16_t samplesPerBlock = track->f.framesPerPacket;
writeU16(&samplesPerBlock);
uint16_t numCoefficients = m_msadpcmNumCoefficients;
writeU16(&numCoefficients);
for (int i=0; i<m_msadpcmNumCoefficients; i++)
{
writeS16(&m_msadpcmCoefficients[i][0]);
writeS16(&m_msadpcmCoefficients[i][1]);
}
}
return AF_SUCCEED;
}
status WAVEFile::writeFrameCount()
{
uint32_t factSize = 4;
uint32_t totalFrameCount;
Track *track = getTrack();
/* Omit the fact chunk only for uncompressed integer audio formats. */
if (track->f.compressionType == AF_COMPRESSION_NONE &&
(track->f.sampleFormat == AF_SAMPFMT_TWOSCOMP ||
track->f.sampleFormat == AF_SAMPFMT_UNSIGNED))
return AF_SUCCEED;
/*
If the offset for the fact chunk hasn't been set yet,
set it to the file's current position.
*/
if (m_factOffset == 0)
m_factOffset = m_fh->tell();
else
m_fh->seek(m_factOffset, File::SeekFromBeginning);
m_fh->write("fact", 4);
writeU32(&factSize);
totalFrameCount = track->totalfframes;
writeU32(&totalFrameCount);
return AF_SUCCEED;
}
status WAVEFile::writeData()
{
Track *track = getTrack();
m_fh->write("data", 4);
m_dataSizeOffset = m_fh->tell();
uint32_t chunkSize = track->data_size;
writeU32(&chunkSize);
track->fpos_first_frame = m_fh->tell();
return AF_SUCCEED;
}
status WAVEFile::update()
{
Track *track = getTrack();
if (track->fpos_first_frame != 0)
{
uint32_t dataLength, fileLength;
// Update the frame count chunk if present.
writeFrameCount();
// Update the length of the data chunk.
m_fh->seek(m_dataSizeOffset, File::SeekFromBeginning);
dataLength = (uint32_t) track->data_size;
writeU32(&dataLength);
// Update the length of the RIFF chunk.
fileLength = (uint32_t) m_fh->length();
fileLength -= 8;
m_fh->seek(4, File::SeekFromBeginning);
writeU32(&fileLength);
}
/*
Write the actual data that was set after initializing
the miscellaneous IDs. The size of the data will be
unchanged.
*/
writeMiscellaneous();
// Write the new positions; the size of the data will be unchanged.
writeCues();
return AF_SUCCEED;
}
/* Convert an Audio File Library miscellaneous type to a WAVE type. */
static bool misc_type_to_wave (int misctype, Tag *miscid)
{
if (misctype == AF_MISC_AUTH)
*miscid = "IART";
else if (misctype == AF_MISC_NAME)
*miscid = "INAM";
else if (misctype == AF_MISC_COPY)
*miscid = "ICOP";
else if (misctype == AF_MISC_ICMT)
*miscid = "ICMT";
else if (misctype == AF_MISC_ICRD)
*miscid = "ICRD";
else if (misctype == AF_MISC_ISFT)
*miscid = "ISFT";
else
return false;
return true;
}
status WAVEFile::writeMiscellaneous()
{
if (m_miscellaneousCount != 0)
{
uint32_t miscellaneousBytes;
uint32_t chunkSize;
/* Start at 12 to account for 'LIST', size, and 'INFO'. */
miscellaneousBytes = 12;
/* Then calculate the size of the whole INFO chunk. */
for (int i=0; i<m_miscellaneousCount; i++)
{
Tag miscid;
// Skip miscellaneous data of an unsupported type.
if (!misc_type_to_wave(m_miscellaneous[i].type, &miscid))
continue;
// Account for miscellaneous type and size.
miscellaneousBytes += 8;
miscellaneousBytes += m_miscellaneous[i].size;
// Add a pad byte if necessary.
if (m_miscellaneous[i].size % 2 != 0)
miscellaneousBytes++;
assert(miscellaneousBytes % 2 == 0);
}
if (m_miscellaneousOffset == 0)
m_miscellaneousOffset = m_fh->tell();
else
m_fh->seek(m_miscellaneousOffset, File::SeekFromBeginning);
/*
Write the data. On the first call to this
function (from _af_wave_write_init), the
data won't be available, fh->seek is used to
reserve space until the data has been provided.
On subseuent calls to this function (from
_af_wave_update), the data will really be written.
*/
/* Write 'LIST'. */
m_fh->write("LIST", 4);
/* Write the size of the following chunk. */
chunkSize = miscellaneousBytes-8;
writeU32(&chunkSize);
/* Write 'INFO'. */
m_fh->write("INFO", 4);
/* Write each miscellaneous chunk. */
for (int i=0; i<m_miscellaneousCount; i++)
{
uint32_t miscsize = m_miscellaneous[i].size;
Tag miscid;
// Skip miscellaneous data of an unsupported type.
if (!misc_type_to_wave(m_miscellaneous[i].type, &miscid))
continue;
writeTag(&miscid);
writeU32(&miscsize);
if (m_miscellaneous[i].buffer != NULL)
{
uint8_t zero = 0;
m_fh->write(m_miscellaneous[i].buffer, m_miscellaneous[i].size);
// Pad if necessary.
if ((m_miscellaneous[i].size%2) != 0)
writeU8(&zero);
}
else
{
int size;
size = m_miscellaneous[i].size;
// Pad if necessary.
if ((size % 2) != 0)
size++;
m_fh->seek(size, File::SeekFromCurrent);
}
}
}
return AF_SUCCEED;
}
status WAVEFile::writeCues()
{
Track *track = getTrack();
if (!track->markerCount)
return AF_SUCCEED;
if (m_markOffset == 0)
m_markOffset = m_fh->tell();
else
m_fh->seek(m_markOffset, File::SeekFromBeginning);
Tag cue("cue ");
writeTag(&cue);
/*
The cue chunk consists of 4 bytes for the number of cue points
followed by 24 bytes for each cue point record.
*/
uint32_t cueChunkSize = 4 + track->markerCount * 24;
writeU32(&cueChunkSize);
uint32_t numCues = track->markerCount;
writeU32(&numCues);
// Write each marker to the file.
for (int i=0; i<track->markerCount; i++)
{
uint32_t identifier = track->markers[i].id;
writeU32(&identifier);
uint32_t position = i;
writeU32(&position);
Tag data("data");
writeTag(&data);
/*
For an uncompressed WAVE file which contains only one data chunk,
chunkStart and blockStart are zero.
*/
uint32_t chunkStart = 0;
writeU32(&chunkStart);
uint32_t blockStart = 0;
writeU32(&blockStart);
AFframecount markPosition = track->markers[i].position;
uint32_t sampleOffset = markPosition;
writeU32(&sampleOffset);
}
// Now write the cue names and comments within a master list chunk.
uint32_t listChunkSize = 4;
for (int i=0; i<track->markerCount; i++)
{
const char *name = track->markers[i].name;
const char *comment = track->markers[i].comment;
/*
Each 'labl' or 'note' chunk consists of 4 bytes for the chunk ID,
4 bytes for the chunk data size, 4 bytes for the cue point ID,
and then the length of the label as a null-terminated string.
In all, this is 12 bytes plus the length of the string, its null
termination byte, and a trailing pad byte if the length of the
chunk is otherwise odd.
*/
listChunkSize += 12 + zStringLength(name);
listChunkSize += 12 + zStringLength(comment);
}
Tag list("LIST");
writeTag(&list);
writeU32(&listChunkSize);
Tag adtl("adtl");
writeTag(&adtl);
for (int i=0; i<track->markerCount; i++)
{
uint32_t cuePointID = track->markers[i].id;
const char *name = track->markers[i].name;
uint32_t labelSize = 4 + zStringLength(name);
Tag lablTag("labl");
writeTag(&lablTag);
writeU32(&labelSize);
writeU32(&cuePointID);
writeZString(name);
const char *comment = track->markers[i].comment;
uint32_t noteSize = 4 + zStringLength(comment);
Tag noteTag("note");
writeTag(¬eTag);
writeU32(¬eSize);
writeU32(&cuePointID);
writeZString(comment);
}
return AF_SUCCEED;
}
bool WAVEFile::writeZString(const char *s)
{
ssize_t lengthPlusNull = strlen(s) + 1;
if (m_fh->write(s, lengthPlusNull) != lengthPlusNull)
return false;
if (lengthPlusNull & 1)
{
uint8_t zero = 0;
if (!writeU8(&zero))
return false;
}
return true;
}
size_t WAVEFile::zStringLength(const char *s)
{
size_t lengthPlusNull = strlen(s) + 1;
return lengthPlusNull + (lengthPlusNull & 1);
}
status WAVEFile::writeInit(AFfilesetup setup)
{
if (initFromSetup(setup) == AF_FAIL)
return AF_FAIL;
initCompressionParams();
uint32_t zero = 0;
m_fh->seek(0, File::SeekFromBeginning);
m_fh->write("RIFF", 4);
m_fh->write(&zero, 4);
m_fh->write("WAVE", 4);
writeMiscellaneous();
writeCues();
writeFormat();
writeFrameCount();
writeData();
return AF_SUCCEED;
}
bool WAVEFile::readUUID(UUID *u)
{
return m_fh->read(u->data, 16) == 16;
}
bool WAVEFile::writeUUID(const UUID *u)
{
return m_fh->write(u->data, 16) == 16;
}
void WAVEFile::initCompressionParams()
{
Track *track = getTrack();
if (track->f.compressionType == AF_COMPRESSION_IMA)
initIMACompressionParams();
else if (track->f.compressionType == AF_COMPRESSION_MS_ADPCM)
initMSADPCMCompressionParams();
}
void WAVEFile::initIMACompressionParams()
{
Track *track = getTrack();
track->f.framesPerPacket = 505;
track->f.bytesPerPacket = 256 * track->f.channelCount;
AUpvlist pv = AUpvnew(1);
AUpvsetparam(pv, 0, _AF_IMA_ADPCM_TYPE);
AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);
long l = _AF_IMA_ADPCM_TYPE_WAVE;
AUpvsetval(pv, 0, &l);
track->f.compressionParams = pv;
}
void WAVEFile::initMSADPCMCompressionParams()
{
const int16_t coefficients[7][2] =
{
{ 256, 0 },
{ 512, -256 },
{ 0, 0 },
{ 192, 64 },
{ 240, 0 },
{ 460, -208 },
{ 392, -232 }
};
memcpy(m_msadpcmCoefficients, coefficients, sizeof (int16_t) * 7 * 2);
m_msadpcmNumCoefficients = 7;
Track *track = getTrack();
track->f.framesPerPacket = 500;
track->f.bytesPerPacket = 256 * track->f.channelCount;
AUpvlist pv = AUpvnew(2);
AUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS);
AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG);
long l = m_msadpcmNumCoefficients;
AUpvsetval(pv, 0, &l);
AUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS);
AUpvsetvaltype(pv, 1, AU_PVTYPE_PTR);
void *v = m_msadpcmCoefficients;
AUpvsetval(pv, 1, &v);
track->f.compressionParams = pv;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_3220_0 |
crossvul-cpp_data_good_1581_1 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: sw-offload.c
*
* This file contains SW Implementation of checksum computation for IP,TCP,UDP
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
// till IP header size is 8 bit
#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4)
// IPv6 Header RFC 2460 (n*8 bytes)
typedef struct _tagIPv6ExtHeader {
UCHAR ip6ext_next_header; // next header type
UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes
USHORT options; //
} IPv6ExtHeader;
// IP Pseudo Header RFC 768
typedef struct _tagIPv4PseudoHeader {
ULONG ipph_src; // Source address
ULONG ipph_dest; // Destination address
UCHAR ipph_zero; // 0
UCHAR ipph_protocol; // TCP/UDP
USHORT ipph_length; // TCP/UDP length
}tIPv4PseudoHeader;
// IPv6 Pseudo Header RFC 2460
typedef struct _tagIPv6PseudoHeader {
IPV6_ADDRESS ipph_src; // Source address
IPV6_ADDRESS ipph_dest; // Destination address
ULONG ipph_length; // TCP/UDP length
UCHAR z1; // 0
UCHAR z2; // 0
UCHAR z3; // 0
UCHAR ipph_protocol; // TCP/UDP
}tIPv6PseudoHeader;
// IP v6 extension header option
typedef struct _tagIP6_EXT_HDR_OPTION
{
UCHAR Type;
UCHAR Length;
} IP6_EXT_HDR_OPTION, *PIP6_EXT_HDR_OPTION;
#define IP6_EXT_HDR_OPTION_PAD1 (0)
#define IP6_EXT_HDR_OPTION_HOME_ADDR (201)
// IP v6 routing header
typedef struct _tagIP6_TYPE2_ROUTING_HEADER
{
UCHAR NextHdr;
UCHAR HdrLen;
UCHAR RoutingType;
UCHAR SegmentsLeft;
ULONG Reserved;
IPV6_ADDRESS Address;
} IP6_TYPE2_ROUTING_HEADER, *PIP6_TYPE2_ROUTING_HEADER;
#define PROTOCOL_TCP 6
#define PROTOCOL_UDP 17
#define IP_HEADER_LENGTH(pHeader) (((pHeader)->ip_verlen & 0x0F) << 2)
#define IP_HEADER_VERSION(pHeader) (((pHeader)->ip_verlen & 0xF0) >> 4)
#define IP_HEADER_IS_FRAGMENT(pHeader) (((pHeader)->ip_offset & ~0xC0) != 0)
#define IP6_HEADER_VERSION(pHeader) (((pHeader)->ip6_ver_tc & 0xF0) >> 4)
#define ETH_GET_VLAN_HDR(ethHdr) ((PVLAN_HEADER) RtlOffsetToPointer(ethHdr, ETH_PRIORITY_HEADER_OFFSET))
#define VLAN_GET_USER_PRIORITY(vlanHdr) ( (((PUCHAR)(vlanHdr))[2] & 0xE0) >> 5 )
#define VLAN_GET_VLAN_ID(vlanHdr) ( ((USHORT) (((PUCHAR)(vlanHdr))[2] & 0x0F) << 8) | ( ((PUCHAR)(vlanHdr))[3] ) )
#define ETH_PROTO_IP4 (0x0800)
#define ETH_PROTO_IP6 (0x86DD)
#define IP6_HDR_HOP_BY_HOP (0)
#define IP6_HDR_ROUTING (43)
#define IP6_HDR_FRAGMENT (44)
#define IP6_HDR_ESP (50)
#define IP6_HDR_AUTHENTICATION (51)
#define IP6_HDR_NONE (59)
#define IP6_HDR_DESTINATON (60)
#define IP6_HDR_MOBILITY (135)
#define IP6_EXT_HDR_GRANULARITY (8)
static UINT32 RawCheckSumCalculator(PVOID buffer, ULONG len)
{
UINT32 val = 0;
PUSHORT pus = (PUSHORT)buffer;
ULONG count = len >> 1;
while (count--) val += *pus++;
if (len & 1) val += (USHORT)*(PUCHAR)pus;
return val;
}
static __inline USHORT RawCheckSumFinalize(UINT32 val)
{
val = (((val >> 16) | (val << 16)) + val) >> 16;
return (USHORT)~val;
}
static __inline USHORT CheckSumCalculatorFlat(PVOID buffer, ULONG len)
{
return RawCheckSumFinalize(RawCheckSumCalculator(buffer, len));
}
static __inline USHORT CheckSumCalculator(tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG len)
{
tCompletePhysicalAddress *pCurrentPage = &pDataPages[0];
ULONG ulCurrPageOffset = 0;
UINT32 u32RawCSum = 0;
while(ulStartOffset > 0)
{
ulCurrPageOffset = min(pCurrentPage->size, ulStartOffset);
if(ulCurrPageOffset < ulStartOffset)
pCurrentPage++;
ulStartOffset -= ulCurrPageOffset;
}
while(len > 0)
{
PVOID pCurrentPageDataStart = RtlOffsetToPointer(pCurrentPage->Virtual, ulCurrPageOffset);
ULONG ulCurrentPageDataLength = min(len, pCurrentPage->size - ulCurrPageOffset);
u32RawCSum += RawCheckSumCalculator(pCurrentPageDataStart, ulCurrentPageDataLength);
pCurrentPage++;
ulCurrPageOffset = 0;
len -= ulCurrentPageDataLength;
}
return RawCheckSumFinalize(u32RawCSum);
}
/******************************************
IP header checksum calculator
*******************************************/
static __inline VOID CalculateIpChecksum(IPv4Header *pIpHeader)
{
pIpHeader->ip_xsum = 0;
pIpHeader->ip_xsum = CheckSumCalculatorFlat(pIpHeader, IP_HEADER_LENGTH(pIpHeader));
}
static __inline tTcpIpPacketParsingResult
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
static __inline tTcpIpPacketParsingResult
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
// may be full or not, but the datagram length is known
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
else
{
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
static __inline tTcpIpPacketParsingResult
QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
{
tTcpIpPacketParsingResult res;
res.value = 0;
if (len < 4)
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
if (len < sizeof(IPv4Header))
{
res.ipStatus = ppresNotIP;
return res;
}
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (res.ipStatus == ppresNotIP)
{
return res;
}
if (ipHeaderSize >= fullLength || len < fullLength)
{
DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipCheckSum = ppresIPTooShort;
return res;
}
}
else if (ip_version == 6)
{
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
//existing extended headers
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
//any other protocol
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
// bit "more fragments" or fragment offset mean the packet is fragmented
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
static __inline USHORT GetXxpHeaderAndPayloadLen(IPHeader *pIpHeader, tTcpIpPacketParsingResult res)
{
if (res.ipStatus == ppresIPV4)
{
USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4);
USHORT len = swap_short(pIpHeader->v4.ip_length);
return len - headerLength;
}
if (res.ipStatus == ppresIPV6)
{
USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize;
}
return 0;
}
static __inline USHORT CalculateIpv4PseudoHeaderChecksum(IPv4Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv4PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src = pIpHeader->ip_src;
ipph.ipph_dest = pIpHeader->ip_dest;
ipph.ipph_zero = 0;
ipph.ipph_protocol = pIpHeader->ip_protocol;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv6PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src[0] = pIpHeader->ip6_src_address[0];
ipph.ipph_src[1] = pIpHeader->ip6_src_address[1];
ipph.ipph_src[2] = pIpHeader->ip6_src_address[2];
ipph.ipph_src[3] = pIpHeader->ip6_src_address[3];
ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0];
ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1];
ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2];
ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3];
ipph.z1 = ipph.z2 = ipph.z3 = 0;
ipph.ipph_protocol = pIpHeader->ip6_next_header;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader,
tTcpIpPacketParsingResult res,
USHORT headerAndPayloadLen)
{
if (res.ipStatus == ppresIPV4)
return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen);
if (res.ipStatus == ppresIPV6)
return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen);
return 0;
}
static __inline BOOLEAN
CompareNetCheckSumOnEndSystem(USHORT computedChecksum, USHORT arrivedChecksum)
{
//According to RFC 1624 sec. 3
//Checksum verification mechanism should treat 0xFFFF
//checksum value from received packet as 0x0000
if(arrivedChecksum == 0xFFFF)
arrivedChecksum = 0;
return computedChecksum == arrivedChecksum;
}
/******************************************
Calculates IP header checksum calculator
it can be already calculated
the header must be complete!
*******************************************/
static __inline tTcpIpPacketParsingResult
VerifyIpChecksum(
IPv4Header *pIpHeader,
tTcpIpPacketParsingResult known,
BOOLEAN bFix)
{
tTcpIpPacketParsingResult res = known;
if (res.ipCheckSum != ppresIPTooShort)
{
USHORT saved = pIpHeader->ip_xsum;
CalculateIpChecksum(pIpHeader);
res.ipCheckSum = CompareNetCheckSumOnEndSystem(pIpHeader->ip_xsum, saved) ? ppresCSOK : ppresCSBad;
if (!bFix)
pIpHeader->ip_xsum = saved;
else
res.fixedIpCS = res.ipCheckSum == ppresCSBad;
}
return res;
}
/*********************************************
Calculates UDP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateUdpChecksumGivenPseudoCS(UDPHeader *pUdpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG udpLength)
{
pUdpHeader->udp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, udpLength);
}
/*********************************************
Calculates TCP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateTcpChecksumGivenPseudoCS(TCPHeader *pTcpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG tcpLength)
{
pTcpHeader->tcp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, tcpLength);
}
/************************************************
Checks (and fix if required) the TCP checksum
sets flags in result structure according to verification
TcpPseudoOK if valid pseudo CS was found
TcpOK if valid TCP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyTcpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pTcpHeader->tcp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (res.xxpCheckSum != ppresPCSOK || whatToFix)
{
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader)))
{
pTcpHeader->tcp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
//USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length);
pTcpHeader->tcp_xsum = phcs;
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pTcpHeader->tcp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else if (whatToFix)
{
res.xxpStatus = ppresXxpIncomplete;
}
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good TCP CS
// in such rare case we give a priority to TCP CS
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pTcpHeader->tcp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
/************************************************
Checks (and fix if required) the UDP checksum
sets flags in result structure according to verification
UdpPseudoOK if valid pseudo CS was found
UdpOK if valid UDP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyUdpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pUdpHeader->udp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader)))
{
pUdpHeader->udp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum))
{
if (res.xxpFull)
{
pUdpHeader->udp_xsum = phcs;
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pUdpHeader->udp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else
res.xxpCheckSum = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good UDP CS
// in such rare case we give a priority to UDP CS
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pUdpHeader->udp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
static LPCSTR __inline GetPacketCase(tTcpIpPacketParsingResult res)
{
static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" };
if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ?
(res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") :
(res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6");
if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP";
if (res.xxpStatus == ppresXxpOther) return "IP";
return IPCaseName[res.ipStatus];
}
static LPCSTR __inline GetIPCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" };
return CSCaseName[res.ipCheckSum];
}
static LPCSTR __inline GetXxpCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" };
return CSCaseName[res.xxpCheckSum];
}
static __inline VOID PrintOutParsingResult(
tTcpIpPacketParsingResult res,
int level,
LPCSTR procname)
{
DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s\n", procname,
GetPacketCase(res),
GetIPCSCase(res),
res.fixedIpCS ? "(fixed)" : "",
GetXxpCSCase(res),
res.fixedXxpCS ? "(fixed)" : ""));
}
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
static __inline
VOID AnalyzeL3Proto(
USHORT L3Proto,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isIP4 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP4));
packetInfo->isIP6 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP6));
}
static
BOOLEAN AnalyzeL2Hdr(
PNET_PACKET_INFO packetInfo)
{
PETH_HEADER dataBuffer = (PETH_HEADER) packetInfo->headersBuffer;
if (packetInfo->dataLength < ETH_HEADER_SIZE)
return FALSE;
packetInfo->ethDestAddr = dataBuffer->DstAddr;
if (ETH_IS_BROADCAST(dataBuffer))
{
packetInfo->isBroadcast = TRUE;
}
else if (ETH_IS_MULTICAST(dataBuffer))
{
packetInfo->isMulticast = TRUE;
}
else
{
packetInfo->isUnicast = TRUE;
}
if(ETH_HAS_PRIO_HEADER(dataBuffer))
{
PVLAN_HEADER vlanHdr = ETH_GET_VLAN_HDR(dataBuffer);
if(packetInfo->dataLength < ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
packetInfo->hasVlanHeader = TRUE;
packetInfo->Vlan.UserPriority = VLAN_GET_USER_PRIORITY(vlanHdr);
packetInfo->Vlan.VlanId = VLAN_GET_VLAN_ID(vlanHdr);
packetInfo->L2HdrLen = ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE;
AnalyzeL3Proto(vlanHdr->EthType, packetInfo);
}
else
{
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
AnalyzeL3Proto(dataBuffer->EthType, packetInfo);
}
packetInfo->L2PayloadLen = packetInfo->dataLength - packetInfo->L2HdrLen;
return TRUE;
}
static __inline
BOOLEAN SkipIP6ExtensionHeader(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr)
{
IPv6ExtHeader* ip6ExtHdr;
if (*ip6HdrLength + sizeof(*ip6ExtHdr) > dataLength)
return FALSE;
ip6ExtHdr = (IPv6ExtHeader *)RtlOffsetToPointer(ip6Hdr, *ip6HdrLength);
*nextHdr = ip6ExtHdr->ip6ext_next_header;
*ip6HdrLength += (ip6ExtHdr->ip6ext_hdr_len + 1) * IP6_EXT_HDR_GRANULARITY;
return TRUE;
}
static
BOOLEAN AnalyzeIP6RoutingExtension(
PIP6_TYPE2_ROUTING_HEADER routingHdr,
ULONG dataLength,
IPV6_ADDRESS **destAddr)
{
if(dataLength < sizeof(*routingHdr))
return FALSE;
if(routingHdr->RoutingType == 2)
{
if((dataLength != sizeof(*routingHdr)) || (routingHdr->SegmentsLeft != 1))
return FALSE;
*destAddr = &routingHdr->Address;
}
else *destAddr = NULL;
return TRUE;
}
static
BOOLEAN AnalyzeIP6DestinationExtension(
PVOID destHdr,
ULONG dataLength,
IPV6_ADDRESS **homeAddr)
{
while(dataLength != 0)
{
PIP6_EXT_HDR_OPTION optHdr = (PIP6_EXT_HDR_OPTION) destHdr;
ULONG optionLen;
switch(optHdr->Type)
{
case IP6_EXT_HDR_OPTION_HOME_ADDR:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
if(optHdr->Length != sizeof(IPV6_ADDRESS))
return FALSE;
*homeAddr = (IPV6_ADDRESS*) RtlOffsetToPointer(optHdr, sizeof(IP6_EXT_HDR_OPTION));
break;
case IP6_EXT_HDR_OPTION_PAD1:
optionLen = RTL_SIZEOF_THROUGH_FIELD(IP6_EXT_HDR_OPTION, Type);
break;
default:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
break;
}
destHdr = RtlOffsetToPointer(destHdr, optionLen);
if(dataLength < optionLen)
return FALSE;
dataLength -= optionLen;
}
return TRUE;
}
static
BOOLEAN AnalyzeIP6Hdr(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr,
PULONG homeAddrOffset,
PULONG destAddrOffset)
{
*homeAddrOffset = 0;
*destAddrOffset = 0;
*ip6HdrLength = sizeof(*ip6Hdr);
if(dataLength < *ip6HdrLength)
return FALSE;
*nextHdr = ip6Hdr->ip6_next_header;
for(;;)
{
switch (*nextHdr)
{
default:
case IP6_HDR_NONE:
case PROTOCOL_TCP:
case PROTOCOL_UDP:
case IP6_HDR_FRAGMENT:
return TRUE;
case IP6_HDR_DESTINATON:
{
IPV6_ADDRESS *homeAddr = NULL;
ULONG destHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6DestinationExtension(RtlOffsetToPointer(ip6Hdr, destHdrOffset),
*ip6HdrLength - destHdrOffset, &homeAddr))
return FALSE;
*homeAddrOffset = homeAddr ? RtlPointerToOffset(ip6Hdr, homeAddr) : 0;
}
break;
case IP6_HDR_ROUTING:
{
IPV6_ADDRESS *destAddr = NULL;
ULONG routingHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6RoutingExtension((PIP6_TYPE2_ROUTING_HEADER) RtlOffsetToPointer(ip6Hdr, routingHdrOffset),
*ip6HdrLength - routingHdrOffset, &destAddr))
return FALSE;
*destAddrOffset = destAddr ? RtlPointerToOffset(ip6Hdr, destAddr) : 0;
}
break;
case IP6_HDR_HOP_BY_HOP:
case IP6_HDR_ESP:
case IP6_HDR_AUTHENTICATION:
case IP6_HDR_MOBILITY:
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
break;
}
}
}
static __inline
VOID AnalyzeL4Proto(
UCHAR l4Protocol,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isTCP = (l4Protocol == PROTOCOL_TCP);
packetInfo->isUDP = (l4Protocol == PROTOCOL_UDP);
}
static
BOOLEAN AnalyzeL3Hdr(
PNET_PACKET_INFO packetInfo)
{
if(packetInfo->isIP4)
{
IPv4Header *ip4Hdr = (IPv4Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(packetInfo->dataLength < packetInfo->L2HdrLen + sizeof(*ip4Hdr))
return FALSE;
packetInfo->L3HdrLen = IP_HEADER_LENGTH(ip4Hdr);
if ((packetInfo->L3HdrLen < sizeof(*ip4Hdr)) ||
(packetInfo->dataLength < packetInfo->L2HdrLen + packetInfo->L3HdrLen))
return FALSE;
if(IP_HEADER_VERSION(ip4Hdr) != 4)
return FALSE;
packetInfo->isFragment = IP_HEADER_IS_FRAGMENT(ip4Hdr);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(ip4Hdr->ip_protocol, packetInfo);
}
}
else if(packetInfo->isIP6)
{
ULONG homeAddrOffset, destAddrOffset;
UCHAR l4Proto;
IPv6Header *ip6Hdr = (IPv6Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(IP6_HEADER_VERSION(ip6Hdr) != 6)
return FALSE;
if(!AnalyzeIP6Hdr(ip6Hdr, packetInfo->L2PayloadLen,
&packetInfo->L3HdrLen, &l4Proto, &homeAddrOffset, &destAddrOffset))
return FALSE;
if (packetInfo->L3HdrLen > MAX_SUPPORTED_IPV6_HEADERS)
return FALSE;
packetInfo->ip6HomeAddrOffset = (homeAddrOffset) ? packetInfo->L2HdrLen + homeAddrOffset : 0;
packetInfo->ip6DestAddrOffset = (destAddrOffset) ? packetInfo->L2HdrLen + destAddrOffset : 0;
packetInfo->isFragment = (l4Proto == IP6_HDR_FRAGMENT);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(l4Proto, packetInfo);
}
}
return TRUE;
}
BOOLEAN ParaNdis_AnalyzeReceivedPacket(
PVOID headersBuffer,
ULONG dataLength,
PNET_PACKET_INFO packetInfo)
{
NdisZeroMemory(packetInfo, sizeof(*packetInfo));
packetInfo->headersBuffer = headersBuffer;
packetInfo->dataLength = dataLength;
if(!AnalyzeL2Hdr(packetInfo))
return FALSE;
if (!AnalyzeL3Hdr(packetInfo))
return FALSE;
return TRUE;
}
ULONG ParaNdis_StripVlanHeaderMoveHead(PNET_PACKET_INFO packetInfo)
{
PUINT32 pData = (PUINT32) packetInfo->headersBuffer;
ASSERT(packetInfo->hasVlanHeader);
ASSERT(packetInfo->L2HdrLen == ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE);
pData[3] = pData[2];
pData[2] = pData[1];
pData[1] = pData[0];
packetInfo->headersBuffer = RtlOffsetToPointer(packetInfo->headersBuffer, ETH_PRIORITY_HEADER_SIZE);
packetInfo->dataLength -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
packetInfo->ethDestAddr = (PUCHAR) RtlOffsetToPointer(packetInfo->ethDestAddr, ETH_PRIORITY_HEADER_SIZE);
packetInfo->ip6DestAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->ip6HomeAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
return ETH_PRIORITY_HEADER_SIZE;
};
VOID ParaNdis_PadPacketToMinimalLength(PNET_PACKET_INFO packetInfo)
{
// Ethernet standard declares minimal possible packet size
// Packets smaller than that must be padded before transfer
// Ethernet HW pads packets on transmit, however in our case
// some packets do not travel over Ethernet but being routed
// guest-to-guest by virtual switch.
// In this case padding is not performed and we may
// receive packet smaller than minimal allowed size. This is not
// a problem for real life scenarios however WHQL/HCK contains
// tests that check padding of received packets.
// To make these tests happy we have to pad small packets on receive
//NOTE: This function assumes that VLAN header has been already stripped out
if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE)
{
RtlZeroMemory(
RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength),
ETH_MIN_PACKET_SIZE - packetInfo->dataLength);
packetInfo->dataLength = ETH_MIN_PACKET_SIZE;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1581_1 |
crossvul-cpp_data_bad_1749_1 | /*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2011-2015 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <Core/Controller.h>
// For calculating delta_monotonic (Ruby < 2.1 workaround, otherwise unused)
#include <uv.h>
/*************************************************************************
*
* Implements Core::Controller methods pertaining sending request data
* to a selected application process. This happens in parallel to forwarding
* application response data to the client.
*
*************************************************************************/
namespace Passenger {
namespace Core {
using namespace std;
using namespace boost;
/****************************
*
* Private methods
*
****************************/
struct Controller::SessionProtocolWorkingState {
StaticString path;
StaticString queryString;
StaticString methodStr;
StaticString serverName;
StaticString serverPort;
const LString *remoteAddr;
const LString *remotePort;
const LString *remoteUser;
const LString *contentType;
const LString *contentLength;
char *environmentVariablesData;
size_t environmentVariablesSize;
bool hasBaseURI;
SessionProtocolWorkingState()
: environmentVariablesData(NULL)
{ }
~SessionProtocolWorkingState() {
free(environmentVariablesData);
}
};
struct Controller::HttpHeaderConstructionCache {
StaticString methodStr;
const LString *remoteAddr;
const LString *setCookie;
bool cached;
};
void
Controller::sendHeaderToApp(Client *client, Request *req) {
TRACE_POINT();
SKC_TRACE(client, 2, "Sending headers to application with " <<
req->session->getProtocol() << " protocol");
req->state = Request::SENDING_HEADER_TO_APP;
/**
* HTTP does not formally support half-closing, and Node.js treats a
* half-close as a full close, so we only half-close session sockets, not
* HTTP sockets.
*/
if (req->session->getProtocol() == "session") {
UPDATE_TRACE_POINT();
req->halfCloseAppConnection = req->bodyType != Request::RBT_NO_BODY;
sendHeaderToAppWithSessionProtocol(client, req);
} else {
UPDATE_TRACE_POINT();
req->halfCloseAppConnection = false;
sendHeaderToAppWithHttpProtocol(client, req);
}
UPDATE_TRACE_POINT();
if (!req->ended()) {
if (req->appSink.acceptingInput()) {
UPDATE_TRACE_POINT();
sendBodyToApp(client, req);
if (!req->ended()) {
req->appSource.startReading();
}
} else if (req->appSink.mayAcceptInputLater()) {
UPDATE_TRACE_POINT();
SKC_TRACE(client, 3, "Waiting for appSink channel to become "
"idle before sending body to application");
req->appSink.setConsumedCallback(sendBodyToAppWhenAppSinkIdle);
req->appSource.startReading();
} else {
// Either we're done feeding to req->appSink, or req->appSink.feed()
// encountered an error while writing to the application socket.
// But we don't care about either scenarios; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
UPDATE_TRACE_POINT();
assert(req->appSink.ended() || req->appSink.hasError());
logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
req->appSource.startReading();
}
}
}
void
Controller::sendHeaderToAppWithSessionProtocol(Client *client, Request *req) {
TRACE_POINT();
SessionProtocolWorkingState state;
// Workaround for Ruby < 2.1 support.
std::string delta_monotonic = boost::to_string(SystemTime::getUsec() - (uv_hrtime() / 1000));
unsigned int bufferSize = determineHeaderSizeForSessionProtocol(req,
state, delta_monotonic);
MemoryKit::mbuf_pool &mbuf_pool = getContext()->mbuf_pool;
const unsigned int MBUF_MAX_SIZE = mbuf_pool_data_size(&mbuf_pool);
bool ok;
if (bufferSize <= MBUF_MAX_SIZE) {
MemoryKit::mbuf buffer(MemoryKit::mbuf_get(&mbuf_pool));
bufferSize = MBUF_MAX_SIZE;
ok = constructHeaderForSessionProtocol(req, buffer.start,
bufferSize, state, delta_monotonic);
assert(ok);
buffer = MemoryKit::mbuf(buffer, 0, bufferSize);
SKC_TRACE(client, 3, "Header data: \"" << cEscapeString(
StaticString(buffer.start, bufferSize)) << "\"");
req->appSink.feedWithoutRefGuard(boost::move(buffer));
} else {
char *buffer = (char *) psg_pnalloc(req->pool, bufferSize);
ok = constructHeaderForSessionProtocol(req, buffer,
bufferSize, state, delta_monotonic);
assert(ok);
SKC_TRACE(client, 3, "Header data: \"" << cEscapeString(
StaticString(buffer, bufferSize)) << "\"");
req->appSink.feedWithoutRefGuard(MemoryKit::mbuf(
buffer, bufferSize));
}
(void) ok; // Shut up compiler warning
}
void
Controller::sendBodyToAppWhenAppSinkIdle(Channel *_channel, unsigned int size) {
FdSinkChannel *channel = reinterpret_cast<FdSinkChannel *>(_channel);
Request *req = static_cast<Request *>(static_cast<
ServerKit::BaseHttpRequest *>(channel->getHooks()->userData));
Client *client = static_cast<Client *>(req->client);
Controller *self = static_cast<Controller *>(
getServerFromClient(client));
SKC_LOG_EVENT_FROM_STATIC(self, Controller, client, "sendBodyToAppWhenAppSinkIdle");
channel->setConsumedCallback(NULL);
if (channel->acceptingInput()) {
self->sendBodyToApp(client, req);
if (!req->ended()) {
req->appSource.startReading();
}
} else {
// req->appSink.feed() encountered an error while writing to the
// application socket. But we don't care about that; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
UPDATE_TRACE_POINT();
assert(!req->appSink.ended());
assert(req->appSink.hasError());
self->logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
req->appSource.startReading();
}
}
static void
httpHeaderToScgiUpperCase(unsigned char *data, unsigned int size) {
static const boost::uint8_t toUpperMap[256] = {
'\0', 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, '\t',
'\n', 0x0b, 0x0c, '\r', 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f, ' ', '!', '"', '#', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', '_', '.', '/', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
'<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', '[', '\\', ']', '^', '_', '`', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '{', '|', '}', '~', 0x7f, 0x80, 0x81,
0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b,
0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,
0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9,
0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd,
0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1,
0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb,
0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5,
0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9,
0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
const unsigned char *buf = data;
const size_t imax = size / 8;
const size_t leftover = size % 8;
size_t i;
for (i = 0; i < imax; i++, data += 8) {
data[0] = (unsigned char) toUpperMap[data[0]];
data[1] = (unsigned char) toUpperMap[data[1]];
data[2] = (unsigned char) toUpperMap[data[2]];
data[3] = (unsigned char) toUpperMap[data[3]];
data[4] = (unsigned char) toUpperMap[data[4]];
data[5] = (unsigned char) toUpperMap[data[5]];
data[6] = (unsigned char) toUpperMap[data[6]];
data[7] = (unsigned char) toUpperMap[data[7]];
}
i = imax * 8;
switch (leftover) {
case 7: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 6: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 5: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 4: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 3: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 2: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 1: *data++ = (unsigned char) toUpperMap[buf[i]];
case 0: break;
}
}
unsigned int
Controller::determineHeaderSizeForSessionProtocol(Request *req,
SessionProtocolWorkingState &state, string delta_monotonic)
{
unsigned int dataSize = sizeof(boost::uint32_t);
state.path = req->getPathWithoutQueryString();
state.hasBaseURI = req->options.baseURI != P_STATIC_STRING("/")
&& startsWith(state.path, req->options.baseURI);
if (state.hasBaseURI) {
state.path = state.path.substr(req->options.baseURI.size());
if (state.path.empty()) {
state.path = P_STATIC_STRING("/");
}
}
state.queryString = req->getQueryString();
state.methodStr = StaticString(http_method_str(req->method));
state.remoteAddr = req->secureHeaders.lookup(REMOTE_ADDR);
state.remotePort = req->secureHeaders.lookup(REMOTE_PORT);
state.remoteUser = req->secureHeaders.lookup(REMOTE_USER);
state.contentType = req->headers.lookup(HTTP_CONTENT_TYPE);
if (req->hasBody()) {
state.contentLength = req->headers.lookup(HTTP_CONTENT_LENGTH);
} else {
state.contentLength = NULL;
}
if (req->envvars != NULL) {
size_t len = modp_b64_decode_len(req->envvars->size);
state.environmentVariablesData = (char *) malloc(len);
if (state.environmentVariablesData == NULL) {
throw RuntimeException("Unable to allocate memory for base64 "
"decoding of environment variables");
}
len = modp_b64_decode(state.environmentVariablesData,
req->envvars->start->data,
req->envvars->size);
if (len == (size_t) -1) {
throw RuntimeException("Unable to base64 decode environment variables");
}
state.environmentVariablesSize = len;
}
dataSize += sizeof("REQUEST_URI");
dataSize += req->path.size + 1;
dataSize += sizeof("PATH_INFO");
dataSize += state.path.size() + 1;
dataSize += sizeof("SCRIPT_NAME");
if (state.hasBaseURI) {
dataSize += req->options.baseURI.size();
} else {
dataSize += sizeof("");
}
dataSize += sizeof("QUERY_STRING");
dataSize += state.queryString.size() + 1;
dataSize += sizeof("REQUEST_METHOD");
dataSize += state.methodStr.size() + 1;
if (req->host != NULL && req->host->size > 0) {
const LString *host = psg_lstr_make_contiguous(req->host, req->pool);
const char *sep = (const char *) memchr(host->start->data, ':', host->size);
if (sep != NULL) {
state.serverName = StaticString(host->start->data, sep - host->start->data);
state.serverPort = StaticString(sep + 1,
host->start->data + host->size - sep - 1);
} else {
state.serverName = StaticString(host->start->data, host->size);
if (req->https) {
state.serverPort = P_STATIC_STRING("443");
} else {
state.serverPort = P_STATIC_STRING("80");
}
}
} else {
state.serverName = defaultServerName;
state.serverPort = defaultServerPort;
}
dataSize += sizeof("SERVER_NAME");
dataSize += state.serverName.size() + 1;
dataSize += sizeof("SERVER_PORT");
dataSize += state.serverPort.size() + 1;
dataSize += sizeof("SERVER_SOFTWARE");
dataSize += serverSoftware.size() + 1;
dataSize += sizeof("SERVER_PROTOCOL");
dataSize += sizeof("HTTP/1.1");
dataSize += sizeof("REMOTE_ADDR");
if (state.remoteAddr != NULL) {
dataSize += state.remoteAddr->size + 1;
} else {
dataSize += sizeof("127.0.0.1");
}
dataSize += sizeof("REMOTE_PORT");
if (state.remotePort != NULL) {
dataSize += state.remotePort->size + 1;
} else {
dataSize += sizeof("0");
}
if (state.remoteUser != NULL) {
dataSize += sizeof("REMOTE_USER");
dataSize += state.remoteUser->size + 1;
}
if (state.contentType != NULL) {
dataSize += sizeof("CONTENT_TYPE");
dataSize += state.contentType->size + 1;
}
if (state.contentLength != NULL) {
dataSize += sizeof("CONTENT_LENGTH");
dataSize += state.contentLength->size + 1;
}
dataSize += sizeof("PASSENGER_CONNECT_PASSWORD");
dataSize += ApplicationPool2::ApiKey::SIZE + 1;
if (req->https) {
dataSize += sizeof("HTTPS");
dataSize += sizeof("on");
}
if (req->options.analytics) {
dataSize += sizeof("PASSENGER_TXN_ID");
dataSize += req->options.transaction->getTxnId().size() + 1;
dataSize += sizeof("PASSENGER_DELTA_MONOTONIC");
dataSize += delta_monotonic.size() + 1;
}
if (req->upgraded()) {
dataSize += sizeof("HTTP_CONNECTION");
dataSize += sizeof("upgrade");
}
ServerKit::HeaderTable::Iterator it(req->headers);
while (*it != NULL) {
dataSize += sizeof("HTTP_") - 1 + it->header->key.size + 1;
dataSize += it->header->val.size + 1;
it.next();
}
if (state.environmentVariablesData != NULL) {
dataSize += state.environmentVariablesSize;
}
return dataSize + 1;
}
bool
Controller::constructHeaderForSessionProtocol(Request *req, char * restrict buffer,
unsigned int &size, const SessionProtocolWorkingState &state, string delta_monotonic)
{
char *pos = buffer;
const char *end = buffer + size;
pos += sizeof(boost::uint32_t);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REQUEST_URI"));
pos = appendData(pos, end, req->path.start->data, req->path.size);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PATH_INFO"));
pos = appendData(pos, end, state.path.data(), state.path.size());
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SCRIPT_NAME"));
if (state.hasBaseURI) {
pos = appendData(pos, end, req->options.baseURI);
pos = appendData(pos, end, "", 1);
} else {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL(""));
}
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("QUERY_STRING"));
pos = appendData(pos, end, state.queryString.data(), state.queryString.size());
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REQUEST_METHOD"));
pos = appendData(pos, end, state.methodStr);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_NAME"));
pos = appendData(pos, end, state.serverName);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_PORT"));
pos = appendData(pos, end, state.serverPort);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_SOFTWARE"));
pos = appendData(pos, end, serverSoftware);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_PROTOCOL"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("HTTP/1.1"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REMOTE_ADDR"));
if (state.remoteAddr != NULL) {
pos = appendData(pos, end, state.remoteAddr);
pos = appendData(pos, end, "", 1);
} else {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("127.0.0.1"));
}
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REMOTE_PORT"));
if (state.remotePort != NULL) {
pos = appendData(pos, end, state.remotePort);
pos = appendData(pos, end, "", 1);
} else {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("0"));
}
if (state.remoteUser != NULL) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REMOTE_USER"));
pos = appendData(pos, end, state.remoteUser);
pos = appendData(pos, end, "", 1);
}
if (state.contentType != NULL) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("CONTENT_TYPE"));
pos = appendData(pos, end, state.contentType);
pos = appendData(pos, end, "", 1);
}
if (state.contentLength != NULL) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("CONTENT_LENGTH"));
pos = appendData(pos, end, state.contentLength);
pos = appendData(pos, end, "", 1);
}
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PASSENGER_CONNECT_PASSWORD"));
pos = appendData(pos, end, req->session->getApiKey().toStaticString());
pos = appendData(pos, end, "", 1);
if (req->https) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("HTTPS"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("on"));
}
if (req->options.analytics) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PASSENGER_TXN_ID"));
pos = appendData(pos, end, req->options.transaction->getTxnId());
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PASSENGER_DELTA_MONOTONIC"));
pos = appendData(pos, end, delta_monotonic);
pos = appendData(pos, end, "", 1);
}
if (req->upgraded()) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("HTTP_CONNECTION"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("upgrade"));
}
ServerKit::HeaderTable::Iterator it(req->headers);
while (*it != NULL) {
if ((it->header->hash == HTTP_CONTENT_LENGTH.hash()
|| it->header->hash == HTTP_CONTENT_TYPE.hash()
|| it->header->hash == HTTP_CONNECTION.hash())
&& (psg_lstr_cmp(&it->header->key, P_STATIC_STRING("content-type"))
|| psg_lstr_cmp(&it->header->key, P_STATIC_STRING("content-length"))
|| psg_lstr_cmp(&it->header->key, P_STATIC_STRING("connection"))))
{
it.next();
continue;
}
pos = appendData(pos, end, P_STATIC_STRING("HTTP_"));
const LString::Part *part = it->header->key.start;
while (part != NULL) {
char *start = pos;
pos = appendData(pos, end, part->data, part->size);
httpHeaderToScgiUpperCase((unsigned char *) start, pos - start);
part = part->next;
}
pos = appendData(pos, end, "", 1);
part = it->header->val.start;
while (part != NULL) {
pos = appendData(pos, end, part->data, part->size);
part = part->next;
}
pos = appendData(pos, end, "", 1);
it.next();
}
if (state.environmentVariablesData != NULL) {
pos = appendData(pos, end, state.environmentVariablesData, state.environmentVariablesSize);
}
Uint32Message::generate(buffer, pos - buffer - sizeof(boost::uint32_t));
size = pos - buffer;
return pos < end;
}
void
Controller::sendHeaderToAppWithHttpProtocol(Client *client, Request *req) {
ssize_t bytesWritten;
HttpHeaderConstructionCache cache;
cache.cached = false;
if (OXT_UNLIKELY(getLogLevel() >= LVL_DEBUG3)) {
struct iovec *buffers;
unsigned int nbuffers, dataSize;
bool ok;
ok = constructHeaderBuffersForHttpProtocol(req, NULL, 0,
nbuffers, dataSize, cache);
assert(ok);
buffers = (struct iovec *) psg_palloc(req->pool,
sizeof(struct iovec) * nbuffers);
ok = constructHeaderBuffersForHttpProtocol(req, buffers, nbuffers,
nbuffers, dataSize, cache);
assert(ok);
(void) ok; // Shut up compiler warning
char *buffer = (char *) psg_pnalloc(req->pool, dataSize);
gatherBuffers(buffer, dataSize, buffers, nbuffers);
SKC_TRACE(client, 3, "Header data: \"" <<
cEscapeString(StaticString(buffer, dataSize)) << "\"");
}
if (!sendHeaderToAppWithHttpProtocolAndWritev(req, bytesWritten, cache)) {
if (bytesWritten >= 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
sendHeaderToAppWithHttpProtocolWithBuffering(req, bytesWritten, cache);
} else {
int e = errno;
P_ASSERT_EQ(bytesWritten, -1);
disconnectWithAppSocketWriteError(&client, e);
}
}
}
/**
* Construct an array of buffers, which together contain the 'http' protocol header
* data that should be sent to the application. This method does not copy any data:
* it just constructs buffers that point to the data stored inside `req->pool`,
* `req->headers`, etc.
*
* The buffers will be stored in the array pointed to by `buffer`. This array must
* have space for at least `maxbuffers` items. The actual number of buffers constructed
* is stored in `nbuffers`, and the total data size of the buffers is stored in `dataSize`.
* Upon success, returns true. If the actual number of buffers necessary exceeds
* `maxbuffers`, then false is returned.
*
* You can also set `buffers` to NULL, in which case this method will not construct any
* buffers, but only count the number of buffers necessary, as well as the total data size.
* In this case, this method always returns true.
*/
bool
Controller::constructHeaderBuffersForHttpProtocol(Request *req, struct iovec *buffers,
unsigned int maxbuffers, unsigned int & restrict_ref nbuffers,
unsigned int & restrict_ref dataSize, HttpHeaderConstructionCache &cache)
{
#define BEGIN_PUSH_NEXT_BUFFER() \
do { \
if (buffers != NULL && i >= maxbuffers) { \
return false; \
} \
} while (false)
#define INC_BUFFER_ITER(i) \
do { \
i++; \
} while (false)
#define PUSH_STATIC_BUFFER(buf) \
do { \
BEGIN_PUSH_NEXT_BUFFER(); \
if (buffers != NULL) { \
buffers[i].iov_base = (void *) buf; \
buffers[i].iov_len = sizeof(buf) - 1; \
} \
INC_BUFFER_ITER(i); \
dataSize += sizeof(buf) - 1; \
} while (false)
ServerKit::HeaderTable::Iterator it(req->headers);
const LString::Part *part;
unsigned int i = 0;
nbuffers = 0;
dataSize = 0;
if (!cache.cached) {
cache.methodStr = http_method_str(req->method);
cache.remoteAddr = req->secureHeaders.lookup(REMOTE_ADDR);
cache.setCookie = req->headers.lookup(ServerKit::HTTP_SET_COOKIE);
cache.cached = true;
}
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) cache.methodStr.data();
buffers[i].iov_len = cache.methodStr.size();
}
INC_BUFFER_ITER(i);
dataSize += cache.methodStr.size();
PUSH_STATIC_BUFFER(" ");
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) req->path.start->data;
buffers[i].iov_len = req->path.size;
}
INC_BUFFER_ITER(i);
dataSize += req->path.size;
if (req->upgraded()) {
PUSH_STATIC_BUFFER(" HTTP/1.1\r\nConnection: upgrade\r\n");
} else {
PUSH_STATIC_BUFFER(" HTTP/1.1\r\nConnection: close\r\n");
}
if (cache.setCookie != NULL) {
LString::Part *part;
PUSH_STATIC_BUFFER("Set-Cookie: ");
part = cache.setCookie->start;
while (part != NULL) {
if (part->size == 1 && part->data[0] == '\n') {
// HeaderTable joins multiple Set-Cookie headers together using \n.
PUSH_STATIC_BUFFER("\r\nSet-Cookie: ");
} else {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
dataSize += part->size;
}
part = part->next;
}
PUSH_STATIC_BUFFER("\r\n");
}
while (*it != NULL) {
if ((it->header->hash == HTTP_CONNECTION.hash()
|| it->header->hash == ServerKit::HTTP_SET_COOKIE.hash())
&& (psg_lstr_cmp(&it->header->key, P_STATIC_STRING("connection"))
|| psg_lstr_cmp(&it->header->key, ServerKit::HTTP_SET_COOKIE)))
{
it.next();
continue;
}
part = it->header->key.start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += it->header->key.size;
PUSH_STATIC_BUFFER(": ");
part = it->header->val.start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += it->header->val.size;
PUSH_STATIC_BUFFER("\r\n");
it.next();
}
if (req->https) {
PUSH_STATIC_BUFFER("X-Forwarded-Proto: https\r\n");
PUSH_STATIC_BUFFER("!~Passenger-Proto: https\r\n");
}
if (cache.remoteAddr != NULL && cache.remoteAddr->size > 0) {
PUSH_STATIC_BUFFER("X-Forwarded-For: ");
part = cache.remoteAddr->start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += cache.remoteAddr->size;
PUSH_STATIC_BUFFER("\r\n");
PUSH_STATIC_BUFFER("!~Passenger-Client-Address: ");
part = cache.remoteAddr->start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += cache.remoteAddr->size;
PUSH_STATIC_BUFFER("\r\n");
}
if (req->envvars != NULL) {
PUSH_STATIC_BUFFER("!~Passenger-Envvars: ");
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) req->envvars->start->data;
buffers[i].iov_len = req->envvars->size;
}
INC_BUFFER_ITER(i);
dataSize += req->envvars->size;
PUSH_STATIC_BUFFER("\r\n");
}
if (req->options.analytics) {
PUSH_STATIC_BUFFER("!~Passenger-Txn-Id: ");
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) req->options.transaction->getTxnId().data();
buffers[i].iov_len = req->options.transaction->getTxnId().size();
}
INC_BUFFER_ITER(i);
dataSize += req->options.transaction->getTxnId().size();
PUSH_STATIC_BUFFER("\r\n");
}
PUSH_STATIC_BUFFER("\r\n");
nbuffers = i;
return true;
#undef BEGIN_PUSH_NEXT_BUFFER
#undef INC_BUFFER_ITER
#undef PUSH_STATIC_BUFFER
}
bool
Controller::sendHeaderToAppWithHttpProtocolAndWritev(Request *req, ssize_t &bytesWritten,
HttpHeaderConstructionCache &cache)
{
unsigned int maxbuffers = std::min<unsigned int>(
5 + req->headers.size() * 4 + 4, IOV_MAX);
struct iovec *buffers = (struct iovec *) psg_palloc(req->pool,
sizeof(struct iovec) * maxbuffers);
unsigned int nbuffers, dataSize;
if (constructHeaderBuffersForHttpProtocol(req, buffers,
maxbuffers, nbuffers, dataSize, cache))
{
ssize_t ret;
do {
ret = writev(req->session->fd(), buffers, nbuffers);
} while (ret == -1 && errno == EINTR);
bytesWritten = ret;
return ret == (ssize_t) dataSize;
} else {
bytesWritten = 0;
return false;
}
}
void
Controller::sendHeaderToAppWithHttpProtocolWithBuffering(Request *req,
unsigned int offset, HttpHeaderConstructionCache &cache)
{
struct iovec *buffers;
unsigned int nbuffers, dataSize;
bool ok;
ok = constructHeaderBuffersForHttpProtocol(req, NULL, 0, nbuffers,
dataSize, cache);
assert(ok);
buffers = (struct iovec *) psg_palloc(req->pool,
sizeof(struct iovec) * nbuffers);
ok = constructHeaderBuffersForHttpProtocol(req, buffers, nbuffers,
nbuffers, dataSize, cache);
assert(ok);
(void) ok; // Shut up compiler warning
MemoryKit::mbuf_pool &mbuf_pool = getContext()->mbuf_pool;
const unsigned int MBUF_MAX_SIZE = mbuf_pool_data_size(&mbuf_pool);
if (dataSize <= MBUF_MAX_SIZE) {
MemoryKit::mbuf buffer(MemoryKit::mbuf_get(&mbuf_pool));
gatherBuffers(buffer.start, MBUF_MAX_SIZE, buffers, nbuffers);
buffer = MemoryKit::mbuf(buffer, offset, dataSize - offset);
req->appSink.feedWithoutRefGuard(boost::move(buffer));
} else {
char *buffer = (char *) psg_pnalloc(req->pool, dataSize);
gatherBuffers(buffer, dataSize, buffers, nbuffers);
req->appSink.feedWithoutRefGuard(MemoryKit::mbuf(
buffer + offset, dataSize - offset));
}
}
void
Controller::sendBodyToApp(Client *client, Request *req) {
TRACE_POINT();
assert(req->appSink.acceptingInput());
#ifdef DEBUG_CC_EVENT_LOOP_BLOCKING
req->timeOnRequestHeaderSent = ev_now(getLoop());
reportLargeTimeDiff(client,
"ApplicationPool get until headers sent",
req->timeBeforeAccessingApplicationPool,
req->timeOnRequestHeaderSent);
#endif
if (req->hasBody() || req->upgraded()) {
// onRequestBody() will take care of forwarding
// the request body to the app.
SKC_TRACE(client, 2, "Sending body to application");
req->state = Request::FORWARDING_BODY_TO_APP;
startBodyChannel(client, req);
} else {
// Our task is done. ForwardResponse.cpp will take
// care of ending the request, once all response
// data is forwarded.
SKC_TRACE(client, 2, "No body to send to application");
req->state = Request::WAITING_FOR_APP_OUTPUT;
halfCloseAppSink(client, req);
}
}
void
Controller::halfCloseAppSink(Client *client, Request *req) {
P_ASSERT_EQ(req->state, Request::WAITING_FOR_APP_OUTPUT);
if (req->halfCloseAppConnection) {
SKC_TRACE(client, 3, "Half-closing application socket with SHUT_WR");
::shutdown(req->session->fd(), SHUT_WR);
}
}
ServerKit::Channel::Result
Controller::whenSendingRequest_onRequestBody(Client *client, Request *req,
const MemoryKit::mbuf &buffer, int errcode)
{
TRACE_POINT();
if (buffer.size() > 0) {
// Data
if (req->bodyType == Request::RBT_CONTENT_LENGTH) {
SKC_TRACE(client, 3, "Forwarding " << buffer.size() <<
" bytes of client request body (" << req->bodyAlreadyRead <<
" of " << req->aux.bodyInfo.contentLength << " bytes forwarded in total): \"" <<
cEscapeString(StaticString(buffer.start, buffer.size())) <<
"\"");
} else {
SKC_TRACE(client, 3, "Forwarding " << buffer.size() <<
" bytes of client request body (" << req->bodyAlreadyRead <<
" bytes forwarded in total): \"" <<
cEscapeString(StaticString(buffer.start, buffer.size())) <<
"\"");
}
req->appSink.feed(buffer);
if (!req->appSink.acceptingInput()) {
if (req->appSink.mayAcceptInputLater()) {
SKC_TRACE(client, 3, "Waiting for appSink channel to become "
"idle before continuing sending body to application");
req->appSink.setConsumedCallback(resumeRequestBodyChannelWhenAppSinkIdle);
stopBodyChannel(client, req);
return Channel::Result(buffer.size(), false);
} else {
// Either we're done feeding to req->appSink, or req->appSink.feed()
// encountered an error while writing to the application socket.
// But we don't care about either scenarios; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
assert(!req->ended());
assert(req->appSink.hasError());
logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
stopBodyChannel(client, req);
}
}
return Channel::Result(buffer.size(), false);
} else if (errcode == 0 || errcode == ECONNRESET) {
// EOF
SKC_TRACE(client, 2, "End of request body encountered");
// Our task is done. ForwardResponse.cpp will take
// care of ending the request, once all response
// data is forwarded.
req->state = Request::WAITING_FOR_APP_OUTPUT;
halfCloseAppSink(client, req);
return Channel::Result(0, true);
} else {
const unsigned int BUFSIZE = 1024;
char *message = (char *) psg_pnalloc(req->pool, BUFSIZE);
int size = snprintf(message, BUFSIZE,
"error reading request body: %s (errno=%d)",
ServerKit::getErrorDesc(errcode), errcode);
disconnectWithError(&client, StaticString(message, size));
return Channel::Result(0, true);
}
}
void
Controller::resumeRequestBodyChannelWhenAppSinkIdle(Channel *_channel,
unsigned int size)
{
FdSinkChannel *channel = reinterpret_cast<FdSinkChannel *>(_channel);
Request *req = static_cast<Request *>(static_cast<
ServerKit::BaseHttpRequest *>(channel->getHooks()->userData));
Client *client = static_cast<Client *>(req->client);
Controller *self = static_cast<Controller *>(getServerFromClient(client));
SKC_LOG_EVENT_FROM_STATIC(self, Controller, client, "resumeRequestBodyChannelWhenAppSinkIdle");
P_ASSERT_EQ(req->state, Request::FORWARDING_BODY_TO_APP);
req->appSink.setConsumedCallback(NULL);
if (req->appSink.acceptingInput()) {
self->startBodyChannel(client, req);
} else {
// Either we're done feeding to req->appSink, or req->appSink.feed()
// encountered an error while writing to the application socket.
// But we don't care about either scenarios; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
assert(!req->ended());
assert(req->appSink.hasError());
self->logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
}
}
void
Controller::startBodyChannel(Client *client, Request *req) {
if (req->requestBodyBuffering) {
req->bodyBuffer.start();
} else {
req->bodyChannel.start();
}
}
void
Controller::stopBodyChannel(Client *client, Request *req) {
if (req->requestBodyBuffering) {
req->bodyBuffer.stop();
} else {
req->bodyChannel.stop();
}
}
void
Controller::logAppSocketWriteError(Client *client, int errcode) {
if (errcode == EPIPE) {
SKC_INFO(client,
"App socket write error: the application closed the socket prematurely"
" (Broken pipe; errno=" << errcode << ")");
} else {
SKC_INFO(client, "App socket write error: " << ServerKit::getErrorDesc(errcode) <<
" (errno=" << errcode << ")");
}
}
} // namespace Core
} // namespace Passenger
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1749_1 |
crossvul-cpp_data_good_3853_0 | /* +------------------------------------+
* | Inspire Internet Relay Chat Daemon |
* +------------------------------------+
*
* InspIRCd: (C) 2002-2010 InspIRCd Development Team
* See: http://wiki.inspircd.org/Credits
*
* This program is free but copyrighted software; see
* the file COPYING for details.
*
* ---------------------------------------------------
*/
/* $Core */
/*
dns.cpp - Nonblocking DNS functions.
Very very loosely based on the firedns library,
Copyright (C) 2002 Ian Gulliver. This file is no
longer anything like firedns, there are many major
differences between this code and the original.
Please do not assume that firedns works like this,
looks like this, walks like this or tastes like this.
*/
#ifndef WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#include "inspircd_win32wrapper.h"
#endif
#include "inspircd.h"
#include "socketengine.h"
#include "configreader.h"
#include "socket.h"
#define DN_COMP_BITMASK 0xC000 /* highest 6 bits in a DN label header */
/** Masks to mask off the responses we get from the DNSRequest methods
*/
enum QueryInfo
{
ERROR_MASK = 0x10000 /* Result is an error */
};
/** Flags which can be ORed into a request or reply for different meanings
*/
enum QueryFlags
{
FLAGS_MASK_RD = 0x01, /* Recursive */
FLAGS_MASK_TC = 0x02,
FLAGS_MASK_AA = 0x04, /* Authoritative */
FLAGS_MASK_OPCODE = 0x78,
FLAGS_MASK_QR = 0x80,
FLAGS_MASK_RCODE = 0x0F, /* Request */
FLAGS_MASK_Z = 0x70,
FLAGS_MASK_RA = 0x80
};
/** Represents a dns resource record (rr)
*/
struct ResourceRecord
{
QueryType type; /* Record type */
unsigned int rr_class; /* Record class */
unsigned long ttl; /* Time to live */
unsigned int rdlength; /* Record length */
};
/** Represents a dns request/reply header, and its payload as opaque data.
*/
class DNSHeader
{
public:
unsigned char id[2]; /* Request id */
unsigned int flags1; /* Flags */
unsigned int flags2; /* Flags */
unsigned int qdcount;
unsigned int ancount; /* Answer count */
unsigned int nscount; /* Nameserver count */
unsigned int arcount;
unsigned char payload[512]; /* Packet payload */
};
class DNSRequest
{
public:
unsigned char id[2]; /* Request id */
unsigned char* res; /* Result processing buffer */
unsigned int rr_class; /* Request class */
QueryType type; /* Request type */
DNS* dnsobj; /* DNS caller (where we get our FD from) */
unsigned long ttl; /* Time to live */
std::string orig; /* Original requested name/ip */
DNSRequest(DNS* dns, int id, const std::string &original);
~DNSRequest();
DNSInfo ResultIsReady(DNSHeader &h, unsigned length);
int SendRequests(const DNSHeader *header, const int length, QueryType qt);
};
class CacheTimer : public Timer
{
private:
DNS* dns;
public:
CacheTimer(DNS* thisdns)
: Timer(3600, ServerInstance->Time(), true), dns(thisdns) { }
virtual void Tick(time_t)
{
dns->PruneCache();
}
};
class RequestTimeout : public Timer
{
DNSRequest* watch;
int watchid;
public:
RequestTimeout(unsigned long n, DNSRequest* watching, int id) : Timer(n, ServerInstance->Time()), watch(watching), watchid(id)
{
}
~RequestTimeout()
{
if (ServerInstance->Res)
Tick(0);
}
void Tick(time_t)
{
if (ServerInstance->Res->requests[watchid] == watch)
{
/* Still exists, whack it */
if (ServerInstance->Res->Classes[watchid])
{
ServerInstance->Res->Classes[watchid]->OnError(RESOLVER_TIMEOUT, "Request timed out");
delete ServerInstance->Res->Classes[watchid];
ServerInstance->Res->Classes[watchid] = NULL;
}
ServerInstance->Res->requests[watchid] = NULL;
delete watch;
}
}
};
CachedQuery::CachedQuery(const std::string &res, unsigned int ttl) : data(res)
{
expires = ServerInstance->Time() + ttl;
}
int CachedQuery::CalcTTLRemaining()
{
int n = expires - ServerInstance->Time();
return (n < 0 ? 0 : n);
}
/* Allocate the processing buffer */
DNSRequest::DNSRequest(DNS* dns, int rid, const std::string &original) : dnsobj(dns)
{
/* hardening against overflow here: make our work buffer twice the theoretical
* maximum size so that hostile input doesn't screw us over.
*/
res = new unsigned char[sizeof(DNSHeader) * 2];
*res = 0;
orig = original;
RequestTimeout* RT = new RequestTimeout(ServerInstance->Config->dns_timeout ? ServerInstance->Config->dns_timeout : 5, this, rid);
ServerInstance->Timers->AddTimer(RT); /* The timer manager frees this */
}
/* Deallocate the processing buffer */
DNSRequest::~DNSRequest()
{
delete[] res;
}
/** Fill a ResourceRecord class based on raw data input */
inline void DNS::FillResourceRecord(ResourceRecord* rr, const unsigned char *input)
{
rr->type = (QueryType)((input[0] << 8) + input[1]);
rr->rr_class = (input[2] << 8) + input[3];
rr->ttl = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + input[7];
rr->rdlength = (input[8] << 8) + input[9];
}
/** Fill a DNSHeader class based on raw data input of a given length */
inline void DNS::FillHeader(DNSHeader *header, const unsigned char *input, const int length)
{
header->id[0] = input[0];
header->id[1] = input[1];
header->flags1 = input[2];
header->flags2 = input[3];
header->qdcount = (input[4] << 8) + input[5];
header->ancount = (input[6] << 8) + input[7];
header->nscount = (input[8] << 8) + input[9];
header->arcount = (input[10] << 8) + input[11];
memcpy(header->payload,&input[12],length);
}
/** Empty a DNSHeader class out into raw data, ready for transmission */
inline void DNS::EmptyHeader(unsigned char *output, const DNSHeader *header, const int length)
{
output[0] = header->id[0];
output[1] = header->id[1];
output[2] = header->flags1;
output[3] = header->flags2;
output[4] = header->qdcount >> 8;
output[5] = header->qdcount & 0xFF;
output[6] = header->ancount >> 8;
output[7] = header->ancount & 0xFF;
output[8] = header->nscount >> 8;
output[9] = header->nscount & 0xFF;
output[10] = header->arcount >> 8;
output[11] = header->arcount & 0xFF;
memcpy(&output[12],header->payload,length);
}
/** Send requests we have previously built down the UDP socket */
int DNSRequest::SendRequests(const DNSHeader *header, const int length, QueryType qt)
{
ServerInstance->Logs->Log("RESOLVER", DEBUG,"DNSRequest::SendRequests");
unsigned char payload[sizeof(DNSHeader)];
this->rr_class = 1;
this->type = qt;
DNS::EmptyHeader(payload,header,length);
if (ServerInstance->SE->SendTo(dnsobj, payload, length + 12, 0, &(dnsobj->myserver.sa), sa_size(dnsobj->myserver)) != length+12)
return -1;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Sent OK");
return 0;
}
/** Add a query with a predefined header, and allocate an ID for it. */
DNSRequest* DNS::AddQuery(DNSHeader *header, int &id, const char* original)
{
/* Is the DNS connection down? */
if (this->GetFd() == -1)
return NULL;
/* Create an id */
do {
id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
} while (requests[id]);
DNSRequest* req = new DNSRequest(this, id, original);
header->id[0] = req->id[0] = id >> 8;
header->id[1] = req->id[1] = id & 0xFF;
header->flags1 = FLAGS_MASK_RD;
header->flags2 = 0;
header->qdcount = 1;
header->ancount = 0;
header->nscount = 0;
header->arcount = 0;
/* At this point we already know the id doesnt exist,
* so there needs to be no second check for the ::end()
*/
requests[id] = req;
/* According to the C++ spec, new never returns NULL. */
return req;
}
int DNS::ClearCache()
{
/* This ensures the buckets are reset to sane levels */
int rv = this->cache->size();
delete this->cache;
this->cache = new dnscache();
return rv;
}
int DNS::PruneCache()
{
int n = 0;
dnscache* newcache = new dnscache();
for (dnscache::iterator i = this->cache->begin(); i != this->cache->end(); i++)
/* Dont include expired items (theres no point) */
if (i->second.CalcTTLRemaining())
newcache->insert(*i);
else
n++;
delete this->cache;
this->cache = newcache;
return n;
}
void DNS::Rehash()
{
if (this->GetFd() > -1)
{
ServerInstance->SE->DelFd(this);
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
/* Rehash the cache */
this->PruneCache();
}
else
{
/* Create initial dns cache */
this->cache = new dnscache();
}
irc::sockets::aptosa(ServerInstance->Config->DNSServer, DNS::QUERY_PORT, myserver);
/* Initialize mastersocket */
int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
this->SetFd(s);
/* Have we got a socket and is it nonblocking? */
if (this->GetFd() != -1)
{
ServerInstance->SE->SetReuse(s);
ServerInstance->SE->NonBlocking(s);
irc::sockets::sockaddrs bindto;
memset(&bindto, 0, sizeof(bindto));
bindto.sa.sa_family = myserver.sa.sa_family;
if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0)
{
/* Failed to bind */
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error binding dns socket - hostnames will NOT resolve");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Internal error starting DNS - hostnames will NOT resolve.");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
}
else
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error creating DNS socket - hostnames will NOT resolve");
}
}
/** Initialise the DNS UDP socket so that we can send requests */
DNS::DNS()
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::DNS");
/* Clear the Resolver class table */
memset(Classes,0,sizeof(Classes));
/* Clear the requests class table */
memset(requests,0,sizeof(requests));
/* Set the id of the next request to 0
*/
currid = 0;
/* DNS::Rehash() sets this to a valid ptr
*/
this->cache = NULL;
/* Again, DNS::Rehash() sets this to a
* valid value
*/
this->SetFd(-1);
/* Actually read the settings
*/
this->Rehash();
this->PruneTimer = new CacheTimer(this);
ServerInstance->Timers->AddTimer(this->PruneTimer);
}
/** Build a payload to be placed after the header, based upon input data, a resource type, a class and a pointer to a buffer */
int DNS::MakePayload(const char * const name, const QueryType rr, const unsigned short rr_class, unsigned char * const payload)
{
short payloadpos = 0;
const char* tempchr, *tempchr2 = name;
unsigned short length;
/* split name up into labels, create query */
while ((tempchr = strchr(tempchr2,'.')) != NULL)
{
length = tempchr - tempchr2;
if (payloadpos + length + 1 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
tempchr2 = &tempchr[1];
}
length = strlen(tempchr2);
if (length)
{
if (payloadpos + length + 2 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
payload[payloadpos++] = 0;
}
if (payloadpos > 508)
return -1;
length = htons(rr);
memcpy(&payload[payloadpos],&length,2);
length = htons(rr_class);
memcpy(&payload[payloadpos + 2],&length,2);
return payloadpos + 4;
}
/** Start lookup of an hostname to an IP address */
int DNS::GetIP(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_A, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_A) == -1))
return -1;
return id;
}
/** Start lookup of an hostname to an IPv6 address */
int DNS::GetIP6(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_AAAA, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_AAAA) == -1))
return -1;
return id;
}
/** Start lookup of a cname to another name */
int DNS::GetCName(const char *alias)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(alias, DNS_QUERY_CNAME, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, alias);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_CNAME) == -1))
return -1;
return id;
}
/** Start lookup of an IP address to a hostname */
int DNS::GetNameForce(const char *ip, ForceProtocol fp)
{
char query[128];
DNSHeader h;
int id;
int length;
if (fp == PROTOCOL_IPV6)
{
in6_addr i;
if (inet_pton(AF_INET6, ip, &i) > 0)
{
DNS::MakeIP6Int(query, &i);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv6 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
else
{
in_addr i;
if (inet_aton(ip, &i))
{
unsigned char* c = (unsigned char*)&i.s_addr;
sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv4 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
length = this->MakePayload(query, DNS_QUERY_PTR, 1, (unsigned char*)&h.payload);
if (length == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't query '%s' using '%s' because it's too long", ip, query);
return -1;
}
DNSRequest* req = this->AddQuery(&h, id, ip);
if (!req)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't add query (resolver down?)");
return -1;
}
if (req->SendRequests(&h, length, DNS_QUERY_PTR) == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't send (firewall?)");
return -1;
}
return id;
}
/** Build an ipv6 reverse domain from an in6_addr
*/
void DNS::MakeIP6Int(char* query, const in6_addr *ip)
{
const char* hex = "0123456789abcdef";
for (int index = 31; index >= 0; index--) /* for() loop steps twice per byte */
{
if (index % 2)
/* low nibble */
*query++ = hex[ip->s6_addr[index / 2] & 0x0F];
else
/* high nibble */
*query++ = hex[(ip->s6_addr[index / 2] & 0xF0) >> 4];
*query++ = '.'; /* Seperator */
}
strcpy(query,"ip6.arpa"); /* Suffix the string */
}
/** Return the next id which is ready, and the result attached to it */
DNSResult DNS::GetResult()
{
/* Fetch dns query response and decide where it belongs */
DNSHeader header;
DNSRequest *req;
unsigned char buffer[sizeof(DNSHeader)];
irc::sockets::sockaddrs from;
memset(&from, 0, sizeof(from));
socklen_t x = sizeof(from);
int length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x);
/* Did we get the whole header? */
if (length < 12)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"GetResult didn't get a full packet (len=%d)", length);
/* Nope - something screwed up. */
return DNSResult(-1,"",0,"");
}
/* Check wether the reply came from a different DNS
* server to the one we sent it to, or the source-port
* is not 53.
* A user could in theory still spoof dns packets anyway
* but this is less trivial than just sending garbage
* to the server, which is possible without this check.
*
* -- Thanks jilles for pointing this one out.
*/
if (from != myserver)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
from.str().c_str(), myserver.str().c_str());
return DNSResult(-1,"",0,"");
}
/* Put the read header info into a header class */
DNS::FillHeader(&header,buffer,length - 12);
/* Get the id of this request.
* Its a 16 bit value stored in two char's,
* so we use logic shifts to create the value.
*/
unsigned long this_id = header.id[1] + (header.id[0] << 8);
/* Do we have a pending request matching this id? */
if (!requests[this_id])
{
/* Somehow we got a DNS response for a request we never made... */
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.", this_id);
return DNSResult(-1,"",0,"");
}
else
{
/* Remove the query from the list of pending queries */
req = requests[this_id];
requests[this_id] = NULL;
}
/* Inform the DNSRequest class that it has a result to be read.
* When its finished it will return a DNSInfo which is a pair of
* unsigned char* resource record data, and an error message.
*/
DNSInfo data = req->ResultIsReady(header, length);
std::string resultstr;
/* Check if we got a result, if we didnt, its an error */
if (data.first == NULL)
{
/* An error.
* Mask the ID with the value of ERROR_MASK, so that
* the dns_deal_with_classes() function knows that its
* an error response and needs to be treated uniquely.
* Put the error message in the second field.
*/
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, data.second, 0, ro);
}
else
{
unsigned long ttl = req->ttl;
char formatted[128];
/* Forward lookups come back as binary data. We must format them into ascii */
switch (req->type)
{
case DNS_QUERY_A:
snprintf(formatted,16,"%u.%u.%u.%u",data.first[0],data.first[1],data.first[2],data.first[3]);
resultstr = formatted;
break;
case DNS_QUERY_AAAA:
{
inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted));
char* c = strstr(formatted,":0:");
if (c != NULL)
{
memmove(c+1,c+2,strlen(c+2) + 1);
c += 2;
while (memcmp(c,"0:",2) == 0)
memmove(c,c+2,strlen(c+2) + 1);
if (memcmp(c,"0",2) == 0)
*c = 0;
if (memcmp(formatted,"0::",3) == 0)
memmove(formatted,formatted + 1, strlen(formatted + 1) + 1);
}
resultstr = formatted;
/* Special case. Sending ::1 around between servers
* and to clients is dangerous, because the : on the
* start makes the client or server interpret the IP
* as the last parameter on the line with a value ":1".
*/
if (*formatted == ':')
resultstr.insert(0, "0");
}
break;
case DNS_QUERY_CNAME:
/* Identical handling to PTR */
case DNS_QUERY_PTR:
/* Reverse lookups just come back as char* */
resultstr = std::string((const char*)data.first);
break;
default:
break;
}
/* Build the reply with the id and hostname/ip in it */
std::string ro = req->orig;
delete req;
return DNSResult(this_id,resultstr,ttl,ro);
}
}
/** A result is ready, process it */
DNSInfo DNSRequest::ResultIsReady(DNSHeader &header, unsigned length)
{
unsigned i = 0, o;
int q = 0;
int curanswer;
ResourceRecord rr;
unsigned short ptr;
/* This is just to keep _FORTIFY_SOURCE happy */
rr.type = DNS_QUERY_NONE;
rr.rdlength = 0;
rr.ttl = 1; /* GCC is a whiney bastard -- see the XXX below. */
rr.rr_class = 0; /* Same for VC++ */
if (!(header.flags1 & FLAGS_MASK_QR))
return std::make_pair((unsigned char*)NULL,"Not a query result");
if (header.flags1 & FLAGS_MASK_OPCODE)
return std::make_pair((unsigned char*)NULL,"Unexpected value in DNS reply packet");
if (header.flags2 & FLAGS_MASK_RCODE)
return std::make_pair((unsigned char*)NULL,"Domain name not found");
if (header.ancount < 1)
return std::make_pair((unsigned char*)NULL,"No resource records returned");
/* Subtract the length of the header from the length of the packet */
length -= 12;
while ((unsigned int)q < header.qdcount && i < length)
{
if (header.payload[i] > 63)
{
i += 6;
q++;
}
else
{
if (header.payload[i] == 0)
{
q++;
i += 5;
}
else i += header.payload[i] + 1;
}
}
curanswer = 0;
while ((unsigned)curanswer < header.ancount)
{
q = 0;
while (q == 0 && i < length)
{
if (header.payload[i] > 63)
{
i += 2;
q = 1;
}
else
{
if (header.payload[i] == 0)
{
i++;
q = 1;
}
else i += header.payload[i] + 1; /* skip length and label */
}
}
if (static_cast<int>(length - i) < 10)
return std::make_pair((unsigned char*)NULL,"Incorrectly sized DNS reply");
/* XXX: We actually initialise 'rr' here including its ttl field */
DNS::FillResourceRecord(&rr,&header.payload[i]);
i += 10;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver: rr.type is %d and this.type is %d rr.class %d this.class %d", rr.type, this->type, rr.rr_class, this->rr_class);
if (rr.type != this->type)
{
curanswer++;
i += rr.rdlength;
continue;
}
if (rr.rr_class != this->rr_class)
{
curanswer++;
i += rr.rdlength;
continue;
}
break;
}
if ((unsigned int)curanswer == header.ancount)
return std::make_pair((unsigned char*)NULL,"No A, AAAA or PTR type answers (" + ConvToStr(header.ancount) + " answers)");
if (i + rr.rdlength > (unsigned int)length)
return std::make_pair((unsigned char*)NULL,"Resource record larger than stated");
if (rr.rdlength > 1023)
return std::make_pair((unsigned char*)NULL,"Resource record too large");
this->ttl = rr.ttl;
switch (rr.type)
{
/*
* CNAME and PTR are compressed. We need to decompress them.
*/
case DNS_QUERY_CNAME:
case DNS_QUERY_PTR:
o = 0;
q = 0;
while (q == 0 && i < length && o + 256 < 1023)
{
/* DN label found (byte over 63) */
if (header.payload[i] > 63)
{
memcpy(&ptr,&header.payload[i],2);
i = ntohs(ptr);
/* check that highest two bits are set. if not, we've been had */
if (!(i & DN_COMP_BITMASK))
return std::make_pair((unsigned char *) NULL, "DN label decompression header is bogus");
/* mask away the two highest bits. */
i &= ~DN_COMP_BITMASK;
/* and decrease length by 12 bytes. */
i =- 12;
}
else
{
if (header.payload[i] == 0)
{
q = 1;
}
else
{
res[o] = 0;
if (o != 0)
res[o++] = '.';
if (o + header.payload[i] > sizeof(DNSHeader))
return std::make_pair((unsigned char *) NULL, "DN label decompression is impossible -- malformed/hostile packet?");
memcpy(&res[o], &header.payload[i + 1], header.payload[i]);
o += header.payload[i];
i += header.payload[i] + 1;
}
}
}
res[o] = 0;
break;
case DNS_QUERY_AAAA:
if (rr.rdlength != sizeof(struct in6_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 16 bytes for an ipv6 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
case DNS_QUERY_A:
if (rr.rdlength != sizeof(struct in_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 4 bytes for an ipv4 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
default:
return std::make_pair((unsigned char *) NULL, "don't know how to handle undefined type (" + ConvToStr(rr.type) + ") -- rejecting");
break;
}
return std::make_pair(res,"No error");
}
/** Close the master socket */
DNS::~DNS()
{
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
ServerInstance->Timers->DelTimer(this->PruneTimer);
if (cache)
delete cache;
}
CachedQuery* DNS::GetCache(const std::string &source)
{
dnscache::iterator x = cache->find(source.c_str());
if (x != cache->end())
return &(x->second);
else
return NULL;
}
void DNS::DelCache(const std::string &source)
{
cache->erase(source.c_str());
}
void Resolver::TriggerCachedResult()
{
if (CQ)
OnLookupComplete(CQ->data, time_left, true);
}
/** High level abstraction of dns used by application at large */
Resolver::Resolver(const std::string &source, QueryType qt, bool &cached, Module* creator) : Creator(creator), input(source), querytype(qt)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver::Resolver");
cached = false;
CQ = ServerInstance->Res->GetCache(source);
if (CQ)
{
time_left = CQ->CalcTTLRemaining();
if (!time_left)
{
ServerInstance->Res->DelCache(source);
}
else
{
cached = true;
return;
}
}
switch (querytype)
{
case DNS_QUERY_A:
this->myid = ServerInstance->Res->GetIP(source.c_str());
break;
case DNS_QUERY_PTR4:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV4);
break;
case DNS_QUERY_PTR6:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV6);
break;
case DNS_QUERY_AAAA:
this->myid = ServerInstance->Res->GetIP6(source.c_str());
break;
case DNS_QUERY_CNAME:
this->myid = ServerInstance->Res->GetCName(source.c_str());
break;
default:
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request with unknown query type %d", querytype);
this->myid = -1;
break;
}
if (this->myid == -1)
{
throw ModuleException("Resolver: Couldn't get an id to make a request");
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request id %d", this->myid);
}
}
/** Called when an error occurs */
void Resolver::OnError(ResolverError, const std::string&)
{
/* Nothing in here */
}
/** Destroy a resolver */
Resolver::~Resolver()
{
/* Nothing here (yet) either */
}
/** Get the request id associated with this class */
int Resolver::GetId()
{
return this->myid;
}
Module* Resolver::GetCreator()
{
return this->Creator;
}
/** Process a socket read event */
void DNS::HandleEvent(EventType, int)
{
/* Fetch the id and result of the next available packet */
DNSResult res(0,"",0,"");
res.id = 0;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Handle DNS event");
res = this->GetResult();
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Result id %d", res.id);
/* Is there a usable request id? */
if (res.id != -1)
{
/* Its an error reply */
if (res.id & ERROR_MASK)
{
/* Mask off the error bit */
res.id -= ERROR_MASK;
/* Marshall the error to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsBad++;
Classes[res.id]->OnError(RESOLVER_NXDOMAIN, res.result);
delete Classes[res.id];
Classes[res.id] = NULL;
}
return;
}
else
{
/* It is a non-error result, marshall the result to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsGood++;
if (!this->GetCache(res.original.c_str()))
this->cache->insert(std::make_pair(res.original.c_str(), CachedQuery(res.result, res.ttl)));
Classes[res.id]->OnLookupComplete(res.result, res.ttl, false);
delete Classes[res.id];
Classes[res.id] = NULL;
}
}
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDns++;
}
}
/** Add a derived Resolver to the working set */
bool DNS::AddResolverClass(Resolver* r)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"AddResolverClass 0x%08lx", (unsigned long)r);
/* Check the pointers validity and the id's validity */
if ((r) && (r->GetId() > -1))
{
/* Check the slot isnt already occupied -
* This should NEVER happen unless we have
* a severely broken DNS server somewhere
*/
if (!Classes[r->GetId()])
{
/* Set up the pointer to the class */
Classes[r->GetId()] = r;
return true;
}
else
/* Duplicate id */
return false;
}
else
{
/* Pointer or id not valid.
* Free the item and return
*/
if (r)
delete r;
return false;
}
}
void DNS::CleanResolvers(Module* module)
{
for (int i = 0; i < MAX_REQUEST_ID; i++)
{
if (Classes[i])
{
if (Classes[i]->GetCreator() == module)
{
Classes[i]->OnError(RESOLVER_FORCEUNLOAD, "Parent module is unloading");
delete Classes[i];
Classes[i] = NULL;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_3853_0 |
crossvul-cpp_data_bad_1442_4 | /*
* Copyright (C) 2004-2016 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "znctest.h"
namespace znc_inttest {
namespace {
TEST_F(ZNCTest, Modperl) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod perleval");
client.Write("PRIVMSG *perleval :2+2");
client.ReadUntil(":*perleval!znc@znc.in PRIVMSG nick :Result: 4");
client.Write("PRIVMSG *perleval :$self->GetUser->GetUserName");
client.ReadUntil("Result: user");
}
TEST_F(ZNCTest, Modpython) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod pyeval");
client.Write("PRIVMSG *pyeval :2+2");
client.ReadUntil(":*pyeval!znc@znc.in PRIVMSG nick :4");
client.Write("PRIVMSG *pyeval :module.GetUser().GetUserName()");
client.ReadUntil("nick :'user'");
ircd.Write(":server 001 nick :Hello");
ircd.Write(":n!u@h PRIVMSG nick :Hi\xF0, github issue #1229");
// "replacement character"
client.ReadUntil("Hi\xEF\xBF\xBD, github issue");
}
TEST_F(ZNCTest, ModpythonSocket) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("socktest.py", R"(
import znc
class acc(znc.Socket):
def OnReadData(self, data):
self.GetModule().PutModule('received {} bytes'.format(len(data)))
self.Close()
class lis(znc.Socket):
def OnAccepted(self, host, port):
sock = self.GetModule().CreateSocket(acc)
sock.DisableReadLine()
return sock
class socktest(znc.Module):
def OnLoad(self, args, ret):
listen = self.CreateSocket(lis)
self.port = listen.Listen()
return True
def OnModCommand(self, cmd):
sock = self.CreateSocket()
sock.Connect('127.0.0.1', self.port)
sock.WriteBytes(b'blah')
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod socktest");
client.Write("PRIVMSG *socktest :foo");
client.ReadUntil("received 4 bytes");
}
TEST_F(ZNCTest, ModperlSocket) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("socktest.pm", R"(
package socktest::acc;
use base 'ZNC::Socket';
sub OnReadData {
my ($self, $data, $len) = @_;
$self->GetModule->PutModule("received $len bytes");
$self->Close;
}
package socktest::lis;
use base 'ZNC::Socket';
sub OnAccepted {
my $self = shift;
return $self->GetModule->CreateSocket('socktest::acc');
}
package socktest::conn;
use base 'ZNC::Socket';
package socktest;
use base 'ZNC::Module';
sub OnLoad {
my $self = shift;
my $listen = $self->CreateSocket('socktest::lis');
$self->{port} = $listen->Listen;
return 1;
}
sub OnModCommand {
my ($self, $cmd) = @_;
my $sock = $self->CreateSocket('socktest::conn');
$sock->Connect('127.0.0.1', $self->{port});
$sock->Write('blah');
}
1;
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod socktest");
client.Write("PRIVMSG *socktest :foo");
client.ReadUntil("received 4 bytes");
}
TEST_F(ZNCTest, ModpythonVCString) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("test.py", R"(
import znc
class test(znc.Module):
def OnUserRawMessage(self, msg):
self.PutModule(str(msg.GetParams()))
return znc.CONTINUE
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod test");
client.Write("PRIVMSG *test :foo");
client.ReadUntil("'*test', 'foo'");
}
TEST_F(ZNCTest, ModperlVCString) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("test.pm", R"(
package test;
use base 'ZNC::Module';
sub OnUserRawMessage {
my ($self, $msg) = @_;
my @params = $msg->GetParams;
$self->PutModule("@params");
return $ZNC::CONTINUE;
}
1;
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod test");
client.Write("PRIVMSG *test :foo");
client.ReadUntil(":*test foo");
}
TEST_F(ZNCTest, ModperlNV) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
InstallModule("test.pm", R"(
package test;
use base 'ZNC::Module';
sub OnLoad {
my $self = shift;
$self->SetNV('a', 'X');
$self->NV->{b} = 'Y';
my @k = keys %{$self->NV};
$self->PutModule("@k");
return $ZNC::CONTINUE;
}
1;
)");
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modperl");
client.Write("znc loadmod test");
client.ReadUntil(":a b");
}
} // namespace
} // namespace znc_inttest
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1442_4 |
crossvul-cpp_data_bad_4220_2 | /* -*- C++ -*-
* Copyright 2019-2020 LibRaw LLC (info@libraw.org)
*
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
*/
#include "../../internal/libraw_cxx_defs.h"
libraw_processed_image_t *LibRaw::dcraw_make_mem_thumb(int *errcode)
{
if (!T.thumb)
{
if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
load_raw == &LibRaw::broadcom_load_raw) // RPi
)
{
if (errcode)
*errcode = LIBRAW_NO_THUMBNAIL;
}
else
{
if (errcode)
*errcode = LIBRAW_OUT_OF_ORDER_CALL;
}
return NULL;
}
if (T.tformat == LIBRAW_THUMBNAIL_BITMAP)
{
libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(
sizeof(libraw_processed_image_t) + T.tlength);
if (!ret)
{
if (errcode)
*errcode = ENOMEM;
return NULL;
}
memset(ret, 0, sizeof(libraw_processed_image_t));
ret->type = LIBRAW_IMAGE_BITMAP;
ret->height = T.theight;
ret->width = T.twidth;
ret->colors = 3;
ret->bits = 8;
ret->data_size = T.tlength;
memmove(ret->data, T.thumb, T.tlength);
if (errcode)
*errcode = 0;
return ret;
}
else if (T.tformat == LIBRAW_THUMBNAIL_JPEG)
{
ushort exif[5];
int mk_exif = 0;
if (strcmp(T.thumb + 6, "Exif"))
mk_exif = 1;
int dsize = T.tlength + mk_exif * (sizeof(exif) + sizeof(tiff_hdr));
libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(
sizeof(libraw_processed_image_t) + dsize);
if (!ret)
{
if (errcode)
*errcode = ENOMEM;
return NULL;
}
memset(ret, 0, sizeof(libraw_processed_image_t));
ret->type = LIBRAW_IMAGE_JPEG;
ret->data_size = dsize;
ret->data[0] = 0xff;
ret->data[1] = 0xd8;
if (mk_exif)
{
struct tiff_hdr th;
memcpy(exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons(8 + sizeof th);
memmove(ret->data + 2, exif, sizeof(exif));
tiff_head(&th, 0);
memmove(ret->data + (2 + sizeof(exif)), &th, sizeof(th));
memmove(ret->data + (2 + sizeof(exif) + sizeof(th)), T.thumb + 2,
T.tlength - 2);
}
else
{
memmove(ret->data + 2, T.thumb + 2, T.tlength - 2);
}
if (errcode)
*errcode = 0;
return ret;
}
else
{
if (errcode)
*errcode = LIBRAW_UNSUPPORTED_THUMBNAIL;
return NULL;
}
}
// jlb
// macros for copying pixels to either BGR or RGB formats
#define FORBGR for (c = P1.colors - 1; c >= 0; c--)
#define FORRGB for (c = 0; c < P1.colors; c++)
void LibRaw::get_mem_image_format(int *width, int *height, int *colors,
int *bps) const
{
*width = S.width;
*height = S.height;
if (imgdata.progress_flags < LIBRAW_PROGRESS_FUJI_ROTATE)
{
if (O.use_fuji_rotate)
{
if (IO.fuji_width)
{
int fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink;
*width = (ushort)(fuji_width / sqrt(0.5));
*height = (ushort)((*height - fuji_width) / sqrt(0.5));
}
else
{
if (S.pixel_aspect < 0.995)
*height = (ushort)(*height / S.pixel_aspect + 0.5);
if (S.pixel_aspect > 1.005)
*width = (ushort)(*width * S.pixel_aspect + 0.5);
}
}
}
if (S.flip & 4)
{
std::swap(*width, *height);
}
*colors = P1.colors;
*bps = O.output_bps;
}
int LibRaw::copy_mem_image(void *scan0, int stride, int bgr)
{
// the image memory pointed to by scan0 is assumed to be in the format
// returned by get_mem_image_format
if ((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) <
LIBRAW_PROGRESS_PRE_INTERPOLATE)
return LIBRAW_OUT_OF_ORDER_CALL;
if (libraw_internal_data.output_data.histogram)
{
int perc, val, total, t_white = 0x2000, c;
perc = S.width * S.height * O.auto_bright_thr;
if (IO.fuji_width)
perc /= 2;
if (!((O.highlight & ~2) || O.no_auto_bright))
for (t_white = c = 0; c < P1.colors; c++)
{
for (val = 0x2000, total = 0; --val > 32;)
if ((total += libraw_internal_data.output_data.histogram[c][val]) >
perc)
break;
if (t_white < val)
t_white = val;
}
gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright);
}
int s_iheight = S.iheight;
int s_iwidth = S.iwidth;
int s_width = S.width;
int s_hwight = S.height;
S.iheight = S.height;
S.iwidth = S.width;
if (S.flip & 4)
SWAP(S.height, S.width);
uchar *ppm;
ushort *ppm2;
int c, row, col, soff, rstep, cstep;
soff = flip_index(0, 0);
cstep = flip_index(0, 1) - soff;
rstep = flip_index(1, 0) - flip_index(0, S.width);
for (row = 0; row < S.height; row++, soff += rstep)
{
uchar *bufp = ((uchar *)scan0) + row * stride;
ppm2 = (ushort *)(ppm = bufp);
// keep trivial decisions in the outer loop for speed
if (bgr)
{
if (O.output_bps == 8)
{
for (col = 0; col < S.width; col++, soff += cstep)
FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8;
}
else
{
for (col = 0; col < S.width; col++, soff += cstep)
FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]];
}
}
else
{
if (O.output_bps == 8)
{
for (col = 0; col < S.width; col++, soff += cstep)
FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8;
}
else
{
for (col = 0; col < S.width; col++, soff += cstep)
FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]];
}
}
// bufp += stride; // go to the next line
}
S.iheight = s_iheight;
S.iwidth = s_iwidth;
S.width = s_width;
S.height = s_hwight;
return 0;
}
#undef FORBGR
#undef FORRGB
libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode)
{
int width, height, colors, bps;
get_mem_image_format(&width, &height, &colors, &bps);
int stride = width * (bps / 8) * colors;
unsigned ds = height * stride;
libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(
sizeof(libraw_processed_image_t) + ds);
if (!ret)
{
if (errcode)
*errcode = ENOMEM;
return NULL;
}
memset(ret, 0, sizeof(libraw_processed_image_t));
// metadata init
ret->type = LIBRAW_IMAGE_BITMAP;
ret->height = height;
ret->width = width;
ret->colors = colors;
ret->bits = bps;
ret->data_size = ds;
copy_mem_image(ret->data, stride, 0);
return ret;
}
void LibRaw::dcraw_clear_mem(libraw_processed_image_t *p)
{
if (p)
::free(p);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_4220_2 |
crossvul-cpp_data_good_660_0 | /*
* The AFFLIB page abstraction.
* Distributed under the Berkeley 4-part license
*/
#include "affconfig.h"
#include "afflib.h"
#include "afflib_i.h"
/* af_read_sizes:
* Get the page sizes if they are set in the file.
*/
void af_read_sizes(AFFILE *af)
{
af_get_seg(af,AF_SECTORSIZE,&af->image_sectorsize,0,0);
if(af->image_sectorsize==0) af->image_sectorsize = 512; // reasonable default
if(af_get_seg(af,AF_PAGESIZE,&af->image_pagesize,0,0)){
af_get_seg(af,AF_SEGSIZE_D,&af->image_pagesize,0,0); // try old name
}
/* Read the badflag if it is present.
* Be sure to adjust badflag size to current sector size (which may have changed).
*/
if(af->badflag!=0) free(af->badflag);
af->badflag = (unsigned char *)malloc(af->image_sectorsize);
size_t sectorsize = af->image_sectorsize;
if(af_get_seg(af,AF_BADFLAG,0,af->badflag,(size_t *)§orsize)==0){
af->badflag_set = 1;
}
/* Read the image file segment if it is present.
* If it isn't, scan through the disk image to figure out the size of the disk image.
*/
if(af_get_segq(af,AF_IMAGESIZE,(int64_t *)&af->image_size)){
/* Calculate the imagesize by scanning all of the pages that are in
* the disk image and finding the highest page number.
* Then read that page to find the last allocated byte.
*/
char segname[AF_MAX_NAME_LEN];
size_t datalen = 0;
af_rewind_seg(af); // start at the beginning
int64_t highest_page_number = 0;
while(af_get_next_seg(af,segname,sizeof(segname),0,0,&datalen)==0){
if(segname[0]==0) continue; // ignore sector
int64_t pagenum = af_segname_page_number(segname);
if(pagenum > highest_page_number) highest_page_number = pagenum;
}
size_t highest_page_len = 0;
if(af_get_page(af,highest_page_number,0,&highest_page_len)==0){
af->image_size = af->image_pagesize * highest_page_number + highest_page_len;
}
}
af->image_size_in_file = af->image_size;
}
int af_page_size(AFFILE *af)
{
return af->image_pagesize;
}
int af_get_pagesize(AFFILE *af)
{
return af->image_pagesize;
}
/* af_set_sectorsize:
* Sets the sectorsize.
* Fails with -1 if imagesize >=0 unless these changes permitted
*/
int af_set_sectorsize(AFFILE *af,int sectorsize)
{
struct af_vnode_info vni;
af_vstat(af,&vni);
if(vni.changable_pagesize==0 && af->image_size>0){
errno = EINVAL;
return -1;
}
af->image_sectorsize =sectorsize;
if(af->badflag==0) af->badflag = (unsigned char *)malloc(sectorsize);
else af->badflag = (unsigned char *)realloc(af->badflag,sectorsize);
af->badflag_set = 0;
if(af_update_seg(af,AF_SECTORSIZE,sectorsize,0,0)){
if(errno != ENOTSUP) return -1;
}
return 0;
}
int af_get_sectorsize(AFFILE *af) // returns sector size
{
return af->image_sectorsize;
}
/*
* af_set_pagesize:
* Sets the pagesize. Fails with -1 if it can't be changed.
*/
int af_set_pagesize(AFFILE *af,uint32_t pagesize)
{
/* Allow the pagesize to be changed if it hasn't been set yet
* and if this format doesn't support metadata updating (which is the raw formats)
*/
struct af_vnode_info vni;
af_vstat(af,&vni);
if(vni.changable_pagesize==0 && af->image_size>0){
if(pagesize==af->image_pagesize) return 0; // it's already set to this, so let it pass
errno = EINVAL;
return -1;
}
if(pagesize % af->image_sectorsize != 0){
(*af->error_reporter)("Cannot set pagesize to %d (sectorsize=%d)\n",
pagesize,af->image_sectorsize);
errno = EINVAL;
return -1;
}
af->image_pagesize = pagesize;
if(af_update_seg(af,AF_PAGESIZE,pagesize,0,0)){
if(errno != ENOTSUP) return -1; // error updating (don't report ENOTSUP);
}
return 0;
}
/****************************************************************
*** page-level interface
****************************************************************/
int af_get_page_raw(AFFILE *af,int64_t pagenum,uint32_t *arg,
unsigned char *data,size_t *bytes)
{
char segname[AF_MAX_NAME_LEN];
memset(segname,0,sizeof(segname));
sprintf(segname,AF_PAGE,pagenum);
int r = af_get_seg(af,segname,arg,data,bytes);
if(r < 0 && errno == ENOENT)
{
/* Couldn't read with AF_PAGE; try AF_SEG_D.
* This is legacy for the old AFF files. Perhaps we should delete it.
*/
sprintf(segname,AF_SEG_D,pagenum);
r = af_get_seg(af,segname,arg,data,bytes);
}
/* Update the counters */
if(r==0 && bytes && *bytes>0) af->pages_read++; // note that we read a page
return r;
}
/* af_get_page:
* Get a page from its named segment.
* If the page is compressed, uncompress it.
* data points to a segmenet of at least *bytes;
* *bytes is then modified to indicate the actual amount of bytes read.
* Return 0 if success, -1 if fail.
*/
int af_get_page(AFFILE *af,int64_t pagenum,unsigned char *data,size_t *bytes)
{
uint32_t arg=0;
size_t page_len=0;
if (af_trace){
fprintf(af_trace,"af_get_page(%p,pagenum=%" I64d ",buf=%p,bytes=%u)\n",af,pagenum,data,(int)*bytes);
}
/* Find out the size of the segment and if it is compressed or not.
* If we can't find it with new nomenclature, try the old one...
*/
int r = af_get_page_raw(af,pagenum,&arg,0,&page_len);
if(r){
/* Segment doesn't exist.
* If we have been provided with a buffer,
* fill buffer with the 'bad segment' flag and return.
*/
if(data && (af->openmode & AF_BADBLOCK_FILL) && errno == ENOENT)
{
for(size_t i = 0;i <= af->image_pagesize - af->image_sectorsize;
i+= af->image_sectorsize){
memcpy(data+i,af->badflag,af->image_sectorsize);
af->bytes_memcpy += af->image_sectorsize;
}
r = 0;
}
return r; // segment doesn't exist
}
/* If the segment isn't compressed, just get it*/
uint32_t pageflag = 0;
if((arg & AF_PAGE_COMPRESSED)==0){
if(data==0){ // if no data provided, just return size of the segment if requested
if(bytes) *bytes = page_len; // set the number of bytes in the page if requested
return 0;
}
int ret = af_get_page_raw(af,pagenum,&pageflag,data,bytes);
if(*bytes > page_len) *bytes = page_len; // we only read this much
if(ret!=0) return ret; // some error happened?
}
else {
/* Allocate memory to hold the compressed segment */
unsigned char *compressed_data = (unsigned char *)malloc(page_len);
size_t compressed_data_len = page_len;
if(compressed_data==0){
return -2; // memory error
}
/* Get the data */
if(af_get_page_raw(af,pagenum,&pageflag,compressed_data,&compressed_data_len)){
free(compressed_data);
return -3; // read error
}
/* Sanity check to avoid undefined behaviour when calling malloc below with pagesize from a corrupt AFF image. */
if(af->image_pagesize <= 0 || af->image_pagesize > 16*1024*1024)
return -1;
/* Now uncompress directly into the buffer provided by the caller, unless the caller didn't
* provide a buffer. If that happens, allocate our own...
*/
int res = -1; // 0 is success
bool free_data = false;
if(data==0){
data = (unsigned char *)malloc(af->image_pagesize);
free_data = true;
*bytes = af->image_pagesize; // I can hold this much
}
switch((pageflag & AF_PAGE_COMP_ALG_MASK)){
case AF_PAGE_COMP_ALG_ZERO:
if(compressed_data_len != 4){
(*af->error_reporter)("ALG_ZERO compressed data is %d bytes, expected 4.",compressed_data_len);
break;
}
memset(data,0,af->image_pagesize);
*bytes = ntohl(*(long *)compressed_data);
res = 0; // not very hard to decompress with the ZERO compressor.
break;
case AF_PAGE_COMP_ALG_ZLIB:
res = uncompress(data,(uLongf *)bytes,compressed_data,compressed_data_len);
switch(res){
case Z_OK:
break;
case Z_ERRNO:
(*af->error_reporter)("Z_ERRNOR decompressing segment %" I64d,pagenum);
case Z_STREAM_ERROR:
(*af->error_reporter)("Z_STREAM_ERROR decompressing segment %" I64d,pagenum);
case Z_DATA_ERROR:
(*af->error_reporter)("Z_DATA_ERROR decompressing segment %" I64d,pagenum);
case Z_MEM_ERROR:
(*af->error_reporter)("Z_MEM_ERROR decompressing segment %" I64d,pagenum);
case Z_BUF_ERROR:
(*af->error_reporter)("Z_BUF_ERROR decompressing segment %" I64d,pagenum);
case Z_VERSION_ERROR:
(*af->error_reporter)("Z_VERSION_ERROR decompressing segment %" I64d,pagenum);
default:
(*af->error_reporter)("uncompress returned an invalid value in get_segment");
}
break;
#ifdef USE_LZMA
case AF_PAGE_COMP_ALG_LZMA:
res = lzma_uncompress(data,bytes,compressed_data,compressed_data_len);
if (af_trace) fprintf(af_trace," LZMA decompressed page %" I64d ". %d bytes => %u bytes\n",
pagenum,(int)compressed_data_len,(int)*bytes);
switch(res){
case 0:break; // OK
case 1:(*af->error_reporter)("LZMA header error decompressing segment %" I64d "\n",pagenum);
break;
case 2:(*af->error_reporter)("LZMA memory error decompressing segment %" I64d "\n",pagenum);
break;
}
break;
#endif
default:
(*af->error_reporter)("Unknown compression algorithm 0x%d",
pageflag & AF_PAGE_COMP_ALG_MASK);
break;
}
if(free_data){
free(data);
data = 0; // restore the way it was
}
free(compressed_data); // don't need this one anymore
af->pages_decompressed++;
if(res!=Z_OK) return -1;
}
/* If the page size is larger than the sector_size,
* make sure that the rest of the sector is zeroed, and that the
* rest after that has the 'bad block' notation.
*/
if(data && (af->image_pagesize > af->image_sectorsize)){
const int SECTOR_SIZE = af->image_sectorsize; // for ease of typing
size_t bytes_left_in_sector = (SECTOR_SIZE - (*bytes % SECTOR_SIZE)) % SECTOR_SIZE;
for(size_t i=0;i<bytes_left_in_sector;i++){
data[*bytes + i] = 0;
}
size_t end_of_data = *bytes + bytes_left_in_sector;
/* Now fill to the end of the page... */
for(size_t i = end_of_data; i <= af->image_pagesize-SECTOR_SIZE; i+=SECTOR_SIZE){
memcpy(data+i,af->badflag,SECTOR_SIZE);
af->bytes_memcpy += SECTOR_SIZE;
}
}
return 0;
}
static bool is_buffer_zero(unsigned char *buf,int buflen)
{
if(buflen >= (int)sizeof(long))
{
// align to word boundary
buflen -= (intptr_t)buf % sizeof(long);
while((intptr_t)buf % sizeof(long))
{
if(*buf++)
return false;
}
// read in words
long *ptr = (long*)buf;
buf += buflen - buflen % sizeof(long);
buflen %= sizeof(long);
while(ptr < (long*)buf)
{
if(*ptr++)
return false;
}
}
while(buflen--)
{
if(*buf++)
return false;
}
return true;
}
/* Write a actual data segment to the disk and sign if necessary. */
int af_update_page(AFFILE *af,int64_t pagenum,unsigned char *data,int datalen)
{
char segname_buf[32];
snprintf(segname_buf,sizeof(segname_buf),AF_PAGE,pagenum); // determine segment name
#ifdef USE_AFFSIGS
/* Write out the signature if we have a private key */
if(af->crypto && af->crypto->sign_privkey){
af_sign_seg3(af,segname_buf,0,data,datalen,AF_SIGNATURE_MODE1);
}
#endif
#ifdef HAVE_MD5
/* Write out MD5 if requested */
if(af->write_md5){
unsigned char md5_buf[16];
char md5name_buf[32];
MD5(data,datalen,md5_buf);
snprintf(md5name_buf,sizeof(md5name_buf),AF_PAGE_MD5,pagenum);
af_update_segf(af,md5name_buf,0,md5_buf,sizeof(md5_buf),AF_SIGFLAG_NOSIG); // ignore failure
}
#endif
#ifdef HAVE_SHA1
/* Write out SHA1 if requested */
if(af->write_sha1){
unsigned char sha1_buf[20];
char sha1name_buf[32];
SHA1(data,datalen,sha1_buf);
snprintf(sha1name_buf,sizeof(sha1name_buf),AF_PAGE_SHA1,pagenum);
af_update_segf(af,sha1name_buf,0,sha1_buf,sizeof(sha1_buf),AF_SIGFLAG_NOSIG); // ignore failure
}
#endif
/* Write out SHA256 if requested and if SHA256 is available */
if(af->write_sha256){
unsigned char sha256_buf[32];
if(af_SHA256(data,datalen,sha256_buf)==0){
char sha256name_buf[32];
snprintf(sha256name_buf,sizeof(sha256name_buf),AF_PAGE_SHA256,pagenum);
af_update_segf(af,sha256name_buf,0,sha256_buf,sizeof(sha256_buf),AF_SIGFLAG_NOSIG); // ignore failure
}
}
/* Check for bypass */
if(af->v->write){
int r = (*af->v->write)(af,data,af->image_pagesize * pagenum,datalen);
if(r!=datalen) return -1;
return 0;
}
struct affcallback_info acbi;
int ret = 0;
uint64_t starting_pages_written = af->pages_written;
/* Setup the callback structure */
memset(&acbi,0,sizeof(acbi));
acbi.info_version = 1;
acbi.af = af->parent ? af->parent : af;
acbi.pagenum = pagenum;
acbi.bytes_to_write = datalen;
size_t destLen = af->image_pagesize; // it could be this big.
/* Compress and write the data, if we are allowed to compress */
if(af->compression_type != AF_COMPRESSION_ALG_NONE){
unsigned char *cdata = (unsigned char *)malloc(destLen); // compressed data
uint32_t *ldata = (uint32_t *)cdata; // allows me to reference as a buffer of uint32_ts
if(cdata!=0){ // If data could be allocated
int cres = -1; // compression results
uint32_t flag = 0; // flag for data segment
int dont_compress = 0;
/* Try zero compression first; it's the best algorithm we have */
if(is_buffer_zero(data,datalen)){
acbi.compression_alg = AF_PAGE_COMP_ALG_ZERO;
acbi.compression_level = AF_COMPRESSION_MAX;
if(af->w_callback) { acbi.phase = 1; (*af->w_callback)(&acbi); }
*ldata = htonl(datalen); // store the data length
destLen = 4; // 4 bytes
flag = AF_PAGE_COMPRESSED | AF_PAGE_COMP_ALG_ZERO | AF_PAGE_COMP_MAX;
cres = 0;
acbi.compressed = 1; // it was compressed
if(af->w_callback) {acbi.phase = 2;(*af->w_callback)(&acbi);}
}
#ifdef USE_LZMA
if(cres!=0 && af->compression_type==AF_COMPRESSION_ALG_LZMA){ // try to compress with LZMA
acbi.compression_alg = AF_PAGE_COMP_ALG_LZMA;
acbi.compression_level = 7; // right now, this is the level we use
if(af->w_callback) { acbi.phase = 1; (*af->w_callback)(&acbi); }
cres = lzma_compress(cdata,&destLen,data,datalen,9);
#if 0
switch(cres){
case 0:break; // OKAY
case 1: (*af->error_reporter)("LZMA: Unspecified Error\n");break;
case 2: (*af->error_reporter)("LZMA: Memory Allocating Error\n");break;
case 3: (*af->error_reporter)("LZMA: Output buffer OVERFLOW\n"); break;
default: (*af->error_reporter)("LZMA: Unknown error %d\n",cres);break;
}
#endif
if(cres==0){
flag = AF_PAGE_COMPRESSED | AF_PAGE_COMP_ALG_LZMA;
acbi.compressed = 1;
if(af->w_callback) {acbi.phase = 2;(*af->w_callback)(&acbi);}
}
else {
/* Don't bother reporting LZMA errors; we just won't compress */
dont_compress = 1;
if(af->w_callback) {acbi.phase = 2;(*af->w_callback)(&acbi);}
}
}
#endif
if(cres!=0
&& af->compression_type==AF_COMPRESSION_ALG_ZLIB
&& dont_compress==0){ // try to compress with zlib
acbi.compression_alg = AF_PAGE_COMP_ALG_ZLIB; // only one that we support
acbi.compression_level = af->compression_level;
if(af->w_callback) { acbi.phase = 1; (*af->w_callback)(&acbi); }
cres = compress2((Bytef *)cdata, (uLongf *)&destLen,
(Bytef *)data,datalen, af->compression_level);
if(cres==0){
flag = AF_PAGE_COMPRESSED | AF_PAGE_COMP_ALG_ZLIB;
if(af->compression_level == AF_COMPRESSION_MAX){
flag |= AF_PAGE_COMP_MAX; // useful to know it can't be better
}
}
acbi.compressed = 1; // it was compressed (or not compressed)
if(af->w_callback) {acbi.phase = 2;(*af->w_callback)(&acbi);}
}
if(cres==0 && destLen < af->image_pagesize){
/* Prepare to write out the compressed segment with compression */
if(af->w_callback) {acbi.phase = 3;(*af->w_callback)(&acbi);}
ret = af_update_segf(af,segname_buf,flag,cdata,destLen,AF_SIGFLAG_NOSIG);
acbi.bytes_written = destLen;
if(af->w_callback) {acbi.phase = 4;(*af->w_callback)(&acbi);}
if(ret==0){
af->pages_written++;
af->pages_compressed++;
}
}
free(cdata);
cdata = 0;
}
}
/* If a compressed segment was not written, write it uncompressed */
if(af->pages_written == starting_pages_written){
if(af->w_callback) {acbi.phase = 3;(*af->w_callback)(&acbi);}
ret = af_update_segf(af,segname_buf,0,data,datalen,AF_SIGFLAG_NOSIG);
acbi.bytes_written = datalen;
if(af->w_callback) {acbi.phase = 4;(*af->w_callback)(&acbi);}
if(ret==0){
acbi.bytes_written = datalen; // because that is how much we wrote
af->pages_written++;
}
}
return ret;
}
/****************************************************************
*** Cache interface
****************************************************************/
/* The page cache is a read/write cache.
*
* Pages that are read are cached after they are decompressed.
* When new pages are fetched, we check the cache first to see if they are there;
* if so, they are satsfied by the cache.
*
* Modifications are written to the cache, then dumped to the disk.
*
* The cache is managed by two functions:
* af_cache_flush(af) - (prevously af_purge)
* - Makes sure that all dirty buffers are written.
* - Sets af->pb=NULL (no current page)
* - (returns 0 if success, -1 if failure.)
*
* af_cache_writethrough(af,page,buf,buflen)
* - used for write bypass
*
*/
static int cachetime = 0;
int af_cache_flush(AFFILE *af)
{
if(af_trace) fprintf(af_trace,"af_cache_flush()\n");
int ret = 0;
for(int i=0;i<af->num_pbufs;i++){
struct aff_pagebuf *p = &af->pbcache[i];
if(p->pagebuf_valid && p->pagebuf_dirty){
if(af_update_page(af,p->pagenum,p->pagebuf,p->pagebuf_bytes)){
ret = -1; // got an error; keep going, though
}
p->pagebuf_dirty = 0;
if(af_trace) fprintf(af_trace,"af_cache_flush: slot %d page %" PRIu64 " flushed.\n",i,p->pagenum);
}
}
return ret; // now return the error that I might have gotten
}
/* If the page being written is in the cache, update it.
* Question: would it make sense to copy the data anyway? I don't think so, because
* the main use of writethrough is when imaging, and in that event you probably don't
* want the extra memcpy.
*/
void af_cache_writethrough(AFFILE *af,int64_t pagenum,const unsigned char *buf,int bufflen)
{
for(int i=0;i<af->num_pbufs;i++){
struct aff_pagebuf *p = &af->pbcache[i];
if(p->pagenum_valid && p->pagenum == pagenum){
if(p->pagebuf_dirty){
(*af->error_reporter)("af_cache_writethrough: overwriting page %" I64u ".\n",pagenum);
exit(-1); // this shouldn't happen
}
memcpy(p->pagebuf,buf,bufflen);
memset(p->pagebuf+bufflen,0,af->image_pagesize-bufflen); // zero fill the rest
af->bytes_memcpy += bufflen;
p->pagebuf_valid = 1; // we have a copy of it now.
p->pagebuf_dirty = 0; // but it isn't dirty
p->last = cachetime++;
}
}
}
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#ifndef HAVE_VALLOC
#define valloc malloc
#endif
struct aff_pagebuf *af_cache_alloc(AFFILE *af,int64_t pagenum)
{
if(af_trace) fprintf(af_trace,"af_cache_alloc(%p,%" I64d ")\n",af,pagenum);
/* Make sure nothing in the cache is dirty */
if(af_cache_flush(af) < 0)
return 0;
/* See if this page is already in the cache */
for(int i=0;i<af->num_pbufs;i++){
struct aff_pagebuf *p = &af->pbcache[i];
if(p->pagenum_valid && p->pagenum==pagenum){
af->cache_hits++;
if(af_trace) fprintf(af_trace," page %" I64d " satisfied fromcache\n",pagenum);
p->last = cachetime++;
return p;
}
}
af->cache_misses++;
int slot = -1;
/* See if there is an empty slot in the cache */
for(int i=0;i<af->num_pbufs;i++){
struct aff_pagebuf *p = &af->pbcache[i];
if(p->pagenum_valid==0){
slot = i;
if(af_trace) fprintf(af_trace," slot %d given to page %" I64d "\n",slot,pagenum);
break;
}
}
if(slot==-1){
/* Find the oldest cache entry */
int oldest_i = 0;
int oldest_t = af->pbcache[0].last;
for(int i=1;i<af->num_pbufs;i++){
if(af->pbcache[i].last < oldest_t){
oldest_t = af->pbcache[i].last;
oldest_i = i;
}
}
slot = oldest_i;
if(af_trace) fprintf(af_trace," slot %d assigned to page %" I64d "\n",slot,pagenum);
}
/* take over this slot */
struct aff_pagebuf *p = &af->pbcache[slot];
if(p->pagebuf==0){
p->pagebuf = (unsigned char *)valloc(af->image_pagesize); // allocate to a page boundary
if(p->pagebuf==0){
/* Malloc failed; See if we can just use the first slot */
slot = 0;
if(af->pbcache[0].pagebuf==0) return 0; // ugh. Cannot malloc?
/* First slot is available. Just use it. */
p = &af->pbcache[0];
}
}
memset(p->pagebuf,0,af->image_pagesize); // clean object reuse
p->pagenum = pagenum;
p->pagenum_valid = 1;
p->pagebuf_valid = 0;
p->pagebuf_dirty = 0;
p->last = cachetime++;
if(af_trace){
fprintf(af_trace," current pages in cache: ");
for(int i=0;i<af->num_pbufs;i++){
fprintf(af_trace," %" I64d,af->pbcache[i].pagenum);
}
fprintf(af_trace,"\n");
}
return p;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_660_0 |
crossvul-cpp_data_good_4877_1 | #include "Hub.h"
namespace uWS {
template <const bool isServer>
bool WebSocketProtocol<isServer>::setCompressed(void *user) {
uS::Socket s((uv_poll_t *) user);
typename WebSocket<isServer>::Data *webSocketData = (typename WebSocket<isServer>::Data *) s.getSocketData();
if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::ENABLED) {
webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME;
return true;
} else {
return false;
}
}
template <const bool isServer>
bool WebSocketProtocol<isServer>::refusePayloadLength(void *user, int length) {
return length > 16777216;
}
template <const bool isServer>
void WebSocketProtocol<isServer>::forceClose(void *user) {
WebSocket<isServer>((uv_poll_t *) user).terminate();
}
template <const bool isServer>
bool WebSocketProtocol<isServer>::handleFragment(char *data, size_t length, unsigned int remainingBytes, int opCode, bool fin, void *user) {
uS::Socket s((uv_poll_t *) user);
typename WebSocket<isServer>::Data *webSocketData = (typename WebSocket<isServer>::Data *) s.getSocketData();
if (opCode < 3) {
if (!remainingBytes && fin && !webSocketData->fragmentBuffer.length()) {
if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME) {
webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::ENABLED;
Hub *hub = ((Group<isServer> *) s.getSocketData()->nodeData)->hub;
data = hub->inflate(data, length);
if (!data) {
forceClose(user);
return true;
}
}
if (opCode == 1 && !isValidUtf8((unsigned char *) data, length)) {
forceClose(user);
return true;
}
((Group<isServer> *) s.getSocketData()->nodeData)->messageHandler(WebSocket<isServer>(s), data, length, (OpCode) opCode);
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
} else {
webSocketData->fragmentBuffer.append(data, length);
if (!remainingBytes && fin) {
length = webSocketData->fragmentBuffer.length();
if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME) {
webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::ENABLED;
Hub *hub = ((Group<isServer> *) s.getSocketData()->nodeData)->hub;
webSocketData->fragmentBuffer.append("....");
data = hub->inflate((char *) webSocketData->fragmentBuffer.data(), length);
if (!data) {
forceClose(user);
return true;
}
} else {
data = (char *) webSocketData->fragmentBuffer.data();
}
if (opCode == 1 && !isValidUtf8((unsigned char *) data, length)) {
forceClose(user);
return true;
}
((Group<isServer> *) s.getSocketData()->nodeData)->messageHandler(WebSocket<isServer>(s), data, length, (OpCode) opCode);
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
webSocketData->fragmentBuffer.clear();
}
}
} else {
// todo: we don't need to buffer up in most cases!
webSocketData->controlBuffer.append(data, length);
if (!remainingBytes && fin) {
if (opCode == CLOSE) {
CloseFrame closeFrame = parseClosePayload((char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
WebSocket<isServer>(s).close(closeFrame.code, closeFrame.message, closeFrame.length);
return true;
} else {
if (opCode == PING) {
WebSocket<isServer>(s).send(webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length(), (OpCode) OpCode::PONG);
((Group<isServer> *) s.getSocketData()->nodeData)->pingHandler(WebSocket<isServer>(s), (char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
} else if (opCode == PONG) {
((Group<isServer> *) s.getSocketData()->nodeData)->pongHandler(WebSocket<isServer>(s), (char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
}
}
webSocketData->controlBuffer.clear();
}
}
return false;
}
template class WebSocketProtocol<SERVER>;
template class WebSocketProtocol<CLIENT>;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_4877_1 |
crossvul-cpp_data_good_600_0 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/HTTP2Constants.h>
#include <proxygen/lib/http/codec/CodecUtil.h>
#include <proxygen/lib/utils/Logging.h>
#include <proxygen/lib/utils/Base64.h>
#include <folly/Conv.h>
#include <folly/Random.h>
#include <folly/ThreadLocal.h>
#include <folly/io/Cursor.h>
#include <folly/tracing/ScopedTraceSection.h>
#include <type_traits>
using namespace proxygen::compress;
using namespace folly::io;
using namespace folly;
using std::string;
namespace {
std::string base64url_encode(ByteRange range) {
return proxygen::Base64::urlEncode(range);
}
std::string base64url_decode(const std::string& str) {
return proxygen::Base64::urlDecode(str);
}
}
namespace proxygen {
HTTP2Codec::HTTP2Codec(TransportDirection direction)
: HTTPParallelCodec(direction),
headerCodec_(direction),
frameState_(direction == TransportDirection::DOWNSTREAM
? FrameState::UPSTREAM_CONNECTION_PREFACE
: FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
const auto maxHeaderListSize = egressSettings_.getSetting(
SettingsId::MAX_HEADER_LIST_SIZE);
if (maxHeaderListSize) {
headerCodec_.setMaxUncompressed(maxHeaderListSize->value);
}
VLOG(4) << "creating " << getTransportDirectionString(direction)
<< " HTTP/2 codec";
}
HTTP2Codec::~HTTP2Codec() {}
// HTTPCodec API
size_t HTTP2Codec::onIngress(const folly::IOBuf& buf) {
// TODO: ensure only 1 parse at a time on stack.
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - onIngress");
Cursor cursor(&buf);
size_t parsed = 0;
ErrorCode connError = ErrorCode::NO_ERROR;
for (auto bufLen = cursor.totalLength();
connError == ErrorCode::NO_ERROR;
bufLen = cursor.totalLength()) {
if (frameState_ == FrameState::UPSTREAM_CONNECTION_PREFACE) {
if (bufLen >= http2::kConnectionPreface.length()) {
auto test = cursor.readFixedString(http2::kConnectionPreface.length());
parsed += http2::kConnectionPreface.length();
if (test != http2::kConnectionPreface) {
goawayErrorMessage_ = "missing connection preface";
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
} else if (frameState_ == FrameState::FRAME_HEADER ||
frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
// Waiting to parse the common frame header
if (bufLen >= http2::kFrameHeaderSize) {
connError = parseFrameHeader(cursor, curHeader_);
parsed += http2::kFrameHeaderSize;
if (frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE &&
curHeader_.type != http2::FrameType::SETTINGS) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: got invalid connection preface frame type=",
getFrameTypeString(curHeader_.type), "(", curHeader_.type, ")",
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
if (curHeader_.length > maxRecvFrameSize()) {
VLOG(4) << "Excessively large frame len=" << curHeader_.length;
connError = ErrorCode::FRAME_SIZE_ERROR;
}
if (callback_) {
callback_->onFrameHeader(
curHeader_.stream,
curHeader_.flags,
curHeader_.length,
static_cast<uint8_t>(curHeader_.type));
}
frameState_ = (curHeader_.type == http2::FrameType::DATA) ?
FrameState::DATA_FRAME_DATA : FrameState::FRAME_DATA;
pendingDataFrameBytes_ = curHeader_.length;
pendingDataFramePaddingBytes_ = 0;
#ifndef NDEBUG
receivedFrameCount_++;
#endif
} else {
break;
}
} else if (frameState_ == FrameState::DATA_FRAME_DATA && bufLen > 0 &&
(bufLen < curHeader_.length ||
pendingDataFrameBytes_ < curHeader_.length)) {
// FrameState::DATA_FRAME_DATA with partial data only
size_t dataParsed = 0;
connError = parseDataFrameData(cursor, bufLen, dataParsed);
if (dataParsed == 0 && pendingDataFrameBytes_ > 0) {
// We received only the padding byte, we will wait for more
break;
} else {
parsed += dataParsed;
if (pendingDataFrameBytes_ == 0) {
frameState_ = FrameState::FRAME_HEADER;
}
}
} else { // FrameState::FRAME_DATA
// or FrameState::DATA_FRAME_DATA with all data available
// Already parsed the common frame header
const auto frameLen = curHeader_.length;
if (bufLen >= frameLen) {
connError = parseFrame(cursor);
parsed += curHeader_.length;
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
}
}
checkConnectionError(connError, &buf);
return parsed;
}
ErrorCode HTTP2Codec::parseFrame(folly::io::Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseFrame");
if (expectedContinuationStream_ != 0 &&
(curHeader_.type != http2::FrameType::CONTINUATION ||
expectedContinuationStream_ != curHeader_.stream)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: while expected CONTINUATION with stream=",
expectedContinuationStream_, ", received streamID=", curHeader_.stream,
" of type=", getFrameTypeString(curHeader_.type));
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (expectedContinuationStream_ == 0 &&
curHeader_.type == http2::FrameType::CONTINUATION) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: unexpected CONTINUATION received with streamID=",
curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (frameAffectsCompression(curHeader_.type) &&
curHeaderBlock_.chainLength() + curHeader_.length >
egressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, 0)) {
// this may be off by up to the padding length (max 255), but
// these numbers are already so generous, and we're comparing the
// max-uncompressed to the actual compressed size. Let's fail
// before buffering.
// TODO(t6513634): it would be nicer to stream-process this header
// block to keep the connection state consistent without consuming
// memory, and fail just the request per the HTTP/2 spec (section
// 10.3)
goawayErrorMessage_ = folly::to<string>(
"Failing connection due to excessively large headers");
LOG(ERROR) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
expectedContinuationStream_ =
(frameAffectsCompression(curHeader_.type) &&
!(curHeader_.flags & http2::END_HEADERS)) ? curHeader_.stream : 0;
switch (curHeader_.type) {
case http2::FrameType::DATA:
return parseAllData(cursor);
case http2::FrameType::HEADERS:
return parseHeaders(cursor);
case http2::FrameType::PRIORITY:
return parsePriority(cursor);
case http2::FrameType::RST_STREAM:
return parseRstStream(cursor);
case http2::FrameType::SETTINGS:
return parseSettings(cursor);
case http2::FrameType::PUSH_PROMISE:
return parsePushPromise(cursor);
case http2::FrameType::EX_HEADERS:
if (ingressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
return parseExHeaders(cursor);
} else {
VLOG(2) << "EX_HEADERS not enabled, ignoring the frame";
break;
}
case http2::FrameType::PING:
return parsePing(cursor);
case http2::FrameType::GOAWAY:
return parseGoaway(cursor);
case http2::FrameType::WINDOW_UPDATE:
return parseWindowUpdate(cursor);
case http2::FrameType::CONTINUATION:
return parseContinuation(cursor);
case http2::FrameType::ALTSVC:
// fall through, unimplemented
break;
case http2::FrameType::CERTIFICATE_REQUEST:
return parseCertificateRequest(cursor);
case http2::FrameType::CERTIFICATE:
return parseCertificate(cursor);
default:
// Implementations MUST ignore and discard any frame that has a
// type that is unknown
break;
}
// Landing here means unknown, unimplemented or ignored frame.
VLOG(2) << "Skipping frame (type=" << (uint8_t)curHeader_.type << ")";
cursor.skip(curHeader_.length);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::handleEndStream() {
if (curHeader_.type != http2::FrameType::HEADERS &&
curHeader_.type != http2::FrameType::EX_HEADERS &&
curHeader_.type != http2::FrameType::CONTINUATION &&
curHeader_.type != http2::FrameType::DATA) {
return ErrorCode::NO_ERROR;
}
// do we need to handle case where this stream has already aborted via
// another callback (onHeadersComplete/onBody)?
pendingEndStreamHandling_ |= (curHeader_.flags & http2::END_STREAM);
// with a websocket upgrade, we need to send message complete cb to
// mirror h1x codec's behavior. when the stream closes, we need to
// send another callback to clean up the stream's resources.
if (ingressWebsocketUpgrade_) {
ingressWebsocketUpgrade_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, true);
}
if (pendingEndStreamHandling_ && expectedContinuationStream_ == 0) {
pendingEndStreamHandling_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, false);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseAllData(Cursor& cursor) {
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing all frame DATA bytes for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto ret = http2::parseData(cursor, curHeader_, outData, padding);
RETURN_IF_ERROR(ret);
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return handleEndStream();
}
ErrorCode HTTP2Codec::parseDataFrameData(Cursor& cursor,
size_t bufLen,
size_t& parsed) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseDataFrameData");
if (bufLen == 0) {
VLOG(10) << "No data to parse";
return ErrorCode::NO_ERROR;
}
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing DATA frame data for stream=" << curHeader_.stream <<
" frame data length=" << curHeader_.length << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
// Parse the padding information only the first time
if (pendingDataFrameBytes_ == curHeader_.length &&
pendingDataFramePaddingBytes_ == 0) {
if (frameHasPadding(curHeader_) && bufLen == 1) {
// We need to wait for more bytes otherwise we won't be able to pass
// the correct padding to the first onBody call
return ErrorCode::NO_ERROR;
}
const auto ret = http2::parseDataBegin(cursor, curHeader_, parsed, padding);
RETURN_IF_ERROR(ret);
if (padding > 0) {
pendingDataFramePaddingBytes_ = padding - 1;
pendingDataFrameBytes_--;
bufLen--;
parsed++;
}
VLOG(10) << "out padding=" << padding << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
if (bufLen > 0) {
// Check if we have application data to parse
if (pendingDataFrameBytes_ > pendingDataFramePaddingBytes_) {
const size_t pendingAppData =
pendingDataFrameBytes_ - pendingDataFramePaddingBytes_;
const size_t toClone = std::min(pendingAppData, bufLen);
cursor.clone(outData, toClone);
bufLen -= toClone;
pendingDataFrameBytes_ -= toClone;
parsed += toClone;
VLOG(10) << "parsed some app data, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
// Check if we have padding bytes to parse
if (bufLen > 0 && pendingDataFramePaddingBytes_ > 0) {
size_t toSkip = 0;
auto ret = http2::parseDataEnd(cursor, bufLen,
pendingDataFramePaddingBytes_, toSkip);
RETURN_IF_ERROR(ret);
pendingDataFrameBytes_ -= toSkip;
pendingDataFramePaddingBytes_ -= toSkip;
parsed += toSkip;
VLOG(10) << "parsed some padding, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
}
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return (pendingDataFrameBytes_ > 0) ? ErrorCode::NO_ERROR : handleEndStream();
}
ErrorCode HTTP2Codec::parseHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseHeaders");
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing HEADERS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseHeaders(cursor, curHeader_, priority, headerBuf);
RETURN_IF_ERROR(err);
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, true /* trailersAllowed */));
}
err = parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
folly::none);
return err;
}
ErrorCode HTTP2Codec::parseExHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseExHeaders");
HTTPCodec::ExAttributes exAttributes;
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing ExHEADERS frame for stream=" << curHeader_.stream
<< " length=" << curHeader_.length;
auto err = http2::parseExHeaders(
cursor, curHeader_, exAttributes, priority, headerBuf);
RETURN_IF_ERROR(err);
if (isRequest(curHeader_.stream)) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, false /* trailersAllowed */));
}
return parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
exAttributes);
}
ErrorCode HTTP2Codec::parseContinuation(Cursor& cursor) {
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing CONTINUATION frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseContinuation(cursor, curHeader_, headerBuf);
RETURN_IF_ERROR(err);
err = parseHeadersImpl(cursor, std::move(headerBuf),
folly::none, folly::none, folly::none);
return err;
}
ErrorCode HTTP2Codec::parseHeadersImpl(
Cursor& /*cursor*/,
std::unique_ptr<IOBuf> headerBuf,
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes) {
curHeaderBlock_.append(std::move(headerBuf));
std::unique_ptr<HTTPMessage> msg;
if (curHeader_.flags & http2::END_HEADERS) {
auto errorCode =
parseHeadersDecodeFrames(priority, promisedStream, exAttributes, msg);
if (errorCode.hasValue()) {
return errorCode.value();
}
}
// if we're not parsing CONTINUATION, then it's start of new header block
if (curHeader_.type != http2::FrameType::CONTINUATION) {
headerBlockFrameType_ = curHeader_.type;
}
// Report back what we've parsed
if (callback_) {
auto concurError = parseHeadersCheckConcurrentStreams(priority);
if (concurError.hasValue()) {
return concurError.value();
}
uint32_t headersCompleteStream = curHeader_.stream;
bool trailers = parsingTrailers();
bool allHeaderFramesReceived =
(curHeader_.flags & http2::END_HEADERS) &&
(headerBlockFrameType_ == http2::FrameType::HEADERS);
if (allHeaderFramesReceived && !trailers) {
// Only deliver onMessageBegin once per stream.
// For responses with CONTINUATION, this will be delayed until
// the frame with the END_HEADERS flag set.
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageBegin,
"onMessageBegin",
curHeader_.stream,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::EX_HEADERS) {
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onExMessageBegin,
"onExMessageBegin",
curHeader_.stream,
exAttributes->controlStream,
exAttributes->unidirectional,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::PUSH_PROMISE) {
DCHECK(promisedStream);
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onPushMessageBegin,
"onPushMessageBegin", *promisedStream,
curHeader_.stream, msg.get())) {
return handleEndStream();
}
headersCompleteStream = *promisedStream;
}
if (curHeader_.flags & http2::END_HEADERS && msg) {
if (!(curHeader_.flags & http2::END_STREAM)) {
// If it there are DATA frames coming, consider it chunked
msg->setIsChunked(true);
}
if (trailers) {
VLOG(4) << "Trailers complete for streamId=" << headersCompleteStream
<< " direction=" << transportDirection_;
auto trailerHeaders =
std::make_unique<HTTPHeaders>(msg->extractHeaders());
msg.reset();
callback_->onTrailersComplete(headersCompleteStream,
std::move(trailerHeaders));
} else {
callback_->onHeadersComplete(headersCompleteStream, std::move(msg));
}
}
return handleEndStream();
}
return ErrorCode::NO_ERROR;
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersDecodeFrames(
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes,
std::unique_ptr<HTTPMessage>& msg) {
// decompress headers
Cursor headerCursor(curHeaderBlock_.front());
bool isReq = false;
if (promisedStream) {
isReq = true;
} else if (exAttributes) {
isReq = isRequest(curHeader_.stream);
} else {
isReq = transportDirection_ == TransportDirection::DOWNSTREAM;
}
// Validate circular dependencies.
if (priority && (curHeader_.stream == priority->streamDependency)) {
streamError(
folly::to<string>("Circular dependency for txn=", curHeader_.stream),
ErrorCode::PROTOCOL_ERROR,
curHeader_.type == http2::FrameType::HEADERS);
return ErrorCode::NO_ERROR;
}
decodeInfo_.init(isReq, parsingDownstreamTrailers_);
if (priority) {
decodeInfo_.msg->setHTTP2Priority(
std::make_tuple(priority->streamDependency,
priority->exclusive,
priority->weight));
}
headerCodec_.decodeStreaming(
headerCursor, curHeaderBlock_.chainLength(), this);
msg = std::move(decodeInfo_.msg);
// Saving this in case we need to log it on error
auto g = folly::makeGuard([this] { curHeaderBlock_.move(); });
// Check decoding error
if (decodeInfo_.decodeError != HPACK::DecodeError::NONE) {
static const std::string decodeErrorMessage =
"Failed decoding header block for stream=";
// Avoid logging header blocks that have failed decoding due to being
// excessively large.
if (decodeInfo_.decodeError != HPACK::DecodeError::HEADERS_TOO_LARGE) {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream
<< " header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
} else {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream;
}
if (msg) {
// print the partial message
msg->dumpMessage(3);
}
return ErrorCode::COMPRESSION_ERROR;
}
// Check parsing error
if (decodeInfo_.parsingError != "") {
LOG(ERROR) << "Failed parsing header list for stream=" << curHeader_.stream
<< ", error=" << decodeInfo_.parsingError << ", header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
HTTPException err(HTTPException::Direction::INGRESS,
folly::to<std::string>("HTTP2Codec stream error: ",
"stream=",
curHeader_.stream,
" status=",
400,
" error: ",
decodeInfo_.parsingError));
err.setHttpStatusCode(400);
callback_->onError(curHeader_.stream, err, true);
return ErrorCode::NO_ERROR;
}
return folly::Optional<ErrorCode>();
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersCheckConcurrentStreams(
const folly::Optional<http2::PriorityUpdate>& priority) {
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::EX_HEADERS) {
if (curHeader_.flags & http2::PRIORITY) {
DCHECK(priority);
// callback_->onPriority(priority.get());
}
// callback checks total number of streams is smaller than settings max
if (callback_->numIncomingStreams() >=
egressSettings_.getSetting(SettingsId::MAX_CONCURRENT_STREAMS,
std::numeric_limits<int32_t>::max())) {
streamError(folly::to<string>("Exceeded max_concurrent_streams"),
ErrorCode::REFUSED_STREAM, true);
return ErrorCode::NO_ERROR;
}
}
return folly::Optional<ErrorCode>();
}
void HTTP2Codec::onHeader(const folly::fbstring& name,
const folly::fbstring& value) {
if (decodeInfo_.onHeader(name, value)) {
if (name == "user-agent" && userAgent_.empty()) {
userAgent_ = value.toStdString();
}
} else {
VLOG(4) << "dir=" << uint32_t(transportDirection_) <<
decodeInfo_.parsingError << " codec=" << headerCodec_;
}
}
void HTTP2Codec::onHeadersComplete(HTTPHeaderSize decodedSize,
bool /*acknowledge*/) {
decodeInfo_.onHeadersComplete(decodedSize);
decodeInfo_.msg->setAdvancedProtocolString(http2::kProtocolString);
HTTPMessage* msg = decodeInfo_.msg.get();
HTTPRequestVerifier& verifier = decodeInfo_.verifier;
if ((transportDirection_ == TransportDirection::DOWNSTREAM) &&
verifier.hasUpgradeProtocol() &&
(*msg->getUpgradeProtocol() == headers::kWebsocketString) &&
msg->getMethod() == HTTPMethod::CONNECT) {
msg->setIngressWebsocketUpgrade();
ingressWebsocketUpgrade_ = true;
} else {
auto it = upgradedStreams_.find(curHeader_.stream);
if (it != upgradedStreams_.end()) {
upgradedStreams_.erase(curHeader_.stream);
// a websocket upgrade was sent on this stream.
if (msg->getStatusCode() != 200) {
decodeInfo_.parsingError =
folly::to<string>("Invalid response code to a websocket upgrade: ",
msg->getStatusCode());
return;
}
msg->setIngressWebsocketUpgrade();
}
}
}
void HTTP2Codec::onDecodeError(HPACK::DecodeError decodeError) {
decodeInfo_.decodeError = decodeError;
}
ErrorCode HTTP2Codec::parsePriority(Cursor& cursor) {
VLOG(4) << "parsing PRIORITY frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
http2::PriorityUpdate pri;
auto err = http2::parsePriority(cursor, curHeader_, pri);
RETURN_IF_ERROR(err);
if (curHeader_.stream == pri.streamDependency) {
streamError(folly::to<string>("Circular dependency for txn=",
curHeader_.stream),
ErrorCode::PROTOCOL_ERROR, false);
return ErrorCode::NO_ERROR;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onPriority, "onPriority",
curHeader_.stream,
std::make_tuple(pri.streamDependency,
pri.exclusive,
pri.weight));
return ErrorCode::NO_ERROR;
}
size_t HTTP2Codec::addPriorityNodes(
PriorityQueue& queue,
folly::IOBufQueue& writeBuf,
uint8_t maxLevel) {
HTTPCodec::StreamID parent = 0;
size_t bytes = 0;
while (maxLevel--) {
auto id = createStream();
virtualPriorityNodes_.push_back(id);
queue.addPriorityNode(id, parent);
bytes += generatePriority(writeBuf, id, std::make_tuple(parent, false, 0));
parent = id;
}
return bytes;
}
ErrorCode HTTP2Codec::parseRstStream(Cursor& cursor) {
// rst for stream in idle state - protocol error
VLOG(4) << "parsing RST_STREAM frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
upgradedStreams_.erase(curHeader_.stream);
ErrorCode statusCode = ErrorCode::NO_ERROR;
auto err = http2::parseRstStream(cursor, curHeader_, statusCode);
RETURN_IF_ERROR(err);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: RST_STREAM with code=", getErrorCodeString(statusCode),
" for streamID=", curHeader_.stream, " user-agent=", userAgent_);
VLOG(2) << goawayErrorMessage_;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onAbort, "onAbort",
curHeader_.stream, statusCode);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseSettings(Cursor& cursor) {
VLOG(4) << "parsing SETTINGS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
std::deque<SettingPair> settings;
auto err = http2::parseSettings(cursor, curHeader_, settings);
RETURN_IF_ERROR(err);
if (curHeader_.flags & http2::ACK) {
handleSettingsAck();
return ErrorCode::NO_ERROR;
}
return handleSettings(settings);
}
void HTTP2Codec::handleSettingsAck() {
if (pendingTableMaxSize_) {
headerCodec_.setDecoderHeaderTableMaxSize(*pendingTableMaxSize_);
pendingTableMaxSize_ = folly::none;
}
if (callback_) {
callback_->onSettingsAck();
}
}
ErrorCode HTTP2Codec::handleSettings(const std::deque<SettingPair>& settings) {
SettingsList settingsList;
for (auto& setting: settings) {
switch (setting.first) {
case SettingsId::HEADER_TABLE_SIZE:
{
uint32_t tableSize = setting.second;
if (setting.second > http2::kMaxHeaderTableSize) {
VLOG(2) << "Limiting table size from " << tableSize << " to " <<
http2::kMaxHeaderTableSize;
tableSize = http2::kMaxHeaderTableSize;
}
headerCodec_.setEncoderHeaderTableSize(tableSize);
}
break;
case SettingsId::ENABLE_PUSH:
if ((setting.second != 0 && setting.second != 1) ||
(setting.second == 1 &&
transportDirection_ == TransportDirection::UPSTREAM)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_PUSH invalid setting=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
break;
case SettingsId::INITIAL_WINDOW_SIZE:
if (setting.second > http2::kMaxWindowUpdateSize) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: INITIAL_WINDOW_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_FRAME_SIZE:
if (setting.second < http2::kMaxFramePayloadLengthMin ||
setting.second > http2::kMaxFramePayloadLength) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: MAX_FRAME_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
ingressSettings_.setSetting(SettingsId::MAX_FRAME_SIZE, setting.second);
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
break;
case SettingsId::ENABLE_EX_HEADERS:
{
auto ptr = egressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS);
if (ptr && ptr->value > 0) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " got ENABLE_EX_HEADERS=" << setting.second;
if (setting.second != 0 && setting.second != 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid ENABLE_EX_HEADERS=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
} else {
// egress ENABLE_EX_HEADERS is disabled, consider the ingress
// ENABLE_EX_HEADERS as unknown setting, and ignore it.
continue;
}
}
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.second > 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_CONNECT_PROTOCOL invalid number=",
setting.second, " for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
case SettingsId::SETTINGS_HTTP_CERT_AUTH:
break;
default:
continue; // ignore unknown setting
}
ingressSettings_.setSetting(setting.first, setting.second);
settingsList.push_back(*ingressSettings_.getSetting(setting.first));
}
if (callback_) {
callback_->onSettings(settingsList);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parsePushPromise(Cursor& cursor) {
// stream id must be idle - protocol error
// assoc-stream-id=closed/unknown - protocol error, unless rst_stream sent
/*
* What does "must handle" mean in the following context? I have to
* accept this as a valid pushed resource?
However, an endpoint that has sent RST_STREAM on the associated
stream MUST handle PUSH_PROMISE frames that might have been
created before the RST_STREAM frame is received and processed.
*/
if (transportDirection_ != TransportDirection::UPSTREAM) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on DOWNSTREAM codec");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (egressSettings_.getSetting(SettingsId::ENABLE_PUSH, -1) != 1) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on codec with push disabled");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
VLOG(4) << "parsing PUSH_PROMISE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t promisedStream;
std::unique_ptr<IOBuf> headerBlockFragment;
auto err = http2::parsePushPromise(cursor, curHeader_, promisedStream,
headerBlockFragment);
RETURN_IF_ERROR(err);
RETURN_IF_ERROR(checkNewStream(promisedStream, false /* trailersAllowed */));
err = parseHeadersImpl(cursor, std::move(headerBlockFragment), folly::none,
promisedStream, folly::none);
return err;
}
ErrorCode HTTP2Codec::parsePing(Cursor& cursor) {
VLOG(4) << "parsing PING frame length=" << curHeader_.length;
uint64_t opaqueData = 0;
auto err = http2::parsePing(cursor, curHeader_, opaqueData);
RETURN_IF_ERROR(err);
if (callback_) {
if (curHeader_.flags & http2::ACK) {
callback_->onPingReply(opaqueData);
} else {
callback_->onPingRequest(opaqueData);
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseGoaway(Cursor& cursor) {
VLOG(4) << "parsing GOAWAY frame length=" << curHeader_.length;
uint32_t lastGoodStream = 0;
ErrorCode statusCode = ErrorCode::NO_ERROR;
std::unique_ptr<IOBuf> debugData;
auto err = http2::parseGoaway(cursor, curHeader_, lastGoodStream, statusCode,
debugData);
if (statusCode != ErrorCode::NO_ERROR) {
VLOG(2) << "Goaway error statusCode=" << getErrorCodeString(statusCode)
<< " lastStream=" << lastGoodStream
<< " user-agent=" << userAgent_ << " debugData=" <<
((debugData) ? string((char*)debugData->data(), debugData->length()):
empty_string);
}
RETURN_IF_ERROR(err);
if (lastGoodStream < ingressGoawayAck_) {
ingressGoawayAck_ = lastGoodStream;
// Drain all streams <= lastGoodStream
// and abort streams > lastGoodStream
if (callback_) {
callback_->onGoaway(lastGoodStream, statusCode, std::move(debugData));
}
} else {
LOG(WARNING) << "Received multiple GOAWAY with increasing ack";
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseWindowUpdate(Cursor& cursor) {
VLOG(4) << "parsing WINDOW_UPDATE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t delta = 0;
auto err = http2::parseWindowUpdate(cursor, curHeader_, delta);
RETURN_IF_ERROR(err);
if (delta == 0) {
VLOG(4) << "Invalid 0 length delta for stream=" << curHeader_.stream;
if (curHeader_.stream == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid/0 length delta for streamID=",
curHeader_.stream);
return ErrorCode::PROTOCOL_ERROR;
} else {
// Parsing a zero delta window update should cause a protocol error
// and send a rst stream
goawayErrorMessage_ = folly::to<string>(
"parseWindowUpdate Invalid 0 length");
VLOG(4) << goawayErrorMessage_;
streamError(folly::to<std::string>("streamID=", curHeader_.stream,
" with HTTP2Codec stream error: ",
"window update delta=", delta),
ErrorCode::PROTOCOL_ERROR);
return ErrorCode::PROTOCOL_ERROR;
}
}
// if window exceeds 2^31-1, connection/stream error flow control error
// must be checked in session/txn
deliverCallbackIfAllowed(&HTTPCodec::Callback::onWindowUpdate,
"onWindowUpdate", curHeader_.stream, delta);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificateRequest(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE_REQUEST frame length=" << curHeader_.length;
uint16_t requestId = 0;
std::unique_ptr<IOBuf> authRequest;
auto err = http2::parseCertificateRequest(
cursor, curHeader_, requestId, authRequest);
RETURN_IF_ERROR(err);
if (callback_) {
callback_->onCertificateRequest(requestId, std::move(authRequest));
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificate(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE frame length=" << curHeader_.length;
uint16_t certId = 0;
std::unique_ptr<IOBuf> authData;
auto err = http2::parseCertificate(cursor, curHeader_, certId, authData);
RETURN_IF_ERROR(err);
if (curAuthenticatorBlock_.empty()) {
curCertId_ = certId;
} else if (certId != curCertId_) {
// Received CERTIFICATE frame with different Cert-ID.
return ErrorCode::PROTOCOL_ERROR;
}
curAuthenticatorBlock_.append(std::move(authData));
if (curAuthenticatorBlock_.chainLength() > http2::kMaxAuthenticatorBufSize) {
// Received excessively long authenticator.
return ErrorCode::PROTOCOL_ERROR;
}
if (!(curHeader_.flags & http2::TO_BE_CONTINUED)) {
auto authenticator = curAuthenticatorBlock_.move();
if (callback_) {
callback_->onCertificate(certId, std::move(authenticator));
} else {
curAuthenticatorBlock_.clear();
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {
if (streamId == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: received streamID=", streamId,
" as invalid new stream for lastStreamID_=", lastStreamID_);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);
if (parsingDownstreamTrailers_) {
VLOG(4) << "Parsing downstream trailers streamId=" << streamId;
}
if (sessionClosing_ != ClosingState::CLOSED && streamId > lastStreamID_) {
lastStreamID_ = streamId;
}
if (isInitiatedStream(streamId)) {
// this stream should be initiated by us, not by peer
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid new stream received with streamID=", streamId);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
} else {
return ErrorCode::NO_ERROR;
}
}
size_t HTTP2Codec::generateConnectionPreface(folly::IOBufQueue& writeBuf) {
if (transportDirection_ == TransportDirection::UPSTREAM) {
VLOG(4) << "generating connection preface";
writeBuf.append(http2::kConnectionPreface);
return http2::kConnectionPreface.length();
}
return 0;
}
bool HTTP2Codec::onIngressUpgradeMessage(const HTTPMessage& msg) {
if (!HTTPParallelCodec::onIngressUpgradeMessage(msg)) {
return false;
}
if (msg.getHeaders().getNumberOfValues(http2::kProtocolSettingsHeader) != 1) {
VLOG(4) << __func__ << " with no HTTP2-Settings";
return false;
}
const auto& settingsHeader = msg.getHeaders().getSingleOrEmpty(
http2::kProtocolSettingsHeader);
if (settingsHeader.empty()) {
return true;
}
auto decoded = base64url_decode(settingsHeader);
// Must be well formed Base64Url and not too large
if (decoded.empty() || decoded.length() > http2::kMaxFramePayloadLength) {
VLOG(4) << __func__ << " failed to decode HTTP2-Settings";
return false;
}
std::unique_ptr<IOBuf> decodedBuf = IOBuf::wrapBuffer(decoded.data(),
decoded.length());
IOBufQueue settingsQueue{IOBufQueue::cacheChainLength()};
settingsQueue.append(std::move(decodedBuf));
Cursor c(settingsQueue.front());
std::deque<SettingPair> settings;
// downcast is ok because of above length check
http2::FrameHeader frameHeader{
(uint32_t)settingsQueue.chainLength(), 0, http2::FrameType::SETTINGS, 0, 0};
auto err = http2::parseSettings(c, frameHeader, settings);
if (err != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " bad settings frame";
return false;
}
if (handleSettings(settings) != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " handleSettings failed";
return false;
}
return true;
}
void HTTP2Codec::generateHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generatePushPromise(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
StreamID assocStream,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
assocStream,
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generateExHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const HTTPCodec::ExAttributes& exAttributes,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
exAttributes,
eom,
size);
}
void HTTP2Codec::generateHeaderImpl(
folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const folly::Optional<StreamID>& assocStream,
const folly::Optional<HTTPCodec::ExAttributes>& exAttributes,
bool eom,
HTTPHeaderSize* size) {
if (assocStream) {
CHECK(!exAttributes);
VLOG(4) << "generating PUSH_PROMISE for stream=" << stream;
} else if (exAttributes) {
CHECK(!assocStream);
VLOG(4) << "generating ExHEADERS for stream=" << stream
<< " with control stream=" << exAttributes->controlStream
<< " unidirectional=" << exAttributes->unidirectional;
} else {
VLOG(4) << "generating HEADERS for stream=" << stream;
}
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing HEADERS/PROMISE for stream=" << stream <<
" ingressGoawayAck_=" << ingressGoawayAck_;
if (size) {
size->uncompressed = 0;
size->compressed = 0;
}
return;
}
if (msg.isRequest()) {
DCHECK(transportDirection_ == TransportDirection::UPSTREAM ||
assocStream || exAttributes);
if (msg.isEgressWebsocketUpgrade()) {
upgradedStreams_.insert(stream);
}
} else {
DCHECK(transportDirection_ == TransportDirection::DOWNSTREAM ||
exAttributes);
}
std::vector<std::string> temps;
auto allHeaders = CodecUtil::prepareMessageForCompression(msg, temps);
auto out = encodeHeaders(msg.getHeaders(), allHeaders, size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto res = msg.getHTTP2Priority();
auto remainingFrameSize = maxFrameSize;
if (res) {
pri = http2::PriorityUpdate{std::get<0>(*res), std::get<1>(*res),
std::get<2>(*res)};
DCHECK_GE(remainingFrameSize, http2::kFramePrioritySize)
<< "no enough space for priority? frameHeadroom=" << remainingFrameSize;
remainingFrameSize -= http2::kFramePrioritySize;
}
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
if (assocStream) {
DCHECK_EQ(transportDirection_, TransportDirection::DOWNSTREAM);
DCHECK(!eom);
generateHeaderCallbackWrapper(stream, http2::FrameType::PUSH_PROMISE,
http2::writePushPromise(writeBuf,
*assocStream,
stream,
std::move(chunk),
http2::kNoPadding,
endHeaders));
} else if (exAttributes) {
generateHeaderCallbackWrapper(
stream,
http2::FrameType::EX_HEADERS,
http2::writeExHeaders(writeBuf,
std::move(chunk),
stream,
*exAttributes,
pri,
http2::kNoPadding,
eom,
endHeaders));
} else {
generateHeaderCallbackWrapper(stream, http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
eom,
endHeaders));
}
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
}
void HTTP2Codec::generateContinuation(folly::IOBufQueue& writeBuf,
folly::IOBufQueue& queue,
StreamID stream,
size_t maxFrameSize) {
bool endHeaders = false;
while (!endHeaders) {
auto chunk = queue.split(std::min(maxFrameSize, queue.chainLength()));
endHeaders = (queue.chainLength() == 0);
VLOG(4) << "generating CONTINUATION for stream=" << stream;
generateHeaderCallbackWrapper(
stream,
http2::FrameType::CONTINUATION,
http2::writeContinuation(
writeBuf, stream, endHeaders, std::move(chunk)));
}
}
std::unique_ptr<folly::IOBuf> HTTP2Codec::encodeHeaders(
const HTTPHeaders& headers,
std::vector<compress::Header>& allHeaders,
HTTPHeaderSize* size) {
headerCodec_.setEncodeHeadroom(http2::kFrameHeaderSize +
http2::kFrameHeadersBaseMaxSize);
auto out = headerCodec_.encode(allHeaders);
if (size) {
*size = headerCodec_.getEncodedSize();
}
if (headerCodec_.getEncodedSize().uncompressed >
ingressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE,
std::numeric_limits<uint32_t>::max())) {
// The remote side told us they don't want headers this large...
// but this function has no mechanism to fail
string serializedHeaders;
headers.forEach(
[&serializedHeaders] (const string& name, const string& value) {
serializedHeaders = folly::to<string>(serializedHeaders, "\\n", name,
":", value);
});
LOG(ERROR) << "generating HEADERS frame larger than peer maximum nHeaders="
<< headers.size() << " all headers="
<< serializedHeaders;
}
return out;
}
size_t HTTP2Codec::generateHeaderCallbackWrapper(StreamID stream,
http2::FrameType type,
size_t length) {
if (callback_) {
callback_->onGenerateFrameHeader(stream,
static_cast<uint8_t>(type),
length);
}
return length;
}
size_t HTTP2Codec::generateBody(folly::IOBufQueue& writeBuf,
StreamID stream,
std::unique_ptr<folly::IOBuf> chain,
folly::Optional<uint8_t> padding,
bool eom) {
// todo: generate random padding for everything?
size_t written = 0;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing DATA for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(chain));
size_t maxFrameSize = maxSendFrameSize();
while (queue.chainLength() > maxFrameSize) {
auto chunk = queue.split(maxFrameSize);
written += generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
std::move(chunk),
stream,
padding,
false,
reuseIOBufHeadroomForData_));
}
return written + generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
queue.move(),
stream,
padding,
eom,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateChunkHeader(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/,
size_t /*length*/) {
// HTTP/2 has no chunk headers
return 0;
}
size_t HTTP2Codec::generateChunkTerminator(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/) {
// HTTP/2 has no chunk terminators
return 0;
}
size_t HTTP2Codec::generateTrailers(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPHeaders& trailers) {
VLOG(4) << "generating TRAILERS for stream=" << stream;
std::vector<compress::Header> allHeaders;
CodecUtil::appendHeaders(trailers, allHeaders, HTTP_HEADER_NONE);
HTTPHeaderSize size;
auto out = encodeHeaders(trailers, allHeaders, &size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto remainingFrameSize = maxFrameSize;
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
generateHeaderCallbackWrapper(stream,
http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
true /*eom*/,
endHeaders));
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
return size.compressed;
}
size_t HTTP2Codec::generateEOM(folly::IOBufQueue& writeBuf,
StreamID stream) {
VLOG(4) << "sending EOM for stream=" << stream;
upgradedStreams_.erase(stream);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed EOM for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
nullptr,
stream,
http2::kNoPadding,
true,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateRstStream(folly::IOBufQueue& writeBuf,
StreamID stream,
ErrorCode statusCode) {
VLOG(4) << "sending RST_STREAM for stream=" << stream
<< " with code=" << getErrorCodeString(statusCode);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed RST_STREAM for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
// Suppress any EOM callback for the current frame.
if (stream == curHeader_.stream) {
curHeader_.flags &= ~http2::END_STREAM;
pendingEndStreamHandling_ = false;
ingressWebsocketUpgrade_ = false;
}
upgradedStreams_.erase(stream);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending RST_STREAM with code=" << getErrorCodeString(statusCode)
<< " for stream=" << stream << " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToReset(statusCode);
return generateHeaderCallbackWrapper(stream, http2::FrameType::RST_STREAM,
http2::writeRstStream(writeBuf, stream, code));
}
size_t HTTP2Codec::generateGoaway(folly::IOBufQueue& writeBuf,
StreamID lastStream,
ErrorCode statusCode,
std::unique_ptr<folly::IOBuf> debugData) {
DCHECK_LE(lastStream, egressGoawayAck_) << "Cannot increase last good stream";
egressGoawayAck_ = lastStream;
if (sessionClosing_ == ClosingState::CLOSED) {
VLOG(4) << "Not sending GOAWAY for closed session";
return 0;
}
switch (sessionClosing_) {
case ClosingState::OPEN:
case ClosingState::OPEN_WITH_GRACEFUL_DRAIN_ENABLED:
if (lastStream == std::numeric_limits<int32_t>::max() &&
statusCode == ErrorCode::NO_ERROR) {
sessionClosing_ = ClosingState::FIRST_GOAWAY_SENT;
} else {
// The user of this codec decided not to do the double goaway
// drain, or this is not a graceful shutdown
sessionClosing_ = ClosingState::CLOSED;
}
break;
case ClosingState::FIRST_GOAWAY_SENT:
sessionClosing_ = ClosingState::CLOSED;
break;
case ClosingState::CLOSING:
case ClosingState::CLOSED:
LOG(FATAL) << "unreachable";
}
VLOG(4) << "Sending GOAWAY with last acknowledged stream="
<< lastStream << " with code=" << getErrorCodeString(statusCode);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending GOAWAY with last acknowledged stream=" << lastStream
<< " with code=" << getErrorCodeString(statusCode)
<< " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToGoaway(statusCode);
return generateHeaderCallbackWrapper(
0,
http2::FrameType::GOAWAY,
http2::writeGoaway(writeBuf,
lastStream,
code,
std::move(debugData)));
}
size_t HTTP2Codec::generatePingRequest(folly::IOBufQueue& writeBuf) {
// should probably let the caller specify when integrating with session
// we know HTTPSession sets up events to track ping latency
uint64_t opaqueData = folly::Random::rand64();
VLOG(4) << "Generating ping request with opaqueData=" << opaqueData;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, opaqueData, false /* no ack */));
}
size_t HTTP2Codec::generatePingReply(folly::IOBufQueue& writeBuf,
uint64_t uniqueID) {
VLOG(4) << "Generating ping reply with opaqueData=" << uniqueID;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, uniqueID, true /* ack */));
}
size_t HTTP2Codec::generateSettings(folly::IOBufQueue& writeBuf) {
std::deque<SettingPair> settings;
for (auto& setting: egressSettings_.getAllSettings()) {
switch (setting.id) {
case SettingsId::HEADER_TABLE_SIZE:
if (pendingTableMaxSize_) {
LOG(ERROR) << "Can't have more than one settings in flight, skipping";
continue;
} else {
pendingTableMaxSize_ = setting.value;
}
break;
case SettingsId::ENABLE_PUSH:
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
// HTTP/2 spec says downstream must not send this flag
// HTTP2Codec uses it to determine if push features are enabled
continue;
} else {
CHECK(setting.value == 0 || setting.value == 1);
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
case SettingsId::INITIAL_WINDOW_SIZE:
case SettingsId::MAX_FRAME_SIZE:
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
headerCodec_.setMaxUncompressed(setting.value);
break;
case SettingsId::ENABLE_EX_HEADERS:
CHECK(setting.value == 0 || setting.value == 1);
if (setting.value == 0) {
continue; // just skip the experimental setting if disabled
} else {
VLOG(4) << "generating ENABLE_EX_HEADERS=" << setting.value;
}
break;
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.value == 0) {
continue;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
default:
LOG(ERROR) << "ignore unknown settingsId="
<< std::underlying_type<SettingsId>::type(setting.id)
<< " value=" << setting.value;
continue;
}
settings.push_back(SettingPair(setting.id, setting.value));
}
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating " << (unsigned)settings.size() << " settings";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettings(writeBuf, settings));
}
void HTTP2Codec::requestUpgrade(HTTPMessage& request) {
static folly::ThreadLocalPtr<HTTP2Codec> defaultCodec;
if (!defaultCodec.get()) {
defaultCodec.reset(new HTTP2Codec(TransportDirection::UPSTREAM));
}
auto& headers = request.getHeaders();
headers.set(HTTP_HEADER_UPGRADE, http2::kProtocolCleartextString);
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION, "Upgrade", false)) {
headers.add(HTTP_HEADER_CONNECTION, "Upgrade");
}
IOBufQueue writeBuf{IOBufQueue::cacheChainLength()};
defaultCodec->generateSettings(writeBuf);
// fake an ack since defaultCodec gets reused
defaultCodec->handleSettingsAck();
writeBuf.trimStart(http2::kFrameHeaderSize);
auto buf = writeBuf.move();
buf->coalesce();
headers.set(http2::kProtocolSettingsHeader,
base64url_encode(folly::ByteRange(buf->data(), buf->length())));
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(),
false)) {
headers.add(HTTP_HEADER_CONNECTION, http2::kProtocolSettingsHeader);
}
}
size_t HTTP2Codec::generateSettingsAck(folly::IOBufQueue& writeBuf) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating settings ack";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettingsAck(writeBuf));
}
size_t HTTP2Codec::generateWindowUpdate(folly::IOBufQueue& writeBuf,
StreamID stream,
uint32_t delta) {
VLOG(4) << "generating window update for stream=" << stream
<< ": Processed " << delta << " bytes";
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed WINDOW_UPDATE for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(stream, http2::FrameType::WINDOW_UPDATE,
http2::writeWindowUpdate(writeBuf, stream, delta));
}
size_t HTTP2Codec::generatePriority(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage::HTTPPriority& pri) {
VLOG(4) << "generating priority for stream=" << stream;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed PRIORITY for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::PRIORITY,
http2::writePriority(writeBuf, stream,
{std::get<0>(pri),
std::get<1>(pri),
std::get<2>(pri)}));
}
size_t HTTP2Codec::generateCertificateRequest(
folly::IOBufQueue& writeBuf,
uint16_t requestId,
std::unique_ptr<folly::IOBuf> certificateRequestData) {
VLOG(4) << "generating CERTIFICATE_REQUEST with Request-ID=" << requestId;
return http2::writeCertificateRequest(
writeBuf, requestId, std::move(certificateRequestData));
}
size_t HTTP2Codec::generateCertificate(folly::IOBufQueue& writeBuf,
uint16_t certId,
std::unique_ptr<folly::IOBuf> certData) {
size_t written = 0;
VLOG(4) << "sending CERTIFICATE with Cert-ID=" << certId << "for stream=0";
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(certData));
// The maximum size of an autenticator fragment, combined with the Cert-ID can
// not exceed the maximal allowable size of a sent frame.
size_t maxChunkSize = maxSendFrameSize() - sizeof(certId);
while (queue.chainLength() > maxChunkSize) {
auto chunk = queue.splitAtMost(maxChunkSize);
written +=
http2::writeCertificate(writeBuf, certId, std::move(chunk), true);
}
return written +
http2::writeCertificate(writeBuf, certId, queue.move(), false);
}
bool HTTP2Codec::checkConnectionError(ErrorCode err, const folly::IOBuf* buf) {
if (err != ErrorCode::NO_ERROR) {
LOG(ERROR) << "Connection error " << getErrorCodeString(err)
<< " with ingress=";
VLOG(3) << IOBufPrinter::printHexFolly(buf, true);
if (callback_) {
std::string errorDescription = goawayErrorMessage_.empty() ?
"Connection error" : goawayErrorMessage_;
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
errorDescription);
ex.setCodecStatusCode(err);
callback_->onError(0, ex, false);
}
return true;
}
return false;
}
void HTTP2Codec::streamError(const std::string& msg, ErrorCode code,
bool newTxn) {
HTTPException error(HTTPException::Direction::INGRESS_AND_EGRESS,
msg);
error.setCodecStatusCode(code);
if (callback_) {
callback_->onError(curHeader_.stream, error, newTxn);
}
}
HTTPCodec::StreamID
HTTP2Codec::mapPriorityToDependency(uint8_t priority) const {
// If the priority is out of the maximum index of virtual nodes array, we
// return the lowest level virtual node as a punishment of not setting
// priority correctly.
return virtualPriorityNodes_.empty()
? 0
: virtualPriorityNodes_[
std::min(priority, uint8_t(virtualPriorityNodes_.size() - 1))];
}
bool HTTP2Codec::parsingTrailers() const {
// HEADERS frame is used for request/response headers and trailers.
// Per spec, specific role of HEADERS frame is determined by it's postion
// within the stream. We don't keep full stream state in this codec,
// thus using heuristics to distinguish between headers/trailers.
// For DOWNSTREAM case, request headers HEADERS frame would be creating
// new stream, thus HEADERS on existing stream ID are considered trailers
// (see checkNewStream).
// For UPSTREAM case, response headers are required to have status code,
// thus if no status code we consider that trailers.
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::CONTINUATION) {
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
return parsingDownstreamTrailers_;
} else {
return !decodeInfo_.hasStatus();
}
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_600_0 |
crossvul-cpp_data_bad_4877_1 | #include "Hub.h"
namespace uWS {
template <const bool isServer>
bool WebSocketProtocol<isServer>::setCompressed(void *user) {
uS::Socket s((uv_poll_t *) user);
typename WebSocket<isServer>::Data *webSocketData = (typename WebSocket<isServer>::Data *) s.getSocketData();
if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::ENABLED) {
webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME;
return true;
} else {
return false;
}
}
template <const bool isServer>
bool WebSocketProtocol<isServer>::refusePayloadLength(void *user, int length) {
return length > 16777216;
}
template <const bool isServer>
void WebSocketProtocol<isServer>::forceClose(void *user) {
WebSocket<isServer>((uv_poll_t *) user).terminate();
}
template <const bool isServer>
bool WebSocketProtocol<isServer>::handleFragment(char *data, size_t length, unsigned int remainingBytes, int opCode, bool fin, void *user) {
uS::Socket s((uv_poll_t *) user);
typename WebSocket<isServer>::Data *webSocketData = (typename WebSocket<isServer>::Data *) s.getSocketData();
if (opCode < 3) {
if (!remainingBytes && fin && !webSocketData->fragmentBuffer.length()) {
if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME) {
webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::ENABLED;
Hub *hub = ((Group<isServer> *) s.getSocketData()->nodeData)->hub;
data = hub->inflate(data, length);
}
if (opCode == 1 && !isValidUtf8((unsigned char *) data, length)) {
forceClose(user);
return true;
}
((Group<isServer> *) s.getSocketData()->nodeData)->messageHandler(WebSocket<isServer>(s), data, length, (OpCode) opCode);
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
} else {
webSocketData->fragmentBuffer.append(data, length);
if (!remainingBytes && fin) {
length = webSocketData->fragmentBuffer.length();
if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME) {
webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::ENABLED;
Hub *hub = ((Group<isServer> *) s.getSocketData()->nodeData)->hub;
webSocketData->fragmentBuffer.append("....");
data = hub->inflate((char *) webSocketData->fragmentBuffer.data(), length);
} else {
data = (char *) webSocketData->fragmentBuffer.data();
}
if (opCode == 1 && !isValidUtf8((unsigned char *) data, length)) {
forceClose(user);
return true;
}
((Group<isServer> *) s.getSocketData()->nodeData)->messageHandler(WebSocket<isServer>(s), data, length, (OpCode) opCode);
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
webSocketData->fragmentBuffer.clear();
}
}
} else {
// todo: we don't need to buffer up in most cases!
webSocketData->controlBuffer.append(data, length);
if (!remainingBytes && fin) {
if (opCode == CLOSE) {
CloseFrame closeFrame = parseClosePayload((char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
WebSocket<isServer>(s).close(closeFrame.code, closeFrame.message, closeFrame.length);
return true;
} else {
if (opCode == PING) {
WebSocket<isServer>(s).send(webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length(), (OpCode) OpCode::PONG);
((Group<isServer> *) s.getSocketData()->nodeData)->pingHandler(WebSocket<isServer>(s), (char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
} else if (opCode == PONG) {
((Group<isServer> *) s.getSocketData()->nodeData)->pongHandler(WebSocket<isServer>(s), (char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
if (s.isClosed() || s.isShuttingDown()) {
return true;
}
}
}
webSocketData->controlBuffer.clear();
}
}
return false;
}
template class WebSocketProtocol<SERVER>;
template class WebSocketProtocol<CLIENT>;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_4877_1 |
crossvul-cpp_data_good_2411_1 | /*
Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "session_base.hpp"
#include "i_engine.hpp"
#include "err.hpp"
#include "pipe.hpp"
#include "likely.hpp"
#include "tcp_connecter.hpp"
#include "ipc_connecter.hpp"
#include "pgm_sender.hpp"
#include "pgm_receiver.hpp"
#include "address.hpp"
#include "ctx.hpp"
#include "req.hpp"
zmq::session_base_t *zmq::session_base_t::create (class io_thread_t *io_thread_,
bool connect_, class socket_base_t *socket_, const options_t &options_,
const address_t *addr_)
{
session_base_t *s = NULL;
switch (options_.type) {
case ZMQ_REQ:
s = new (std::nothrow) req_session_t (io_thread_, connect_,
socket_, options_, addr_);
break;
case ZMQ_DEALER:
case ZMQ_REP:
case ZMQ_ROUTER:
case ZMQ_PUB:
case ZMQ_XPUB:
case ZMQ_SUB:
case ZMQ_XSUB:
case ZMQ_PUSH:
case ZMQ_PULL:
case ZMQ_PAIR:
case ZMQ_STREAM:
s = new (std::nothrow) session_base_t (io_thread_, connect_,
socket_, options_, addr_);
break;
default:
errno = EINVAL;
return NULL;
}
alloc_assert (s);
return s;
}
zmq::session_base_t::session_base_t (class io_thread_t *io_thread_,
bool connect_, class socket_base_t *socket_, const options_t &options_,
const address_t *addr_) :
own_t (io_thread_, options_),
io_object_t (io_thread_),
connect (connect_),
pipe (NULL),
zap_pipe (NULL),
incomplete_in (false),
pending (false),
engine (NULL),
socket (socket_),
io_thread (io_thread_),
has_linger_timer (false),
addr (addr_)
{
}
zmq::session_base_t::~session_base_t ()
{
zmq_assert (!pipe);
zmq_assert (!zap_pipe);
// If there's still a pending linger timer, remove it.
if (has_linger_timer) {
cancel_timer (linger_timer_id);
has_linger_timer = false;
}
// Close the engine.
if (engine)
engine->terminate ();
delete addr;
}
void zmq::session_base_t::attach_pipe (pipe_t *pipe_)
{
zmq_assert (!is_terminating ());
zmq_assert (!pipe);
zmq_assert (pipe_);
pipe = pipe_;
pipe->set_event_sink (this);
}
int zmq::session_base_t::pull_msg (msg_t *msg_)
{
if (!pipe || !pipe->read (msg_)) {
errno = EAGAIN;
return -1;
}
incomplete_in = msg_->flags () & msg_t::more ? true : false;
return 0;
}
int zmq::session_base_t::push_msg (msg_t *msg_)
{
if (pipe && pipe->write (msg_)) {
int rc = msg_->init ();
errno_assert (rc == 0);
return 0;
}
errno = EAGAIN;
return -1;
}
int zmq::session_base_t::read_zap_msg (msg_t *msg_)
{
if (zap_pipe == NULL) {
errno = ENOTCONN;
return -1;
}
if (!zap_pipe->read (msg_)) {
errno = EAGAIN;
return -1;
}
return 0;
}
int zmq::session_base_t::write_zap_msg (msg_t *msg_)
{
if (zap_pipe == NULL) {
errno = ENOTCONN;
return -1;
}
const bool ok = zap_pipe->write (msg_);
zmq_assert (ok);
if ((msg_->flags () & msg_t::more) == 0)
zap_pipe->flush ();
const int rc = msg_->init ();
errno_assert (rc == 0);
return 0;
}
void zmq::session_base_t::reset ()
{
}
void zmq::session_base_t::flush ()
{
if (pipe)
pipe->flush ();
}
void zmq::session_base_t::clean_pipes ()
{
if (pipe) {
// Get rid of half-processed messages in the out pipe. Flush any
// unflushed messages upstream.
pipe->rollback ();
pipe->flush ();
// Remove any half-read message from the in pipe.
while (incomplete_in) {
msg_t msg;
int rc = msg.init ();
errno_assert (rc == 0);
rc = pull_msg (&msg);
errno_assert (rc == 0);
rc = msg.close ();
errno_assert (rc == 0);
}
}
}
void zmq::session_base_t::pipe_terminated (pipe_t *pipe_)
{
// Drop the reference to the deallocated pipe if required.
zmq_assert (pipe_ == pipe
|| pipe_ == zap_pipe
|| terminating_pipes.count (pipe_) == 1);
if (pipe_ == pipe)
// If this is our current pipe, remove it
pipe = NULL;
else
if (pipe_ == zap_pipe) {
zap_pipe = NULL;
}
else
// Remove the pipe from the detached pipes set
terminating_pipes.erase (pipe_);
if (!is_terminating () && options.raw_sock) {
if (engine) {
engine->terminate ();
engine = NULL;
}
terminate ();
}
// If we are waiting for pending messages to be sent, at this point
// we are sure that there will be no more messages and we can proceed
// with termination safely.
if (pending && !pipe && !zap_pipe && terminating_pipes.empty ())
proceed_with_term ();
}
void zmq::session_base_t::read_activated (pipe_t *pipe_)
{
// Skip activating if we're detaching this pipe
if (unlikely(pipe_ != pipe && pipe_ != zap_pipe)) {
zmq_assert (terminating_pipes.count (pipe_) == 1);
return;
}
if (unlikely (engine == NULL)) {
pipe->check_read ();
return;
}
if (likely (pipe_ == pipe))
engine->restart_output ();
else
engine->zap_msg_available ();
}
void zmq::session_base_t::write_activated (pipe_t *pipe_)
{
// Skip activating if we're detaching this pipe
if (pipe != pipe_) {
zmq_assert (terminating_pipes.count (pipe_) == 1);
return;
}
if (engine)
engine->restart_input ();
}
void zmq::session_base_t::hiccuped (pipe_t *)
{
// Hiccups are always sent from session to socket, not the other
// way round.
zmq_assert (false);
}
zmq::socket_base_t *zmq::session_base_t::get_socket ()
{
return socket;
}
void zmq::session_base_t::process_plug ()
{
if (connect)
start_connecting (false);
}
int zmq::session_base_t::zap_connect ()
{
zmq_assert (zap_pipe == NULL);
endpoint_t peer = find_endpoint ("inproc://zeromq.zap.01");
if (peer.socket == NULL) {
errno = ECONNREFUSED;
return -1;
}
if (peer.options.type != ZMQ_REP
&& peer.options.type != ZMQ_ROUTER) {
errno = ECONNREFUSED;
return -1;
}
// Create a bi-directional pipe that will connect
// session with zap socket.
object_t *parents [2] = {this, peer.socket};
pipe_t *new_pipes [2] = {NULL, NULL};
int hwms [2] = {0, 0};
bool conflates [2] = {false, false};
int rc = pipepair (parents, new_pipes, hwms, conflates);
errno_assert (rc == 0);
// Attach local end of the pipe to this socket object.
zap_pipe = new_pipes [0];
zap_pipe->set_nodelay ();
zap_pipe->set_event_sink (this);
send_bind (peer.socket, new_pipes [1], false);
// Send empty identity if required by the peer.
if (peer.options.recv_identity) {
msg_t id;
rc = id.init ();
errno_assert (rc == 0);
id.set_flags (msg_t::identity);
bool ok = zap_pipe->write (&id);
zmq_assert (ok);
zap_pipe->flush ();
}
return 0;
}
bool zmq::session_base_t::zap_enabled ()
{
return (
options.mechanism != ZMQ_NULL ||
(options.mechanism == ZMQ_NULL && options.zap_domain.length() > 0)
);
}
void zmq::session_base_t::process_attach (i_engine *engine_)
{
zmq_assert (engine_ != NULL);
// Create the pipe if it does not exist yet.
if (!pipe && !is_terminating ()) {
object_t *parents [2] = {this, socket};
pipe_t *pipes [2] = {NULL, NULL};
bool conflate = options.conflate &&
(options.type == ZMQ_DEALER ||
options.type == ZMQ_PULL ||
options.type == ZMQ_PUSH ||
options.type == ZMQ_PUB ||
options.type == ZMQ_SUB);
int hwms [2] = {conflate? -1 : options.rcvhwm,
conflate? -1 : options.sndhwm};
bool conflates [2] = {conflate, conflate};
int rc = pipepair (parents, pipes, hwms, conflates);
errno_assert (rc == 0);
// Plug the local end of the pipe.
pipes [0]->set_event_sink (this);
// Remember the local end of the pipe.
zmq_assert (!pipe);
pipe = pipes [0];
// Ask socket to plug into the remote end of the pipe.
send_bind (socket, pipes [1]);
}
// Plug in the engine.
zmq_assert (!engine);
engine = engine_;
engine->plug (io_thread, this);
}
void zmq::session_base_t::detach ()
{
// Engine is dead. Let's forget about it.
engine = NULL;
// Remove any half-done messages from the pipes.
clean_pipes ();
// Send the event to the derived class.
detached ();
// Just in case there's only a delimiter in the pipe.
if (pipe)
pipe->check_read ();
if (zap_pipe)
zap_pipe->check_read ();
}
void zmq::session_base_t::process_term (int linger_)
{
zmq_assert (!pending);
// If the termination of the pipe happens before the term command is
// delivered there's nothing much to do. We can proceed with the
// standard termination immediately.
if (!pipe && !zap_pipe) {
proceed_with_term ();
return;
}
pending = true;
if (pipe != NULL) {
// If there's finite linger value, delay the termination.
// If linger is infinite (negative) we don't even have to set
// the timer.
if (linger_ > 0) {
zmq_assert (!has_linger_timer);
add_timer (linger_, linger_timer_id);
has_linger_timer = true;
}
// Start pipe termination process. Delay the termination till all messages
// are processed in case the linger time is non-zero.
pipe->terminate (linger_ != 0);
// TODO: Should this go into pipe_t::terminate ?
// In case there's no engine and there's only delimiter in the
// pipe it wouldn't be ever read. Thus we check for it explicitly.
pipe->check_read ();
}
if (zap_pipe != NULL)
zap_pipe->terminate (false);
}
void zmq::session_base_t::proceed_with_term ()
{
// The pending phase has just ended.
pending = false;
// Continue with standard termination.
own_t::process_term (0);
}
void zmq::session_base_t::timer_event (int id_)
{
// Linger period expired. We can proceed with termination even though
// there are still pending messages to be sent.
zmq_assert (id_ == linger_timer_id);
has_linger_timer = false;
// Ask pipe to terminate even though there may be pending messages in it.
zmq_assert (pipe);
pipe->terminate (false);
}
void zmq::session_base_t::detached ()
{
// Transient session self-destructs after peer disconnects.
if (!connect) {
terminate ();
return;
}
// For delayed connect situations, terminate the pipe
// and reestablish later on
if (pipe && options.immediate == 1
&& addr->protocol != "pgm" && addr->protocol != "epgm") {
pipe->hiccup ();
pipe->terminate (false);
terminating_pipes.insert (pipe);
pipe = NULL;
}
reset ();
// Reconnect.
if (options.reconnect_ivl != -1)
start_connecting (true);
// For subscriber sockets we hiccup the inbound pipe, which will cause
// the socket object to resend all the subscriptions.
if (pipe && (options.type == ZMQ_SUB || options.type == ZMQ_XSUB))
pipe->hiccup ();
}
void zmq::session_base_t::start_connecting (bool wait_)
{
zmq_assert (connect);
// Choose I/O thread to run connecter in. Given that we are already
// running in an I/O thread, there must be at least one available.
io_thread_t *io_thread = choose_io_thread (options.affinity);
zmq_assert (io_thread);
// Create the connecter object.
if (addr->protocol == "tcp") {
tcp_connecter_t *connecter = new (std::nothrow) tcp_connecter_t (
io_thread, this, options, addr, wait_);
alloc_assert (connecter);
launch_child (connecter);
return;
}
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
if (addr->protocol == "ipc") {
ipc_connecter_t *connecter = new (std::nothrow) ipc_connecter_t (
io_thread, this, options, addr, wait_);
alloc_assert (connecter);
launch_child (connecter);
return;
}
#endif
#ifdef ZMQ_HAVE_OPENPGM
// Both PGM and EPGM transports are using the same infrastructure.
if (addr->protocol == "pgm" || addr->protocol == "epgm") {
zmq_assert (options.type == ZMQ_PUB || options.type == ZMQ_XPUB
|| options.type == ZMQ_SUB || options.type == ZMQ_XSUB);
// For EPGM transport with UDP encapsulation of PGM is used.
bool const udp_encapsulation = addr->protocol == "epgm";
// At this point we'll create message pipes to the session straight
// away. There's no point in delaying it as no concept of 'connect'
// exists with PGM anyway.
if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB) {
// PGM sender.
pgm_sender_t *pgm_sender = new (std::nothrow) pgm_sender_t (
io_thread, options);
alloc_assert (pgm_sender);
int rc = pgm_sender->init (udp_encapsulation, addr->address.c_str ());
errno_assert (rc == 0);
send_attach (this, pgm_sender);
}
else {
// PGM receiver.
pgm_receiver_t *pgm_receiver = new (std::nothrow) pgm_receiver_t (
io_thread, options);
alloc_assert (pgm_receiver);
int rc = pgm_receiver->init (udp_encapsulation, addr->address.c_str ());
errno_assert (rc == 0);
send_attach (this, pgm_receiver);
}
return;
}
#endif
zmq_assert (false);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_2411_1 |
crossvul-cpp_data_good_238_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Config.h>
#include <znc/FileUtils.h>
#include <stack>
#include <sstream>
struct ConfigStackEntry {
CString sTag;
CString sName;
CConfig Config;
ConfigStackEntry(const CString& Tag, const CString Name)
: sTag(Tag), sName(Name), Config() {}
};
CConfigEntry::CConfigEntry() : m_pSubConfig(nullptr) {}
CConfigEntry::CConfigEntry(const CConfig& Config)
: m_pSubConfig(new CConfig(Config)) {}
CConfigEntry::CConfigEntry(const CConfigEntry& other) : m_pSubConfig(nullptr) {
if (other.m_pSubConfig) m_pSubConfig = new CConfig(*other.m_pSubConfig);
}
CConfigEntry::~CConfigEntry() { delete m_pSubConfig; }
CConfigEntry& CConfigEntry::operator=(const CConfigEntry& other) {
delete m_pSubConfig;
if (other.m_pSubConfig)
m_pSubConfig = new CConfig(*other.m_pSubConfig);
else
m_pSubConfig = nullptr;
return *this;
}
bool CConfig::Parse(CFile& file, CString& sErrorMsg) {
CString sLine;
unsigned int uLineNum = 0;
CConfig* pActiveConfig = this;
std::stack<ConfigStackEntry> ConfigStack;
bool bCommented = false; // support for /**/ style comments
if (!file.Seek(0)) {
sErrorMsg = "Could not seek to the beginning of the config.";
return false;
}
while (file.ReadLine(sLine)) {
uLineNum++;
#define ERROR(arg) \
do { \
std::stringstream stream; \
stream << "Error on line " << uLineNum << ": " << arg; \
sErrorMsg = stream.str(); \
m_SubConfigs.clear(); \
m_ConfigEntries.clear(); \
return false; \
} while (0)
// Remove all leading spaces and trailing line endings
sLine.TrimLeft();
sLine.TrimRight("\r\n");
if (bCommented || sLine.StartsWith("/*")) {
/* Does this comment end on the same line again? */
bCommented = (!sLine.EndsWith("*/"));
continue;
}
if ((sLine.empty()) || (sLine.StartsWith("#")) ||
(sLine.StartsWith("//"))) {
continue;
}
if ((sLine.StartsWith("<")) && (sLine.EndsWith(">"))) {
sLine.LeftChomp();
sLine.RightChomp();
sLine.Trim();
CString sTag = sLine.Token(0);
CString sValue = sLine.Token(1, true);
sTag.Trim();
sValue.Trim();
if (sTag.TrimPrefix("/")) {
if (!sValue.empty())
ERROR("Malformated closing tag. Expected \"</" << sTag
<< ">\".");
if (ConfigStack.empty())
ERROR("Closing tag \"" << sTag << "\" which is not open.");
const struct ConfigStackEntry& entry = ConfigStack.top();
CConfig myConfig(entry.Config);
CString sName(entry.sName);
if (!sTag.Equals(entry.sTag))
ERROR("Closing tag \"" << sTag << "\" which is not open.");
// This breaks entry
ConfigStack.pop();
if (ConfigStack.empty())
pActiveConfig = this;
else
pActiveConfig = &ConfigStack.top().Config;
SubConfig& conf = pActiveConfig->m_SubConfigs[sTag.AsLower()];
SubConfig::const_iterator it = conf.find(sName);
if (it != conf.end())
ERROR("Duplicate entry for tag \"" << sTag << "\" name \""
<< sName << "\".");
conf[sName] = CConfigEntry(myConfig);
} else {
if (sValue.empty())
ERROR("Empty block name at begin of block.");
ConfigStack.push(ConfigStackEntry(sTag.AsLower(), sValue));
pActiveConfig = &ConfigStack.top().Config;
}
continue;
}
// If we have a regular line, figure out where it goes
CString sName = sLine.Token(0, false, "=");
CString sValue = sLine.Token(1, true, "=");
// Only remove the first space, people might want
// leading spaces (e.g. in the MOTD).
sValue.TrimPrefix(" ");
// We don't have any names with spaces, trim all
// leading/trailing spaces.
sName.Trim();
if (sName.empty() || sValue.empty()) ERROR("Malformed line");
CString sNameLower = sName.AsLower();
pActiveConfig->m_ConfigEntries[sNameLower].push_back(sValue);
}
if (bCommented) ERROR("Comment not closed at end of file.");
if (!ConfigStack.empty()) {
const CString& sTag = ConfigStack.top().sTag;
ERROR(
"Not all tags are closed at the end of the file. Inner-most open "
"tag is \""
<< sTag << "\".");
}
return true;
}
void CConfig::Write(CFile& File, unsigned int iIndentation) {
CString sIndentation = CString(iIndentation, '\t');
auto SingleLine = [](const CString& s) {
return s.Replace_n("\r", "").Replace_n("\n", "");
};
for (const auto& it : m_ConfigEntries) {
for (const CString& sValue : it.second) {
File.Write(SingleLine(sIndentation + it.first + " = " + sValue) +
"\n");
}
}
for (const auto& it : m_SubConfigs) {
for (const auto& it2 : it.second) {
File.Write("\n");
File.Write(SingleLine(sIndentation + "<" + it.first + " " +
it2.first + ">") +
"\n");
it2.second.m_pSubConfig->Write(File, iIndentation + 1);
File.Write(SingleLine(sIndentation + "</" + it.first + ">") + "\n");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_238_0 |
crossvul-cpp_data_good_600_2 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <string>
#include <vector>
#include <folly/Conv.h>
#include <folly/Range.h>
#include <folly/futures/Promise.h>
#include <folly/io/Cursor.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventBaseManager.h>
#include <folly/io/async/TimeoutManager.h>
#include <folly/io/async/test/MockAsyncTransport.h>
#include <folly/portability/GTest.h>
#include <proxygen/lib/http/codec/HTTPCodecFactory.h>
#include <proxygen/lib/http/codec/test/TestUtils.h>
#include <proxygen/lib/http/session/HTTPDirectResponseHandler.h>
#include <proxygen/lib/http/session/HTTPDownstreamSession.h>
#include <proxygen/lib/http/session/HTTPSession.h>
#include <proxygen/lib/http/session/test/HTTPSessionMocks.h>
#include <proxygen/lib/http/session/test/HTTPSessionTest.h>
#include <proxygen/lib/http/session/test/MockByteEventTracker.h>
#include <proxygen/lib/http/session/test/TestUtils.h>
#include <proxygen/lib/test/TestAsyncTransport.h>
#include <wangle/acceptor/ConnectionManager.h>
using namespace folly::io;
using namespace wangle;
using namespace folly;
using namespace proxygen;
using namespace std;
using namespace testing;
using namespace std::chrono;
using folly::Promise;
template <typename C>
class HTTPDownstreamTest : public testing::Test {
public:
explicit HTTPDownstreamTest(
std::vector<int64_t> flowControl = { -1, -1, -1 },
bool startImmediately = true)
: eventBase_(),
transport_(new TestAsyncTransport(&eventBase_)),
transactionTimeouts_(makeTimeoutSet(&eventBase_)),
flowControl_(flowControl) {
EXPECT_CALL(mockController_, getGracefulShutdownTimeout())
.WillRepeatedly(Return(std::chrono::milliseconds(0)));
EXPECT_CALL(mockController_, attachSession(_))
.WillRepeatedly(Invoke([&] (HTTPSessionBase* session) {
session->setPrioritySampled(true);
}));
HTTPSession::setDefaultReadBufferLimit(65536);
auto codec = makeServerCodec<typename C::Codec>(C::version);
rawCodec_ = codec.get();
// If the codec is H2, getHeaderIndexingStrategy will be called when setting
// up the codec
if (rawCodec_->getProtocol() == CodecProtocol::HTTP_2) {
EXPECT_CALL(mockController_, getHeaderIndexingStrategy())
.WillOnce(
Return(&testH2IndexingStrat_)
);
}
httpSession_ = new HTTPDownstreamSession(
transactionTimeouts_.get(),
std::move(AsyncTransportWrapper::UniquePtr(transport_)),
localAddr, peerAddr,
&mockController_,
std::move(codec),
mockTransportInfo /* no stats for now */,
nullptr);
for (auto& param: flowControl) {
if (param < 0) {
param = rawCodec_->getDefaultWindowSize();
}
}
// Ensure the H2 header indexing strategy was setup correctly if applicable
if (rawCodec_->getProtocol() == CodecProtocol::HTTP_2) {
HTTP2Codec* recastedCodec = dynamic_cast<HTTP2Codec*>(rawCodec_);
EXPECT_EQ(
recastedCodec->getHeaderIndexingStrategy(), &testH2IndexingStrat_);
}
httpSession_->setFlowControl(flowControl[0], flowControl[1],
flowControl[2]);
httpSession_->setEgressSettings({{ SettingsId::MAX_CONCURRENT_STREAMS, 80 },
{ SettingsId::HEADER_TABLE_SIZE, 5555 },
{ SettingsId::ENABLE_PUSH, 1 },
{ SettingsId::ENABLE_EX_HEADERS, 1 }});
if (startImmediately) {
httpSession_->startNow();
}
clientCodec_ = makeClientCodec<typename C::Codec>(C::version);
if (clientCodec_->getProtocol() == CodecProtocol::HTTP_2) {
clientCodec_->getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
}
clientCodec_->generateConnectionPreface(requests_);
clientCodec_->setCallback(&callbacks_);
}
HTTPCodec::StreamID sendRequest(const std::string& url = "/",
int8_t priority = 0,
bool eom = true) {
auto req = getGetRequest();
req.setURL(url);
req.setPriority(priority);
return sendRequest(req, eom);
}
HTTPCodec::StreamID sendRequest(const HTTPMessage& req, bool eom = true) {
auto streamID = clientCodec_->createStream();
clientCodec_->generateHeader(requests_, streamID, req, eom);
return streamID;
}
HTTPCodec::StreamID sendHeader() {
return sendRequest("/", 0, false);
}
Promise<Unit> sendRequestLater(HTTPMessage req, bool eof=false) {
Promise<Unit> reqp;
reqp.getFuture().then(&eventBase_, [=] {
sendRequest(req);
transport_->addReadEvent(requests_, milliseconds(0));
if (eof) {
transport_->addReadEOF(milliseconds(0));
}
});
return reqp;
}
void SetUp() override {
folly::EventBaseManager::get()->clearEventBase();
HTTPSession::setDefaultWriteBufferLimit(65536);
HTTP2PriorityQueue::setNodeLifetime(std::chrono::milliseconds(2));
}
void cleanup() {
EXPECT_CALL(mockController_, detachSession(_));
httpSession_->dropConnection();
}
std::unique_ptr<testing::StrictMock<MockHTTPHandler>>
addSimpleStrictHandler() {
std::unique_ptr<testing::StrictMock<MockHTTPHandler>> handler =
std::make_unique<testing::StrictMock<MockHTTPHandler>>();
// The ownership model here is suspect, but assume the callers won't destroy
// handler before it's requested
auto rawHandler = handler.get();
EXPECT_CALL(mockController_, getRequestHandler(testing::_, testing::_))
.WillOnce(testing::Return(rawHandler))
.RetiresOnSaturation();
EXPECT_CALL(*handler, setTransaction(testing::_))
.WillOnce(testing::SaveArg<0>(&handler->txn_));
return handler;
}
std::unique_ptr<testing::NiceMock<MockHTTPHandler>>
addSimpleNiceHandler() {
std::unique_ptr<testing::NiceMock<MockHTTPHandler>> handler =
std::make_unique<testing::NiceMock<MockHTTPHandler>>();
// See comment above
auto rawHandler = handler.get();
EXPECT_CALL(mockController_, getRequestHandler(testing::_, testing::_))
.WillOnce(testing::Return(rawHandler))
.RetiresOnSaturation();
EXPECT_CALL(*handler, setTransaction(testing::_))
.WillOnce(testing::SaveArg<0>(&handler->txn_));
return handler;
}
void onEOMTerminateHandlerExpectShutdown(MockHTTPHandler& handler) {
handler.expectEOM([&] { handler.terminate(); });
handler.expectDetachTransaction();
expectDetachSession();
}
void expectDetachSession() {
EXPECT_CALL(mockController_, detachSession(testing::_));
}
void addSingleByteReads(const char* data, milliseconds delay={}) {
for (const char* p = data; *p != '\0'; ++p) {
transport_->addReadEvent(p, 1, delay);
}
}
void flushRequestsAndLoop(
bool eof=false, milliseconds eofDelay=milliseconds(0),
milliseconds initialDelay=milliseconds(0),
std::function<void()> extraEventsFn = std::function<void()>()) {
flushRequests(eof, eofDelay, initialDelay, extraEventsFn);
eventBase_.loop();
}
void flushRequestsAndLoopN(uint64_t n,
bool eof=false, milliseconds eofDelay=milliseconds(0),
milliseconds initialDelay=milliseconds(0),
std::function<void()> extraEventsFn = std::function<void()>()) {
flushRequests(eof, eofDelay, initialDelay, extraEventsFn);
for (uint64_t i = 0; i < n; i++) {
eventBase_.loopOnce();
}
}
void flushRequests(
bool eof=false, milliseconds eofDelay=milliseconds(0),
milliseconds initialDelay=milliseconds(0),
std::function<void()> extraEventsFn = std::function<void()>()) {
transport_->addReadEvent(requests_, initialDelay);
if (extraEventsFn) {
extraEventsFn();
}
if (eof) {
transport_->addReadEOF(eofDelay);
}
transport_->startReadEvents();
}
void testSimpleUpgrade(
const std::string& upgradeHeader,
CodecProtocol expectedProtocol,
const std::string& expectedUpgradeHeader);
void gracefulShutdown() {
folly::DelayedDestruction::DestructorGuard g(httpSession_);
clientCodec_->generateGoaway(this->requests_, 0, ErrorCode::NO_ERROR);
expectDetachSession();
flushRequestsAndLoop(true);
}
void testPriorities(uint32_t numPriorities);
void testChunks(bool trailers);
void expect101(CodecProtocol expectedProtocol,
const std::string& expectedUpgrade,
bool expect100 = false) {
NiceMock<MockHTTPCodecCallback> callbacks;
EXPECT_CALL(callbacks, onMessageBegin(_, _));
EXPECT_CALL(callbacks, onNativeProtocolUpgrade(_, _, _, _))
.WillOnce(
Invoke([this, expectedUpgrade] (HTTPCodec::StreamID,
CodecProtocol,
const std::string&,
HTTPMessage& msg) {
EXPECT_EQ(msg.getStatusCode(), 101);
EXPECT_EQ(msg.getStatusMessage(), "Switching Protocols");
EXPECT_EQ(msg.getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE),
expectedUpgrade);
// also connection and date
EXPECT_EQ(msg.getHeaders().size(), 3);
breakParseOutput_ = true;
return true;
}));
// this comes before 101, but due to gmock this is backwards
if (expect100) {
EXPECT_CALL(callbacks, onMessageBegin(_, _))
.RetiresOnSaturation();
EXPECT_CALL(callbacks, onHeadersComplete(_, _))
.WillOnce(Invoke([] (HTTPCodec::StreamID,
std::shared_ptr<HTTPMessage> msg) {
LOG(INFO) << "100 headers";
EXPECT_EQ(msg->getStatusCode(), 100);
}))
.RetiresOnSaturation();
EXPECT_CALL(callbacks, onMessageComplete(_, _))
.RetiresOnSaturation();
}
clientCodec_->setCallback(&callbacks);
parseOutput(*clientCodec_);
clientCodec_ = HTTPCodecFactory::getCodec(expectedProtocol,
TransportDirection::UPSTREAM);
}
void expectResponse(uint32_t code = 200,
ErrorCode errorCode = ErrorCode::NO_ERROR,
bool expect100 = false, bool expectGoaway = false) {
expectResponses(1, code, errorCode, expect100, expectGoaway);
}
void expectResponses(uint32_t n, uint32_t code = 200,
ErrorCode errorCode = ErrorCode::NO_ERROR,
bool expect100 = false, bool expectGoaway = false) {
clientCodec_->setCallback(&callbacks_);
if (isParallelCodecProtocol(clientCodec_->getProtocol())) {
EXPECT_CALL(callbacks_, onSettings(_))
.WillOnce(Invoke([this] (const SettingsList& settings) {
if (flowControl_[0] > 0) {
bool foundInitialWindow = false;
for (const auto& setting: settings) {
if (setting.id == SettingsId::INITIAL_WINDOW_SIZE) {
EXPECT_EQ(flowControl_[0], setting.value);
foundInitialWindow = true;
}
}
EXPECT_TRUE(foundInitialWindow);
}
}));
}
if (flowControl_[2] > 0) {
int64_t sessionDelta =
flowControl_[2] - clientCodec_->getDefaultWindowSize();
if (clientCodec_->supportsSessionFlowControl() && sessionDelta) {
EXPECT_CALL(callbacks_, onWindowUpdate(0, sessionDelta));
}
}
if (flowControl_[1] > 0) {
size_t initWindow = flowControl_[0] > 0 ?
flowControl_[0] : clientCodec_->getDefaultWindowSize();
int64_t streamDelta = flowControl_[1] - initWindow;
if (clientCodec_->supportsStreamFlowControl() && streamDelta) {
EXPECT_CALL(callbacks_, onWindowUpdate(1, streamDelta));
}
}
if (expectGoaway) {
EXPECT_CALL(callbacks_, onGoaway(HTTPCodec::StreamID(1),
ErrorCode::NO_ERROR, _));
}
for (uint32_t i = 0; i < n; i++) {
uint8_t times = (expect100) ? 2 : 1;
EXPECT_CALL(callbacks_, onMessageBegin(_, _))
.Times(times).RetiresOnSaturation();
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.WillOnce(Invoke([code] (HTTPCodec::StreamID,
std::shared_ptr<HTTPMessage> msg) {
EXPECT_EQ(msg->getStatusCode(), code);
}));
if (expect100) {
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.WillOnce(Invoke([] (HTTPCodec::StreamID,
std::shared_ptr<HTTPMessage> msg) {
EXPECT_EQ(msg->getStatusCode(), 100);
}))
.RetiresOnSaturation();
}
if (errorCode != ErrorCode::NO_ERROR) {
EXPECT_CALL(callbacks_, onAbort(_, _))
.WillOnce(Invoke([errorCode] (HTTPCodec::StreamID,
ErrorCode error) {
EXPECT_EQ(error, errorCode);
}));
}
EXPECT_CALL(callbacks_, onBody(_, _, _)).RetiresOnSaturation();
EXPECT_CALL(callbacks_, onMessageComplete(_, _)).RetiresOnSaturation();
}
parseOutput(*clientCodec_);
}
void parseOutput(HTTPCodec& clientCodec) {
auto writeEvents = transport_->getWriteEvents();
while (!breakParseOutput_ &&
(!writeEvents->empty() || !parseOutputStream_.empty())) {
if (!writeEvents->empty()) {
auto event = writeEvents->front();
auto vec = event->getIoVec();
for (size_t i = 0; i < event->getCount(); i++) {
parseOutputStream_.append(
IOBuf::copyBuffer(vec[i].iov_base, vec[i].iov_len));
}
writeEvents->pop_front();
}
uint32_t consumed = clientCodec.onIngress(*parseOutputStream_.front());
parseOutputStream_.split(consumed);
}
if (!breakParseOutput_) {
EXPECT_EQ(parseOutputStream_.chainLength(), 0);
}
breakParseOutput_ = false;
}
void resumeWritesInLoop() {
eventBase_.runInLoop([this] { transport_->resumeWrites(); });
}
void resumeWritesAfterDelay(milliseconds delay) {
eventBase_.runAfterDelay([this] { transport_->resumeWrites(); },
delay.count());
}
MockByteEventTracker* setMockByteEventTracker() {
auto byteEventTracker = new MockByteEventTracker(nullptr);
httpSession_->setByteEventTracker(
std::unique_ptr<ByteEventTracker>(byteEventTracker));
EXPECT_CALL(*byteEventTracker, preSend(_, _, _))
.WillRepeatedly(Return(0));
EXPECT_CALL(*byteEventTracker, drainByteEvents())
.WillRepeatedly(Return(0));
EXPECT_CALL(*byteEventTracker, processByteEvents(_, _))
.WillRepeatedly(Invoke([]
(std::shared_ptr<ByteEventTracker> self,
uint64_t bytesWritten) {
return self->ByteEventTracker::processByteEvents(
self,
bytesWritten);
}));
return byteEventTracker;
}
protected:
EventBase eventBase_;
TestAsyncTransport* transport_; // invalid once httpSession_ is destroyed
folly::HHWheelTimer::UniquePtr transactionTimeouts_;
std::vector<int64_t> flowControl_;
StrictMock<MockController> mockController_;
HTTPDownstreamSession* httpSession_;
IOBufQueue requests_{IOBufQueue::cacheChainLength()};
unique_ptr<HTTPCodec> clientCodec_;
NiceMock<MockHTTPCodecCallback> callbacks_;
IOBufQueue parseOutputStream_{IOBufQueue::cacheChainLength()};
bool breakParseOutput_{false};
typename C::Codec* rawCodec_{nullptr};
HeaderIndexingStrategy testH2IndexingStrat_;
};
// Uses TestAsyncTransport
using HTTPDownstreamSessionTest = HTTPDownstreamTest<HTTP1xCodecPair>;
using SPDY3DownstreamSessionTest = HTTPDownstreamTest<SPDY3CodecPair>;
namespace {
class HTTP2DownstreamSessionTest : public HTTPDownstreamTest<HTTP2CodecPair> {
public:
HTTP2DownstreamSessionTest()
: HTTPDownstreamTest<HTTP2CodecPair>() {}
void SetUp() override {
HTTPDownstreamTest<HTTP2CodecPair>::SetUp();
}
void SetupControlStream(HTTPCodec::StreamID cStreamId) {
// enable EX_HEADERS
clientCodec_->getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
clientCodec_->generateSettings(requests_);
// create a control stream
clientCodec_->generateHeader(requests_, cStreamId, getGetRequest("/cc"),
true, nullptr);
}
void TearDown() override {
}
};
}
namespace {
class HTTP2DownstreamSessionEarlyShutdownTest :
public HTTPDownstreamTest<HTTP2CodecPair> {
public:
HTTP2DownstreamSessionEarlyShutdownTest()
: HTTPDownstreamTest<HTTP2CodecPair>({-1, -1, -1}, false) {}
void SetUp() override {
HTTPDownstreamTest<HTTP2CodecPair>::SetUp();
}
void TearDown() override {
}
};
}
TEST_F(HTTP2DownstreamSessionEarlyShutdownTest, EarlyShutdown) {
folly::DelayedDestruction::DestructorGuard g(httpSession_);
// Try shutting down the session and then starting it. This should be properly
// handled by the HTTPSession such that no HTTP/2 frames are sent in the
// wrong order.
StrictMock<MockHTTPCodecCallback> callbacks;
clientCodec_->setCallback(&callbacks);
EXPECT_CALL(callbacks, onFrameHeader(_, _, _, _, _)).Times(2);
EXPECT_CALL(callbacks, onSettings(_)).Times(1);
EXPECT_CALL(callbacks, onGoaway(_, _, _)).Times(1);
expectDetachSession();
httpSession_->notifyPendingShutdown();
httpSession_->startNow();
eventBase_.loop();
parseOutput(*clientCodec_);
}
TEST_F(HTTPDownstreamSessionTest, ImmediateEof) {
// Send EOF without any request data
EXPECT_CALL(mockController_, getRequestHandler(_, _)).Times(0);
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(0));
}
TEST_F(HTTPDownstreamSessionTest, Http10NoHeaders) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/", msg->getURL());
EXPECT_EQ("/", msg->getPath());
EXPECT_EQ("", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(0, msg->getHTTPVersion().second);
});
onEOMTerminateHandlerExpectShutdown(*handler);
auto req = getGetRequest();
req.setHTTPVersion(1, 0);
sendRequest(req);
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, Http10NoHeadersEof) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("http://example.com/foo?bar", msg->getURL());
EXPECT_EQ("/foo", msg->getPath());
EXPECT_EQ("bar", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(0, msg->getHTTPVersion().second);
});
onEOMTerminateHandlerExpectShutdown(*handler);
const char *req = "GET http://example.com/foo?bar HTTP/1.0\r\n\r\n";
requests_.append(req, strlen(req));
flushRequestsAndLoop(true, milliseconds(0));
}
TEST_F(HTTPDownstreamSessionTest, SingleBytes) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(2, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("connection"));
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/somepath.php?param=foo", msg->getURL());
EXPECT_EQ("/somepath.php", msg->getPath());
EXPECT_EQ("param=foo", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
});
onEOMTerminateHandlerExpectShutdown(*handler);
addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n");
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, SingleBytesWithBody) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(3, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("content-length"));
EXPECT_TRUE(hdrs.exists("myheader"));
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/somepath.php?param=foo", msg->getURL());
EXPECT_EQ("/somepath.php", msg->getPath());
EXPECT_EQ("param=foo", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
});
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("1"))
.WillOnce(ExpectString("2"))
.WillOnce(ExpectString("3"))
.WillOnce(ExpectString("4"))
.WillOnce(ExpectString("5"));
onEOMTerminateHandlerExpectShutdown(*handler);
addSingleByteReads("POST /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"MyHeader: FooBar\r\n"
"Content-Length: 5\r\n"
"\r\n"
"12345");
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, SplitBody) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(2, hdrs.size());
});
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("12345"))
.WillOnce(ExpectString("abcde"));
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("POST / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Length: 10\r\n"
"\r\n"
"12345", milliseconds(0));
transport_->addReadEvent("abcde", milliseconds(5));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, PostChunked) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(3, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("content-type"));
EXPECT_TRUE(hdrs.exists("transfer-encoding"));
EXPECT_TRUE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("http://example.com/cgi-bin/foo.aspx?abc&def",
msg->getURL());
EXPECT_EQ("/cgi-bin/foo.aspx", msg->getPath());
EXPECT_EQ("abc&def", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
});
EXPECT_CALL(*handler, onChunkHeader(3));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("bar"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onChunkHeader(0x22));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("0123456789abcdef\nfedcba9876543210\n"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onChunkHeader(3));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("foo"));
EXPECT_CALL(*handler, onChunkComplete());
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("POST http://example.com/cgi-bin/foo.aspx?abc&def "
"HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Type: text/pla", milliseconds(0));
transport_->addReadEvent("in; charset=utf-8\r\n"
"Transfer-encoding: chunked\r\n"
"\r", milliseconds(2));
transport_->addReadEvent("\n"
"3\r\n"
"bar\r\n"
"22\r\n"
"0123456789abcdef\n"
"fedcba9876543210\n"
"\r\n"
"3\r", milliseconds(3));
transport_->addReadEvent("\n"
"foo\r\n"
"0\r\n\r\n", milliseconds(1));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, MultiMessage) {
InSequence enforceOrder;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
EXPECT_CALL(*handler1, onBody(_))
.WillOnce(ExpectString("foo"))
.WillOnce(ExpectString("bar9876"));
handler1->expectEOM([&] { handler1->sendReply(); });
handler1->expectDetachTransaction();
auto handler2 = addSimpleNiceHandler();
handler2->expectHeaders();
EXPECT_CALL(*handler2, onChunkHeader(0xa));
EXPECT_CALL(*handler2, onBody(_))
.WillOnce(ExpectString("some "))
.WillOnce(ExpectString("data\n"));
EXPECT_CALL(*handler2, onChunkComplete());
onEOMTerminateHandlerExpectShutdown(*handler2);
transport_->addReadEvent("POST / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Length: 10\r\n"
"\r\n"
"foo", milliseconds(0));
transport_->addReadEvent("bar9876"
"POST /foo HTTP/1.1\r\n"
"Host: exa", milliseconds(2));
transport_->addReadEvent("mple.com\r\n"
"Connection: close\r\n"
"Trans", milliseconds(0));
transport_->addReadEvent("fer-encoding: chunked\r\n"
"\r\n", milliseconds(2));
transport_->addReadEvent("a\r\nsome ", milliseconds(0));
transport_->addReadEvent("data\n\r\n0\r\n\r\n", milliseconds(2));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, Connect) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
// Send HTTP 200 OK to accept the CONNECT request
handler->expectHeaders([&handler] {
handler->sendHeaders(200, 100);
});
EXPECT_CALL(*handler, onUpgrade(_));
// Data should be received using onBody
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("12345"))
.WillOnce(ExpectString("abcde"));
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("CONNECT test HTTP/1.1\r\n"
"\r\n"
"12345", milliseconds(0));
transport_->addReadEvent("abcde", milliseconds(5));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, ConnectRejected) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
// Send HTTP 400 to reject the CONNECT request
handler->expectHeaders([&handler] {
handler->sendReplyCode(400);
});
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("CONNECT test HTTP/1.1\r\n"
"\r\n"
"12345", milliseconds(0));
transport_->addReadEvent("abcde", milliseconds(5));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, HttpUpgrade) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
// Send HTTP 101 Switching Protocls to accept the upgrade request
handler->expectHeaders([&handler] {
handler->sendHeaders(101, 100);
});
// Send the response in the new protocol after upgrade
EXPECT_CALL(*handler, onUpgrade(_))
.WillOnce(Invoke([&handler](UpgradeProtocol /*protocol*/) {
handler->sendReplyCode(100);
}));
onEOMTerminateHandlerExpectShutdown(*handler);
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_UPGRADE, "TEST/1.0");
req.getHeaders().add(HTTP_HEADER_CONNECTION, "upgrade");
sendRequest(req);
flushRequestsAndLoop(true, milliseconds(0));
}
TEST(HTTPDownstreamTest, ParseErrorNoTxn) {
// 1) Get a parse error on SYN_STREAM for streamID == 1
// 2) Expect that the codec should be asked to generate an abort on
// streamID==1
EventBase evb;
// Setup the controller and its expecations.
NiceMock<MockController> mockController;
// Setup the codec, its callbacks, and its expectations.
auto codec = makeDownstreamParallelCodec();
HTTPCodec::Callback* codecCallback = nullptr;
EXPECT_CALL(*codec, setCallback(_))
.WillRepeatedly(SaveArg<0>(&codecCallback));
// Expect egress abort for streamID == 1
EXPECT_CALL(*codec, generateRstStream(_, 1, _));
// Setup transport
bool transportGood = true;
auto transport = newMockTransport(&evb);
EXPECT_CALL(*transport, good())
.WillRepeatedly(ReturnPointee(&transportGood));
EXPECT_CALL(*transport, closeNow())
.WillRepeatedly(Assign(&transportGood, false));
EXPECT_CALL(*transport, writeChain(_, _, _))
.WillRepeatedly(
Invoke([&] (folly::AsyncTransportWrapper::WriteCallback* callback,
const shared_ptr<IOBuf>&, WriteFlags) {
callback->writeSuccess();
}));
// Create the downstream session, thus initializing codecCallback
auto transactionTimeouts = makeInternalTimeoutSet(&evb);
auto session = new HTTPDownstreamSession(
transactionTimeouts.get(),
AsyncTransportWrapper::UniquePtr(transport),
localAddr, peerAddr,
&mockController, std::move(codec),
mockTransportInfo,
nullptr);
session->startNow();
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, "foo");
ex.setProxygenError(kErrorParseHeader);
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
codecCallback->onError(HTTPCodec::StreamID(1), ex, true);
// cleanup
session->dropConnection();
evb.loop();
}
TEST(HTTPDownstreamTest, ByteEventsDrained) {
// Test that byte events are drained before socket is closed
EventBase evb;
NiceMock<MockController> mockController;
auto codec = makeDownstreamParallelCodec();
auto byteEventTracker = new MockByteEventTracker(nullptr);
auto transport = newMockTransport(&evb);
auto transactionTimeouts = makeInternalTimeoutSet(&evb);
// Create the downstream session
auto session = new HTTPDownstreamSession(
transactionTimeouts.get(),
AsyncTransportWrapper::UniquePtr(transport),
localAddr, peerAddr,
&mockController, std::move(codec),
mockTransportInfo,
nullptr);
session->setByteEventTracker(
std::unique_ptr<ByteEventTracker>(byteEventTracker));
InSequence enforceOrder;
session->startNow();
// Byte events should be drained first
EXPECT_CALL(*byteEventTracker, drainByteEvents())
.Times(1);
EXPECT_CALL(*transport, closeNow())
.Times(AtLeast(1));
// Close the socket
session->dropConnection();
evb.loop();
}
TEST_F(HTTPDownstreamSessionTest, HttpWithAckTiming) {
// This is to test cases where holding a byte event to a finished HTTP/1.1
// transaction does not masquerade as HTTP pipelining.
auto byteEventTracker = setMockByteEventTracker();
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
handler1->sendChunkedReplyWithBody(200, 100, 100, false);
});
// Hold a pending byte event
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _))
.WillOnce(Invoke([] (HTTPTransaction* txn,
uint64_t /*byteNo*/) {
txn->incrementPendingByteEvents();
}));
sendRequest();
flushRequestsAndLoop();
expectResponse();
// Send the secode request after receiving the first response (eg: clearly
// not pipelined)
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
handler2->sendChunkedReplyWithBody(200, 100, 100, false);
});
// This txn processed and destroyed before txn1
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _));
handler2->expectDetachTransaction();
sendRequest();
flushRequestsAndLoop();
expectResponse();
// Now clear the pending byte event (simulate ack) and the first txn
// goes away too
handler1->expectDetachTransaction();
handler1->txn_->decrementPendingByteEvents();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, TestOnContentMismatch) {
// Test the behavior when the reported content-length on the header
// is different from the actual length of the body.
// The expectation is simply to log the behavior, such as:
// ".. HTTPTransaction.cpp ] Content-Length/body mismatch: expected: .. "
folly::EventBase base;
InSequence enforceOrder;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
// over-estimate the content-length on the header
handler1->sendHeaders(200, 105);
handler1->sendBody(100);
handler1->txn_->sendEOM();
});
sendRequest();
flushRequestsAndLoop();
auto handler2 = addSimpleNiceHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
// under-estimate the content-length on the header
handler2->sendHeaders(200, 95);
handler2->sendBody(100);
handler2->txn_->sendEOM();
});
sendRequest();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, HttpWithAckTimingPipeline) {
// Test a real pipelining case as well. First request is done waiting for
// ack, then receive two pipelined requests.
auto byteEventTracker = setMockByteEventTracker();
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
handler1->sendChunkedReplyWithBody(200, 100, 100, false);
});
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _))
.WillOnce(Invoke([] (HTTPTransaction* txn,
uint64_t /*byteNo*/) {
txn->incrementPendingByteEvents();
}));
sendRequest();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
handler2->sendChunkedReplyWithBody(200, 100, 100, false);
});
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _));
handler2->expectDetachTransaction();
sendRequest();
sendRequest();
auto handler3 = addSimpleStrictHandler();
handler3->expectHeaders();
handler3->expectEOM([&handler3] () {
handler3->sendChunkedReplyWithBody(200, 100, 100, false);
});
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _));
handler3->expectDetachTransaction();
flushRequestsAndLoop();
expectResponses(3);
handler1->expectDetachTransaction();
handler1->txn_->decrementPendingByteEvents();
gracefulShutdown();
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] regular request 1st stream (getGetRequest())
* - [server --> client] respond 1st stream (res, 100 bytes, without EOM)
* - [server --> client] request 2nd stream (pub, 200 bytes, EOM)
* - [client --> server] respond 2nd stream (OK, EOM)
* - [client --> server] EOM on the 1st stream
*/
TEST_F(HTTP2DownstreamSessionTest, ExheaderFromServer) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// Create a dummy request and a dummy response messages
auto pub = getGetRequest("/sub/fyi");
// set up the priority for fun
pub.setHTTP2Priority(std::make_tuple(0, false, 7));
InSequence handlerSequence;
auto cHandler = addSimpleStrictHandler();
StrictMock<MockHTTPHandler> pubHandler;
cHandler->expectHeaders([&] {
cHandler->txn_->pauseIngress();
// Generate response for the control stream
cHandler->txn_->sendHeaders(getResponse(200, 0));
cHandler->txn_->sendBody(makeBuf(100));
auto* pubTxn = cHandler->txn_->newExTransaction(&pubHandler);
// Generate a pub request (encapsulated in EX_HEADERS frame)
pubTxn->sendHeaders(pub);
pubTxn->sendBody(makeBuf(200));
pubTxn->sendEOM();
});
EXPECT_CALL(pubHandler, setTransaction(_));
EXPECT_CALL(callbacks_, onSettings(_))
.WillOnce(InvokeWithoutArgs([&] {
clientCodec_->generateSettingsAck(requests_);
}));
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onExMessageBegin(2, _, _, _));
EXPECT_CALL(callbacks_, onHeadersComplete(2, _));
EXPECT_CALL(callbacks_, onMessageComplete(2, _));
EXPECT_CALL(pubHandler, onHeadersComplete(_));
EXPECT_CALL(pubHandler, onEOM());
EXPECT_CALL(pubHandler, detachTransaction());
EXPECT_CALL(*cHandler, onEOM());
EXPECT_CALL(*cHandler, detachTransaction());
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
eventBase_.runAfterDelay([&] {
parseOutput(*clientCodec_);
// send a response from client to server
clientCodec_->generateExHeader(requests_, 2, getResponse(200, 0),
HTTPCodec::ExAttributes(cStreamId, false),
true, nullptr);
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
parseOutput(*clientCodec_);
cHandler->txn_->resumeIngress();
cHandler->txn_->sendEOM();
transport_->addReadEOF(milliseconds(0));
}, 100);
HTTPSession::DestructorGuard g(httpSession_);
expectDetachSession();
eventBase_.loop();
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] regular request on control stream 1
* - [client --> server] Pub request on stream 3
* - [server --> client] response on stream 1 (OK, )
* - [server --> client] response on stream 3 (OK, EOM)
* - [server --> client] response on stream 1 (EOM)
*/
TEST_F(HTTP2DownstreamSessionTest, ExheaderFromClient) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// generate an EX_HEADERS
auto exStreamId = cStreamId + 2;
clientCodec_->generateExHeader(requests_, exStreamId, getGetRequest("/pub"),
HTTPCodec::ExAttributes(cStreamId, false),
true, nullptr);
auto cHandler = addSimpleStrictHandler();
cHandler->expectHeaders([&] {
// send back the response for control stream, but EOM
cHandler->txn_->sendHeaders(getResponse(200, 0));
});
EXPECT_CALL(*cHandler, onEOM());
StrictMock<MockHTTPHandler> pubHandler;
EXPECT_CALL(*cHandler, onExTransaction(_))
.WillOnce(Invoke([&pubHandler] (HTTPTransaction* exTxn) {
exTxn->setHandler(&pubHandler);
pubHandler.txn_ = exTxn;
}));
InSequence handlerSequence;
EXPECT_CALL(pubHandler, setTransaction(_));
pubHandler.expectHeaders([&] {
// send back the response for the pub request
pubHandler.txn_->sendHeadersWithEOM(getResponse(200, 0));
});
EXPECT_CALL(pubHandler, onEOM());
EXPECT_CALL(pubHandler, detachTransaction());
cHandler->expectDetachTransaction();
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onExMessageBegin(exStreamId, _, _, _));
EXPECT_CALL(callbacks_, onHeadersComplete(exStreamId, _));
EXPECT_CALL(callbacks_, onMessageComplete(exStreamId, _));
EXPECT_CALL(callbacks_, onMessageComplete(cStreamId, _));
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
transport_->addReadEOF(milliseconds(0));
eventBase_.loop();
HTTPSession::DestructorGuard g(httpSession_);
expectDetachSession();
cHandler->txn_->sendEOM();
eventBase_.loop();
parseOutput(*clientCodec_);
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] regular request 1st stream (getGetRequest())
* - [server --> client] request 2nd stream (unidirectional)
* - [server --> client] response + EOM on the 1st stream
*/
TEST_F(HTTP2DownstreamSessionTest, UnidirectionalExTransaction) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
InSequence handlerSequence;
auto cHandler = addSimpleStrictHandler();
StrictMock<MockHTTPHandler> uniHandler;
cHandler->expectHeaders([&] {
auto* uniTxn = cHandler->txn_->newExTransaction(&uniHandler, true);
EXPECT_TRUE(uniTxn->isIngressComplete());
uniTxn->sendHeaders(getGetRequest("/uni"));
uniTxn->sendEOM();
// close control stream
cHandler->txn_->sendHeadersWithEOM(getResponse(200, 0));
});
EXPECT_CALL(uniHandler, setTransaction(_));
EXPECT_CALL(*cHandler, onEOM());
EXPECT_CALL(uniHandler, detachTransaction());
EXPECT_CALL(*cHandler, detachTransaction());
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
eventBase_.runAfterDelay([&] {
transport_->addReadEOF(milliseconds(0));
}, 100);
HTTPSession::DestructorGuard g(httpSession_);
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, PauseResumeControlStream) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// generate an EX_HEADERS
clientCodec_->generateExHeader(requests_, cStreamId + 2, getGetRequest(),
HTTPCodec::ExAttributes(cStreamId, false),
true, nullptr);
auto cHandler = addSimpleStrictHandler();
cHandler->expectHeaders([&] {
cHandler->txn_->pauseIngress();
// send back the response for control stream, but EOM
cHandler->txn_->sendHeaders(getResponse(200, 0));
});
EXPECT_CALL(*cHandler, onEOM());
StrictMock<MockHTTPHandler> pubHandler;
EXPECT_CALL(*cHandler, onExTransaction(_))
.WillOnce(Invoke([&pubHandler] (HTTPTransaction* exTxn) {
exTxn->setHandler(&pubHandler);
pubHandler.txn_ = exTxn;
}));
InSequence handlerSequence;
EXPECT_CALL(pubHandler, setTransaction(_));
pubHandler.expectHeaders([&] {
// send back the response for the pub request
pubHandler.txn_->sendHeadersWithEOM(getResponse(200, 0));
});
EXPECT_CALL(pubHandler, onEOM());
EXPECT_CALL(pubHandler, detachTransaction());
cHandler->expectDetachTransaction();
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId + 2, _));
EXPECT_CALL(callbacks_, onMessageComplete(cStreamId + 2, _));
EXPECT_CALL(callbacks_, onMessageComplete(cStreamId, _));
HTTPSession::DestructorGuard g(httpSession_);
transport_->addReadEvent(requests_, milliseconds(0));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
cHandler->txn_->resumeIngress();
cHandler->txn_->sendEOM();
eventBase_.loop();
expectDetachSession();
parseOutput(*clientCodec_);
}
TEST_F(HTTP2DownstreamSessionTest, InvalidControlStream) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// generate an EX_HEADERS, but with a non-existing control stream
clientCodec_->generateExHeader(requests_, cStreamId + 2, getGetRequest(),
HTTPCodec::ExAttributes(cStreamId + 4, false),
true, nullptr);
auto cHandler = addSimpleStrictHandler();
InSequence handlerSequence;
cHandler->expectHeaders([&] {
// send back the response for control stream, but EOM
cHandler->txn_->sendHeaders(getResponse(200, 0));
});
EXPECT_CALL(*cHandler, onExTransaction(_)).Times(0);
EXPECT_CALL(*cHandler, onEOM());
cHandler->expectDetachTransaction();
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onAbort(cStreamId + 2, _));
HTTPSession::DestructorGuard g(httpSession_);
transport_->addReadEvent(requests_, milliseconds(0));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
cHandler->txn_->sendEOM();
eventBase_.loop();
expectDetachSession();
parseOutput(*clientCodec_);
}
TEST_F(HTTP2DownstreamSessionTest, SetByteEventTracker) {
InSequence enforceOrder;
// Send two requests with writes paused, which will queue several byte events,
// including last byte events which are holding a reference to the
// transaction.
transport_->pauseWrites();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
handler1->sendReplyWithBody(200, 100);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
handler2->sendReplyWithBody(200, 100);
});
sendRequest();
sendRequest();
// Resume writes from the loop callback
eventBase_.runInLoop([this] {
transport_->resumeWrites();
});
// Graceful shutdown will notify of GOAWAY
EXPECT_CALL(*handler1, onGoaway(ErrorCode::NO_ERROR));
EXPECT_CALL(*handler2, onGoaway(ErrorCode::NO_ERROR));
// The original byteEventTracker will process the last byte event of the
// first transaction, and detach by deleting the event. Swap out the tracker.
handler1->expectDetachTransaction([this] {
auto tracker = std::make_unique<ByteEventTracker>(httpSession_);
httpSession_->setByteEventTracker(std::move(tracker));
});
// handler2 should also be detached immediately because the new
// ByteEventTracker continues procesing where the old one left off.
handler2->expectDetachTransaction();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, TestTrackedByteEventTracker) {
auto byteEventTracker = setMockByteEventTracker();
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
size_t bytesToSend = 200;
size_t expectedTrackedByteOffset = bytesToSend + 99;
handler1->expectHeaders();
handler1->expectEOM([&handler1, &bytesToSend] () {
handler1->sendHeaders(200, 200);
handler1->sendBodyWithLastByteTracking(bytesToSend);
handler1->txn_->sendEOM();
});
EXPECT_CALL(*byteEventTracker,
addTrackedByteEvent(_, expectedTrackedByteOffset))
.WillOnce(Invoke([] (HTTPTransaction* txn,
uint64_t /*byteNo*/) {
txn->incrementPendingByteEvents();
}));
sendRequest();
flushRequestsAndLoop();
handler1->expectDetachTransaction();
handler1->txn_->decrementPendingByteEvents();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, Trailers) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&handler]() {
handler->sendReplyWithBody(
200, 100, true /* keepalive */, true /* sendEOM */, true /*trailers*/);
});
handler->expectDetachTransaction();
HTTPSession::DestructorGuard g(httpSession_);
sendRequest();
flushRequestsAndLoop(true, milliseconds(0));
EXPECT_CALL(callbacks_, onMessageBegin(1, _)).Times(1);
EXPECT_CALL(callbacks_, onHeadersComplete(1, _)).Times(1);
EXPECT_CALL(callbacks_, onBody(1, _, _));
EXPECT_CALL(callbacks_, onTrailersComplete(1, _));
EXPECT_CALL(callbacks_, onMessageComplete(1, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTPDownstreamSessionTest, Trailers) {
testChunks(true);
}
TEST_F(HTTPDownstreamSessionTest, ExplicitChunks) {
testChunks(false);
}
template <class C>
void HTTPDownstreamTest<C>::testChunks(bool trailers) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&handler, trailers] () {
handler->sendChunkedReplyWithBody(200, 100, 17, trailers);
});
handler->expectDetachTransaction();
HTTPSession::DestructorGuard g(httpSession_);
sendRequest();
flushRequestsAndLoop(true, milliseconds(0));
EXPECT_CALL(callbacks_, onMessageBegin(1, _))
.Times(1);
EXPECT_CALL(callbacks_, onHeadersComplete(1, _))
.Times(1);
for (int i = 0; i < 6; i++) {
EXPECT_CALL(callbacks_, onChunkHeader(1, _));
EXPECT_CALL(callbacks_, onBody(1, _, _));
EXPECT_CALL(callbacks_, onChunkComplete(1));
}
if (trailers) {
EXPECT_CALL(callbacks_, onTrailersComplete(1, _));
}
EXPECT_CALL(callbacks_, onMessageComplete(1, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTPDownstreamSessionTest, HttpDrain) {
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders([this, &handler1] {
handler1->sendHeaders(200, 100);
httpSession_->notifyPendingShutdown();
});
handler1->expectEOM([&handler1] {
handler1->sendBody(100);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders([&handler2] {
handler2->sendHeaders(200, 100);
});
handler2->expectEOM([&handler2] {
handler2->sendBody(100);
handler2->txn_->sendEOM();
});
handler2->expectDetachTransaction();
expectDetachSession();
sendRequest();
sendRequest();
flushRequestsAndLoop();
}
// 1) receive full request
// 2) notify pending shutdown
// 3) wait for session read timeout -> should be ignored
// 4) response completed
TEST_F(HTTPDownstreamSessionTest, HttpDrainLongRunning) {
InSequence enforceSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders([this, &handler] {
httpSession_->notifyPendingShutdown();
eventBase_.tryRunAfterDelay([this] {
// simulate read timeout
httpSession_->timeoutExpired();
}, 100);
eventBase_.tryRunAfterDelay([&handler] {
handler->sendReplyWithBody(200, 100);
}, 200);
});
handler->expectEOM();
handler->expectDetachTransaction();
expectDetachSession();
sendRequest();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, EarlyAbort) {
StrictMock<MockHTTPHandler> handler;
InSequence enforceOrder;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
handler.txn_ = txn;
handler.txn_->sendAbort();
}));
handler.expectDetachTransaction();
expectDetachSession();
addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n");
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(SPDY3DownstreamSessionTest, HttpPausedBuffered) {
IOBufQueue rst{IOBufQueue::cacheChainLength()};
auto s = sendRequest();
clientCodec_->generateRstStream(rst, s, ErrorCode::CANCEL);
sendRequest();
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
transport_->pauseWrites();
handler1->sendHeaders(200, 65536 * 2);
handler1->sendBody(65536 * 2);
});
handler1->expectEgressPaused();
auto handler2 = addSimpleNiceHandler();
handler2->expectEgressPaused();
handler2->expectHeaders();
handler2->expectEOM([&] {
eventBase_.runInLoop([&] {
transport_->addReadEvent(rst, milliseconds(0)); });
});
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorStreamAbort);
resumeWritesInLoop();
});
handler1->expectDetachTransaction();
handler2->expectEgressResumed([&] {
handler2->sendReplyWithBody(200, 32768);
});
handler2->expectDetachTransaction([this] {
eventBase_.runInLoop([&] { transport_->addReadEOF(milliseconds(0)); });
});
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, HttpWritesDrainingTimeout) {
sendRequest();
sendHeader();
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
transport_->pauseWrites();
handler1->sendHeaders(200, 1000);
});
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("WriteTimeout on transaction id: ",
handler1->txn_->getID()),
std::string(ex.what()));
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, HttpRateLimitNormal) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
// Create a request
sendRequest();
InSequence handlerSequence;
// Set a low rate-limit on the transaction
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders([&] {
uint32_t rateLimit_kbps = 640;
handler1->txn_->setEgressRateLimit(rateLimit_kbps * 1024);
});
// Send a somewhat big response that we know will get rate-limited
handler1->expectEOM([&handler1] {
// At 640kbps, this should take slightly over 800ms
uint32_t rspLengthBytes = 100000;
handler1->sendHeaders(200, rspLengthBytes);
handler1->sendBody(rspLengthBytes);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
proxygen::TimePoint timeFirstWrite =
transport_->getWriteEvents()->front()->getTime();
proxygen::TimePoint timeLastWrite =
transport_->getWriteEvents()->back()->getTime();
int64_t writeDuration =
(int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count();
EXPECT_GE(writeDuration, 800);
cleanup();
}
TEST_F(SPDY3DownstreamSessionTest, SpdyRateLimitNormal) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
100000);
clientCodec_->generateSettings(requests_);
sendRequest();
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders([&] {
uint32_t rateLimit_kbps = 640;
handler1->txn_->setEgressRateLimit(rateLimit_kbps * 1024);
});
handler1->expectEOM([&handler1] {
// At 640kbps, this should take slightly over 800ms
uint32_t rspLengthBytes = 100000;
handler1->sendHeaders(200, rspLengthBytes);
handler1->sendBody(rspLengthBytes);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop(true, milliseconds(50));
proxygen::TimePoint timeFirstWrite =
transport_->getWriteEvents()->front()->getTime();
proxygen::TimePoint timeLastWrite =
transport_->getWriteEvents()->back()->getTime();
int64_t writeDuration =
(int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count();
EXPECT_GE(writeDuration, 800);
expectDetachSession();
}
/**
* This test will reset the connection while the server is waiting around
* to send more bytes (so as to keep under the rate limit).
*/
TEST_F(SPDY3DownstreamSessionTest, SpdyRateLimitRst) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
IOBufQueue rst{IOBufQueue::cacheChainLength()};
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
100000);
clientCodec_->generateSettings(requests_);
auto streamID = sendRequest();
clientCodec_->generateRstStream(rst, streamID, ErrorCode::CANCEL);
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders([&] {
uint32_t rateLimit_kbps = 640;
handler1->txn_->setEgressRateLimit(rateLimit_kbps * 1024);
});
handler1->expectEOM([&handler1] {
uint32_t rspLengthBytes = 100000;
handler1->sendHeaders(200, rspLengthBytes);
handler1->sendBody(rspLengthBytes);
handler1->txn_->sendEOM();
});
handler1->expectError();
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(50), milliseconds(0), [&] {
transport_->addReadEvent(rst, milliseconds(10));
});
}
// Send a 1.0 request, egress the EOM with the last body chunk on a paused
// socket, and let it timeout. dropConnection()
// to removeTransaction with writesDraining_=true
TEST_F(HTTPDownstreamSessionTest, WriteTimeout) {
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
sendRequest(req);
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
handler1->sendHeaders(200, 100);
eventBase_.tryRunAfterDelay([&handler1, this] {
transport_->pauseWrites();
handler1->sendBody(100);
handler1->txn_->sendEOM();
}, 50);
});
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(folly::to<std::string>("WriteTimeout on transaction id: ",
handler1->txn_->getID()),
std::string(ex.what()));
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
// Send an abort from the write timeout path while pipelining
TEST_F(HTTPDownstreamSessionTest, WriteTimeoutPipeline) {
const char* buf = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"
"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
requests_.append(buf, strlen(buf));
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
handler1->sendHeaders(200, 100);
eventBase_.tryRunAfterDelay([&handler1, this] {
transport_->pauseWrites();
handler1->sendBody(100);
handler1->txn_->sendEOM();
}, 50);
});
auto handler2 = addSimpleNiceHandler();
handler2->expectHeaders();
handler2->expectEOM();
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(folly::to<std::string>("WriteTimeout on transaction id: ",
handler1->txn_->getID()),
std::string(ex.what()));
handler1->txn_->sendAbort();
});
handler2->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(folly::to<std::string>("WriteTimeout on transaction id: ",
handler2->txn_->getID()),
std::string(ex.what()));
handler2->txn_->sendAbort();
});
handler2->expectDetachTransaction();
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, BodyPacketization) {
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
req.setWantsKeepalive(false);
sendRequest(req);
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 32768);
});
handler1->expectDetachTransaction();
expectDetachSession();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
EXPECT_EQ(transport_->getWriteEvents()->size(), 1);
}
TEST_F(HTTPDownstreamSessionTest, HttpMalformedPkt1) {
// Create a HTTP connection and keep sending just '\n' to the HTTP1xCodec.
std::string data(90000, '\n');
requests_.append(data.data(), data.length());
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(0));
}
TEST_F(HTTPDownstreamSessionTest, BigExplcitChunkWrite) {
// even when the handler does a massive write, the transport only gets small
// writes
sendRequest();
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(200, 100, false);
size_t len = 16 * 1024 * 1024;
handler->txn_->sendChunkHeader(len);
auto chunk = makeBuf(len);
handler->txn_->sendBody(std::move(chunk));
handler->txn_->sendChunkTerminator();
handler->txn_->sendEOM();
});
handler->expectDetachTransaction();
expectDetachSession();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
EXPECT_GT(transport_->getWriteEvents()->size(), 250);
}
// ==== upgrade tests ====
// Test upgrade to a protocol unknown to HTTPSession
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNonNative) {
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(101, 0, true, {{"Upgrade", "blarf"}});
});
EXPECT_CALL(*handler, onUpgrade(UpgradeProtocol::TCP));
handler->expectEOM([&handler] {
handler->txn_->sendEOM();
});
handler->expectDetachTransaction();
sendRequest(getUpgradeRequest("blarf"));
expectDetachSession();
flushRequestsAndLoop(true);
}
// Test upgrade to a protocol unknown to HTTPSession, but don't switch
// protocols
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNonNativeIgnore) {
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectEOM();
handler->expectDetachTransaction();
sendRequest(getUpgradeRequest("blarf"));
expectDetachSession();
flushRequestsAndLoop(true);
}
// Test upgrade to a protocol unknown to HTTPSession
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNonNativePipeline) {
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders([&handler1] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_EQ(msg->getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE),
"blarf");
handler1->sendReplyWithBody(200, 100);
});
handler1->expectEOM();
handler1->expectDetachTransaction();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders([&handler2] {
handler2->sendReplyWithBody(200, 100);
});
handler2->expectEOM();
handler2->expectDetachTransaction();
sendRequest(getUpgradeRequest("blarf"));
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"\r\n");
expectDetachSession();
flushRequestsAndLoop(true);
}
// Helper that does a simple upgrade test - request an upgrade, receive a 101
// and an upgraded response
template <class C>
void HTTPDownstreamTest<C>::testSimpleUpgrade(
const std::string& upgradeHeader,
CodecProtocol expectedProtocol,
const std::string& expectedUpgradeHeader) {
this->rawCodec_->setAllowedUpgradeProtocols({expectedUpgradeHeader});
auto handler = addSimpleStrictHandler();
HeaderIndexingStrategy testH2IndexingStrat;
handler->expectHeaders();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM(
[&handler, expectedProtocol, expectedUpgradeHeader, &testH2IndexingStrat] {
EXPECT_FALSE(handler->txn_->getSetupTransportInfo().secure);
EXPECT_EQ(*handler->txn_->getSetupTransportInfo().appProtocol,
expectedUpgradeHeader);
if (expectedProtocol == CodecProtocol::HTTP_2) {
const HTTP2Codec* codec = dynamic_cast<const HTTP2Codec*>(
&handler->txn_->getTransport().getCodec());
ASSERT_NE(codec, nullptr);
EXPECT_EQ(codec->getHeaderIndexingStrategy(), &testH2IndexingStrat);
}
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
if (expectedProtocol == CodecProtocol::HTTP_2) {
EXPECT_CALL(mockController_, getHeaderIndexingStrategy())
.WillOnce(
Return(&testH2IndexingStrat)
);
}
HTTPMessage req = getUpgradeRequest(upgradeHeader);
if (upgradeHeader == http2::kProtocolCleartextString) {
HTTP2Codec::requestUpgrade(req);
}
sendRequest(req);
flushRequestsAndLoop();
expect101(expectedProtocol, expectedUpgradeHeader);
expectResponse();
gracefulShutdown();
}
// Upgrade to SPDY/3
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNative3) {
testSimpleUpgrade("spdy/3", CodecProtocol::SPDY_3, "spdy/3");
}
// Upgrade to SPDY/3.1
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNative31) {
testSimpleUpgrade("spdy/3.1", CodecProtocol::SPDY_3_1, "spdy/3.1");
}
// Upgrade to HTTP/2
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeH2) {
testSimpleUpgrade("h2c", CodecProtocol::HTTP_2, "h2c");
}
class HTTPDownstreamSessionUpgradeFlowControlTest :
public HTTPDownstreamSessionTest {
public:
HTTPDownstreamSessionUpgradeFlowControlTest()
: HTTPDownstreamSessionTest({100000, 105000, 110000}) {}
};
// Upgrade to HTTP/2, with non-default flow control settings
TEST_F(HTTPDownstreamSessionUpgradeFlowControlTest, UpgradeH2Flowcontrol) {
testSimpleUpgrade("h2c", CodecProtocol::HTTP_2, "h2c");
}
// Upgrade to SPDY/3.1 with a non-native proto in the list
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeUnknown) {
// This is maybe weird, the client asked for non-native as first choice,
// but we go native
testSimpleUpgrade("blarf, spdy/3.1, spdy/3",
CodecProtocol::SPDY_3_1, "spdy/3.1");
}
// Upgrade header with extra whitespace
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeWhitespace) {
testSimpleUpgrade(" \tspdy/3.1\t , spdy/3",
CodecProtocol::SPDY_3_1, "spdy/3.1");
}
// Upgrade header with random junk
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeJunk) {
testSimpleUpgrade(",,,, ,,\t~^%$(*&@(@$^^*(,spdy/3",
CodecProtocol::SPDY_3, "spdy/3");
}
// Attempt to upgrade on second txn
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeTxn2) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 100);
});
handler1->expectDetachTransaction();
sendRequest(getGetRequest());
flushRequestsAndLoop();
expectResponse();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] {
handler2->sendReplyWithBody(200, 100);
});
handler2->expectDetachTransaction();
sendRequest(getUpgradeRequest("spdy/3"));
flushRequestsAndLoop();
expectResponse();
gracefulShutdown();
}
// Upgrade on POST
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePost) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
// cheat and not sending EOM, it's a no-op
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3");
expectResponse();
gracefulShutdown();
}
// Upgrade on POST with a reply that comes before EOM, don't switch protocols
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePostEarlyResp) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectBody();
handler->expectEOM();
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expectResponse();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePostEarlyPartialResp) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(200, 100);
});
handler->expectBody();
handler->expectEOM([&handler] {
handler->sendBody(100);
handler->txn_->sendEOM();
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expectResponse();
gracefulShutdown();
}
// Upgrade but with a pipelined HTTP request. It is parsed as SPDY and
// rejected
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeExtra) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
sendRequest(getUpgradeRequest("spdy/3"));
// It's a fatal to send this out on the HTTP1xCodec, so hack it manually
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"Upgrade: spdy/3\r\n"
"\r\n");
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3");
expectResponse(200, ErrorCode::_SPDY_INVALID_STREAM);
gracefulShutdown();
}
// Upgrade on POST with Expect: 100-Continue. If the 100 goes out
// before the EOM is parsed, the 100 will be in HTTP. This should be the normal
// case since the client *should* wait a bit for the 100 continue to come back
// before sending the POST. But if the 101 is delayed beyond EOM, the 101
// will come via SPDY.
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePost100) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(100, 0);
});
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
req.getHeaders().add(HTTP_HEADER_EXPECT, "100-continue");
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3", true /* expect 100 continue */);
expectResponse();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePost100Late) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendHeaders(100, 0);
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
req.getHeaders().add(HTTP_HEADER_EXPECT, "100-continue");
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3");
expectResponse(200, ErrorCode::NO_ERROR, true /* expect 100 via SPDY */);
gracefulShutdown();
}
TEST_F(SPDY3DownstreamSessionTest, SpdyPrio) {
testPriorities(8);
cleanup();
}
// Test sending a GOAWAY while the downstream session is still processing
// the request that was an upgrade. The reply GOAWAY should have last good
// stream = 1, not 0.
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeGoawayDrain) {
this->rawCodec_->setAllowedUpgradeProtocols({"h2c"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM();
handler->expectGoaway();
handler->expectDetachTransaction();
EXPECT_CALL(mockController_, getHeaderIndexingStrategy())
.WillOnce(
Return(&testH2IndexingStrat_)
);
HTTPMessage req = getUpgradeRequest("h2c", HTTPMethod::POST, 10);
HTTP2Codec::requestUpgrade(req);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
// cheat and not sending EOM, it's a no-op
flushRequestsAndLoop();
expect101(CodecProtocol::HTTP_2, "h2c");
clientCodec_->generateConnectionPreface(requests_);
clientCodec_->generateGoaway(requests_, 0, ErrorCode::NO_ERROR);
flushRequestsAndLoop();
eventBase_.runInLoop([&handler] {
handler->sendReplyWithBody(200, 100);
});
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
expectResponse(200, ErrorCode::NO_ERROR, false, true);
expectDetachSession();
}
template <class C>
void HTTPDownstreamTest<C>::testPriorities(uint32_t numPriorities) {
uint32_t iterations = 10;
uint32_t maxPriority = numPriorities - 1;
std::vector<std::unique_ptr<testing::NiceMock<MockHTTPHandler>>> handlers;
for (int pri = numPriorities - 1; pri >= 0; pri--) {
for (uint32_t i = 0; i < iterations; i++) {
sendRequest("/", pri * (8 / numPriorities));
InSequence handlerSequence;
auto handler = addSimpleNiceHandler();
auto rawHandler = handler.get();
handlers.push_back(std::move(handler));
rawHandler->expectHeaders();
rawHandler->expectEOM([rawHandler] {
rawHandler->sendReplyWithBody(200, 1000);
});
rawHandler->expectDetachTransaction([] { });
}
}
auto buf = requests_.move();
buf->coalesce();
requests_.append(std::move(buf));
flushRequestsAndLoop();
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks_, onMessageBegin(_, _))
.Times(iterations * numPriorities);
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.Times(iterations * numPriorities);
// body is variable and hence ignored
EXPECT_CALL(callbacks_, onMessageComplete(_, _))
.Times(iterations * numPriorities)
.WillRepeatedly(Invoke([&](HTTPCodec::StreamID stream, bool /*upgrade*/) {
streams.push_back(stream);
}));
parseOutput(*clientCodec_);
// transactions finish in priority order (higher streamIDs first)
EXPECT_EQ(streams.size(), iterations * numPriorities);
auto txn = streams.begin();
for (int band = maxPriority; band >= 0; band--) {
auto upperID = iterations * 2 * (band + 1);
auto lowerID = iterations * 2 * band;
for (uint32_t i = 0; i < iterations; i++) {
EXPECT_LE(lowerID, (uint32_t)*txn);
EXPECT_GE(upperID, (uint32_t)*txn);
++txn;
}
}
}
// Verifies that the read timeout is not running when no ingress is expected/
// required to proceed
TEST_F(SPDY3DownstreamSessionTest, SpdyTimeout) {
sendRequest();
sendRequest();
httpSession_->setWriteBufferLimit(512);
InSequence handlerSequence;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders([this] { transport_->pauseWrites(); });
handler1->expectEOM([&] {
handler1->sendHeaders(200, 1000);
handler1->sendBody(1000);
});
handler1->expectEgressPaused();
auto handler2 = addSimpleStrictHandler();
// handler2 is paused before it gets headers
handler2->expectEgressPaused();
handler2->expectHeaders();
handler2->expectEOM([this] {
// This transaction should start egress paused. We've received the
// EOM, so the timeout shouldn't be running delay 400ms and resume
// writes, this keeps txn1 from getting a write timeout
resumeWritesAfterDelay(milliseconds(400));
});
handler1->expectEgressResumed([&handler1] { handler1->txn_->sendEOM(); });
handler2->expectEgressResumed([&handler2, this] {
// delay an additional 200ms. The total 600ms delay shouldn't fire
// onTimeout
eventBase_.tryRunAfterDelay([&handler2] {
handler2->sendReplyWithBody(200, 400); }, 200
);
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoop(false, milliseconds(0), milliseconds(10));
cleanup();
}
// Verifies that the read timer is running while a transaction is blocked
// on a window update
TEST_F(SPDY3DownstreamSessionTest, SpdyTimeoutWin) {
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec_->generateSettings(requests_);
auto streamID = sendRequest();
InSequence handlerSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&] {
handler->sendReplyWithBody(200, 1000);
});
handler->expectEgressPaused();
handler->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("ingress timeout, streamID=", streamID),
std::string(ex.what()));
handler->terminate();
});
handler->expectDetachTransaction();
flushRequestsAndLoop();
cleanup();
}
TYPED_TEST_CASE_P(HTTPDownstreamTest);
TYPED_TEST_P(HTTPDownstreamTest, TestWritesDraining) {
auto badCodec =
makeServerCodec<typename TypeParam::Codec>(TypeParam::version);
this->sendRequest();
badCodec->generatePushPromise(this->requests_, 2 /* bad */, getGetRequest(),
1);
this->expectDetachSession();
InSequence handlerSequence;
auto handler1 = this->addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM();
handler1->expectError([&](const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorEOF);
ASSERT_TRUE(
folly::StringPiece(ex.what()).startsWith("Shutdown transport: EOF"))
<< ex.what();
});
handler1->expectDetachTransaction();
this->flushRequestsAndLoop();
}
TYPED_TEST_P(HTTPDownstreamTest, TestBodySizeLimit) {
this->clientCodec_->generateWindowUpdate(this->requests_, 0, 65536);
this->sendRequest();
this->sendRequest();
InSequence handlerSequence;
auto handler1 = this->addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM();
auto handler2 = this->addSimpleNiceHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler1->sendReplyWithBody(200, 33000);
handler2->sendReplyWithBody(200, 33000);
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
this->flushRequestsAndLoop();
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(this->callbacks_, onMessageBegin(1, _));
EXPECT_CALL(this->callbacks_, onHeadersComplete(1, _));
EXPECT_CALL(this->callbacks_, onMessageBegin(3, _));
EXPECT_CALL(this->callbacks_, onHeadersComplete(3, _));
for (uint32_t i = 0; i < 8; i++) {
EXPECT_CALL(this->callbacks_, onBody(1, _, _));
EXPECT_CALL(this->callbacks_, onBody(3, _, _));
}
EXPECT_CALL(this->callbacks_, onBody(1, _, _));
EXPECT_CALL(this->callbacks_, onMessageComplete(1, _));
EXPECT_CALL(this->callbacks_, onBody(3, _, _));
EXPECT_CALL(this->callbacks_, onMessageComplete(3, _));
this->parseOutput(*this->clientCodec_);
this->cleanup();
}
#define IF_HTTP2(X) \
if (this->clientCodec_->getProtocol() == CodecProtocol::HTTP_2) { X; }
TYPED_TEST_P(HTTPDownstreamTest, TestUniformPauseState) {
this->httpSession_->setWriteBufferLimit(12000);
this->clientCodec_->getEgressSettings()->setSetting(
SettingsId::INITIAL_WINDOW_SIZE, 1000000);
this->clientCodec_->generateSettings(this->requests_);
this->clientCodec_->generateWindowUpdate(this->requests_, 0, 1000000);
this->sendRequest("/", 1);
this->sendRequest("/", 1);
this->sendRequest("/", 2);
InSequence handlerSequence;
auto handler1 = this->addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM();
auto handler2 = this->addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler1->sendHeaders(200, 24002);
// triggers pause of all txns
this->transport_->pauseWrites();
handler1->txn_->sendBody(std::move(makeBuf(12001)));
this->resumeWritesAfterDelay(milliseconds(50));
});
handler1->expectEgressPaused();
handler2->expectEgressPaused();
auto handler3 = this->addSimpleStrictHandler();
handler3->expectEgressPaused();
handler3->expectHeaders();
handler3->expectEOM();
handler1->expectEgressResumed([&] {
// resume does not trigger another pause,
handler1->txn_->sendBody(std::move(makeBuf(12001)));
});
// handler2 gets a fair shot, handler3 is not resumed
// HTTP/2 priority is not implemented, so handler3 is like another 0 pri txn
handler2->expectEgressResumed();
IF_HTTP2(handler3->expectEgressResumed());
handler1->expectEgressPaused();
handler2->expectEgressPaused();
IF_HTTP2(handler3->expectEgressPaused());
handler1->expectEgressResumed();
handler2->expectEgressResumed([&] {
handler2->sendHeaders(200, 12001);
handler2->txn_->sendBody(std::move(makeBuf(12001)));
this->transport_->pauseWrites();
this->resumeWritesAfterDelay(milliseconds(50));
});
// handler3 not resumed
IF_HTTP2(handler3->expectEgressResumed());
handler1->expectEgressPaused();
handler2->expectEgressPaused();
IF_HTTP2(handler3->expectEgressPaused());
handler1->expectEgressResumed();
handler2->expectEgressResumed([&] {
handler1->txn_->sendEOM();
handler2->txn_->sendEOM();
});
handler3->expectEgressResumed([&] {
handler3->txn_->sendAbort();
});
handler3->expectDetachTransaction();
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
this->flushRequestsAndLoop();
this->cleanup();
}
// Test exceeding the MAX_CONCURRENT_STREAMS setting. The txn should get
// REFUSED_STREAM, and other streams can complete normally
TYPED_TEST_P(HTTPDownstreamTest, TestMaxTxns) {
auto settings = this->rawCodec_->getEgressSettings();
auto maxTxns = settings->getSetting(SettingsId::MAX_CONCURRENT_STREAMS,
100);
std::list<unique_ptr<StrictMock<MockHTTPHandler>>> handlers;
{
InSequence enforceOrder;
for (auto i = 0U; i < maxTxns; i++) {
this->sendRequest();
auto handler = this->addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM();
handlers.push_back(std::move(handler));
}
auto streamID = this->sendRequest();
this->clientCodec_->generateGoaway(this->requests_, 0, ErrorCode::NO_ERROR);
for (auto& handler: handlers) {
EXPECT_CALL(*handler, onGoaway(ErrorCode::NO_ERROR));
}
this->flushRequestsAndLoop();
EXPECT_CALL(this->callbacks_, onSettings(_));
EXPECT_CALL(this->callbacks_, onAbort(streamID, ErrorCode::REFUSED_STREAM));
this->parseOutput(*this->clientCodec_);
}
// handlers can finish out of order?
for (auto& handler: handlers) {
handler->sendReplyWithBody(200, 100);
handler->expectDetachTransaction();
}
this->expectDetachSession();
this->eventBase_.loop();
}
// Set max streams=1
// send two spdy requests a few ms apart.
// Block writes
// generate a complete response for txn=1 before parsing txn=3
// HTTPSession should allow the txn=3 to be served rather than refusing it
TEST_F(SPDY3DownstreamSessionTest, SpdyMaxConcurrentStreams) {
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
req.setWantsKeepalive(false);
sendRequest(req);
auto req2p = sendRequestLater(req, true);
httpSession_->setEgressSettings({{
SettingsId::MAX_CONCURRENT_STREAMS, 1}});
InSequence handlerSequence;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, req, this, &req2p] {
transport_->pauseWrites();
handler1->sendReplyWithBody(200, 100);
req2p.setValue();
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2, this] {
handler2->sendReplyWithBody(200, 100);
resumeWritesInLoop();
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
REGISTER_TYPED_TEST_CASE_P(HTTPDownstreamTest,
TestWritesDraining, TestBodySizeLimit,
TestUniformPauseState, TestMaxTxns);
typedef ::testing::Types<SPDY3CodecPair, SPDY3_1CodecPair,
HTTP2CodecPair> ParallelCodecs;
INSTANTIATE_TYPED_TEST_CASE_P(ParallelCodecs,
HTTPDownstreamTest,
ParallelCodecs);
class SPDY31DownstreamTest : public HTTPDownstreamTest<SPDY3_1CodecPair> {
public:
SPDY31DownstreamTest()
: HTTPDownstreamTest<SPDY3_1CodecPair>({-1, -1,
2 * spdy::kInitialWindow}) {}
};
TEST_F(SPDY31DownstreamTest, TestSessionFlowControl) {
eventBase_.loopOnce();
InSequence sequence;
EXPECT_CALL(callbacks_, onSettings(_));
EXPECT_CALL(callbacks_, onWindowUpdate(0, spdy::kInitialWindow));
parseOutput(*clientCodec_);
cleanup();
}
TEST_F(SPDY3DownstreamSessionTest, TestEOFOnBlockedStream) {
sendRequest();
auto handler1 = addSimpleStrictHandler();
InSequence handlerSequence;
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 80000);
});
handler1->expectEgressPaused();
handler1->expectError([&] (const HTTPException& ex) {
// Not optimal to have a different error code here than the session
// flow control case, but HTTPException direction is immutable and
// building another one seems not future proof.
EXPECT_EQ(ex.getDirection(), HTTPException::Direction::INGRESS);
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(10));
}
TEST_F(SPDY31DownstreamTest, TestEOFOnBlockedSession) {
sendRequest();
sendRequest();
InSequence handlerSequence;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendHeaders(200, 40000);
handler1->sendBody(32769);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2, this] {
handler2->sendHeaders(200, 40000);
handler2->sendBody(32768);
eventBase_.runInLoop([this] { transport_->addReadEOF(milliseconds(0)); });
});
handler1->expectEgressPaused();
handler2->expectEgressPaused();
handler1->expectEgressResumed();
handler2->expectEgressResumed();
handler1->expectError([&] (const HTTPException& ex) {
EXPECT_EQ(ex.getDirection(),
HTTPException::Direction::INGRESS_AND_EGRESS);
});
handler1->expectDetachTransaction();
handler2->expectError([&] (const HTTPException& ex) {
EXPECT_EQ(ex.getDirection(),
HTTPException::Direction::INGRESS_AND_EGRESS);
});
handler2->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(SPDY3DownstreamSessionTest, NewTxnEgressPaused) {
// Send 1 request with prio=0
// Have egress pause while sending the first response
// Send a second request with prio=1
// -- the new txn should start egress paused
// Finish the body and eom both responses
// Unpause egress
// The first txn should complete first
sendRequest("/", 0);
auto req2 = getGetRequest();
req2.setPriority(1);
auto req2p = sendRequestLater(req2, true);
unique_ptr<StrictMock<MockHTTPHandler>> handler1;
unique_ptr<StrictMock<MockHTTPHandler>> handler2;
httpSession_->setWriteBufferLimit(200); // lower the per session buffer limit
{
InSequence handlerSequence;
handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this, &req2p] {
this->transport_->pauseWrites();
handler1->sendHeaders(200, 1000);
handler1->sendBody(100); // headers + 100 bytes - over the limit
req2p.setValue();
});
handler1->expectEgressPaused([] { LOG(INFO) << "paused 1"; });
handler2 = addSimpleStrictHandler();
handler2->expectEgressPaused(); // starts paused
handler2->expectHeaders();
handler2->expectEOM([&] {
// Technically shouldn't send while handler is egress paused, but meh.
handler1->sendBody(900);
handler1->txn_->sendEOM();
handler2->sendReplyWithBody(200, 1000);
resumeWritesInLoop();
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
}
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks_, onMessageBegin(_, _))
.Times(2);
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.Times(2);
// body is variable and hence ignored;
EXPECT_CALL(callbacks_, onMessageComplete(_, _))
.WillRepeatedly(Invoke([&](HTTPCodec::StreamID stream, bool /*upgrade*/) {
streams.push_back(stream);
}));
parseOutput(*clientCodec_);
cleanup();
}
TEST_F(HTTP2DownstreamSessionTest, ZeroDeltaWindowUpdate) {
// generateHeader() will create a session and a transaction
auto streamID = sendHeader();
// First generate a frame with delta=1 so as to pass the checks, and then
// hack the frame so that delta=0 without modifying other checks
clientCodec_->generateWindowUpdate(requests_, streamID, 1);
requests_.trimEnd(http2::kFrameWindowUpdateSize);
QueueAppender appender(&requests_, http2::kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(0);
auto handler = addSimpleStrictHandler();
InSequence handlerSequence;
handler->expectHeaders();
handler->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getCodecStatusCode(), ErrorCode::PROTOCOL_ERROR);
ASSERT_EQ(
"streamID=1 with HTTP2Codec stream error: window update delta=0",
std::string(ex.what()));
});
handler->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTP2DownstreamSessionTest, PaddingFlowControl) {
// generateHeader() will create a session and a transaction
auto streamID = sendHeader();
// This sends a total of 33kb including padding, so we should get a session
// and stream window update
for (auto i = 0; i < 129; i++) {
clientCodec_->generateBody(requests_, streamID, makeBuf(1), 255, false);
}
auto handler = addSimpleStrictHandler();
InSequence handlerSequence;
handler->expectHeaders([&] {
handler->txn_->pauseIngress();
eventBase_.runAfterDelay([&] { handler->txn_->resumeIngress(); },
100);
});
EXPECT_CALL(*handler, onBody(_))
.Times(129);
handler->expectError();
handler->expectDetachTransaction();
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop(false, milliseconds(0), milliseconds(0), [&] {
clientCodec_->generateRstStream(requests_, streamID, ErrorCode::CANCEL);
clientCodec_->generateGoaway(requests_, 0, ErrorCode::NO_ERROR);
transport_->addReadEvent(requests_, milliseconds(110));
});
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks_, onWindowUpdate(0, _));
EXPECT_CALL(callbacks_, onWindowUpdate(1, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTP2DownstreamSessionTest, GracefulDrainOnTimeout) {
InSequence handlerSequence;
std::chrono::milliseconds gracefulTimeout(200);
httpSession_->enableDoubleGoawayDrain();
EXPECT_CALL(mockController_, getGracefulShutdownTimeout())
.WillOnce(InvokeWithoutArgs([&] {
// Once session asks for graceful shutdown timeout, expect the client
// to receive the first GOAWAY
eventBase_.runInLoop([&] {
EXPECT_CALL(callbacks_,
onGoaway(std::numeric_limits<int32_t>::max(),
ErrorCode::NO_ERROR, _));
parseOutput(*clientCodec_);
});
return gracefulTimeout;
}));
// Simulate ConnectionManager idle timeout
eventBase_.runAfterDelay([&] { httpSession_->timeoutExpired(); },
transactionTimeouts_->getDefaultTimeout().count());
HTTPSession::DestructorGuard g(httpSession_);
auto start = getCurrentTime();
eventBase_.loop();
auto finish = getCurrentTime();
auto minDuration =
gracefulTimeout + transactionTimeouts_->getDefaultTimeout();
EXPECT_GE((finish - start).count(), minDuration.count());
EXPECT_CALL(callbacks_, onGoaway(0, ErrorCode::NO_ERROR, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] request 1st stream (getGetRequest())
* - [server --> client] respond 1st stream (res with length 100)
* - [server --> client] request 2nd stream (req)
* - [server --> client] respond 2nd stream (res with length 200 + EOM)
* - [client --> server] RST_STREAM on the 1st stream
*/
TEST_F(HTTP2DownstreamSessionTest, ServerPush) {
// Create a dummy request and a dummy response messages
HTTPMessage req, res;
req.getHeaders().set("HOST", "www.foo.com");
req.setURL("https://www.foo.com/");
res.setStatusCode(200);
res.setStatusMessage("Ohai");
// enable server push
clientCodec_->getEgressSettings()->setSetting(SettingsId::ENABLE_PUSH, 1);
clientCodec_->generateSettings(requests_);
// generateHeader() will create a session and a transaction
auto assocStreamId = HTTPCodec::StreamID(1);
clientCodec_->generateHeader(requests_, assocStreamId, getGetRequest(),
false, nullptr);
auto handler = addSimpleStrictHandler();
StrictMock<MockHTTPPushHandler> pushHandler;
InSequence handlerSequence;
handler->expectHeaders([&] {
// Generate response for the associated stream
handler->txn_->sendHeaders(res);
handler->txn_->sendBody(makeBuf(100));
handler->txn_->pauseIngress();
auto* pushTxn = handler->txn_->newPushedTransaction(&pushHandler);
ASSERT_NE(pushTxn, nullptr);
// Generate a push request (PUSH_PROMISE)
auto outgoingStreams = httpSession_->getNumOutgoingStreams();
pushTxn->sendHeaders(req);
EXPECT_EQ(httpSession_->getNumOutgoingStreams(), outgoingStreams);
// Generate a push response
auto pri = handler->txn_->getPriority();
res.setHTTP2Priority(std::make_tuple(pri.streamDependency,
pri.exclusive, pri.weight));
pushTxn->sendHeaders(res);
EXPECT_EQ(httpSession_->getNumOutgoingStreams(), outgoingStreams + 1);
pushTxn->sendBody(makeBuf(200));
pushTxn->sendEOM();
eventBase_.runAfterDelay([&] { handler->txn_->resumeIngress(); },
100);
});
EXPECT_CALL(pushHandler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
pushHandler.txn_ = txn; }));
EXPECT_CALL(pushHandler, detachTransaction());
handler->expectError();
handler->expectDetachTransaction();
transport_->addReadEvent(requests_, milliseconds(0));
clientCodec_->generateRstStream(requests_, assocStreamId, ErrorCode::CANCEL);
clientCodec_->generateGoaway(requests_, 2, ErrorCode::NO_ERROR);
transport_->addReadEvent(requests_, milliseconds(200));
transport_->startReadEvents();
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
EXPECT_CALL(callbacks_, onMessageBegin(1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(1, _));
EXPECT_CALL(callbacks_, onPushMessageBegin(2, 1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(2, _));
EXPECT_CALL(callbacks_, onMessageBegin(2, _));
EXPECT_CALL(callbacks_, onHeadersComplete(2, _));
EXPECT_CALL(callbacks_, onMessageComplete(2, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTP2DownstreamSessionTest, ServerPushAbortPaused) {
// Create a dummy request and a dummy response messages
HTTPMessage req, res;
req.getHeaders().set("HOST", "www.foo.com");
req.setURL("https://www.foo.com/");
res.setStatusCode(200);
res.setStatusMessage("Ohai");
// enable server push
clientCodec_->getEgressSettings()->setSetting(SettingsId::ENABLE_PUSH, 1);
clientCodec_->generateSettings(requests_);
// generateHeader() will create a session and a transaction
auto assocStreamId = HTTPCodec::StreamID(1);
clientCodec_->generateHeader(requests_, assocStreamId, getGetRequest(),
false, nullptr);
auto handler = addSimpleStrictHandler();
StrictMock<MockHTTPPushHandler> pushHandler;
InSequence handlerSequence;
handler->expectHeaders([&] {
// Generate response for the associated stream
this->transport_->pauseWrites();
handler->txn_->sendHeaders(res);
handler->txn_->sendBody(makeBuf(100));
handler->txn_->pauseIngress();
auto* pushTxn = handler->txn_->newPushedTransaction(&pushHandler);
ASSERT_NE(pushTxn, nullptr);
// Generate a push request (PUSH_PROMISE)
pushTxn->sendHeaders(req);
});
EXPECT_CALL(pushHandler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
pushHandler.txn_ = txn; }));
EXPECT_CALL(pushHandler, onError(_));
EXPECT_CALL(pushHandler, detachTransaction());
handler->expectError();
handler->expectDetachTransaction();
transport_->addReadEvent(requests_, milliseconds(0));
// Cancels everything
clientCodec_->generateRstStream(requests_, assocStreamId, ErrorCode::CANCEL);
transport_->addReadEvent(requests_, milliseconds(10));
transport_->startReadEvents();
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityWeightsTinyRatio) {
// Create a transaction with egress and a ratio small enough that
// ratio*4096 < 1.
//
// root
// / \ level 1
// 256 1 (no egress)
// / \ level 2
// 256 1 <-- has ratio (1/257)^2
InSequence enforceOrder;
auto req1 = getGetRequest();
auto req2 = getGetRequest();
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 255});
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 0});
sendRequest(req1);
auto id2 = sendRequest(req2);
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{id2, false, 255});
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{id2, false, 0});
sendRequest(req1);
sendRequest(req2);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 4 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM();
auto handler3 = addSimpleStrictHandler();
handler3->expectHeaders();
handler3->expectEOM([&] {
handler3->sendReplyWithBody(200, 15);
});
auto handler4 = addSimpleStrictHandler();
handler4->expectHeaders();
handler4->expectEOM([&] {
handler4->sendReplyWithBody(200, 1);
});
handler1->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler1->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler1->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// id1 had no egress when id2 was running, so id1 was contending only with
// id3 and id4. Average number of contentions for id1 is 3
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 3);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 3);
// this is a first level transaction, depth == 1
EXPECT_EQ(summary.depth_.byTransactionBytes_, 1);
EXPECT_EQ(summary.depth_.bySessionBytes_, 1);
// the expected relative weight is 256/257 ~= 0.9961
EXPECT_GT(summary.expected_weight_, 0.996);
EXPECT_LT(summary.expected_weight_, 0.9962);
// the measured relative weight is 4096/(4096+15) ~= 0.99635
// This value is higher than the expected relative weight of 0.9961.
// Due to the arithmetical rounding to the lowest integer, the measured
// relative weight tends to be higher for transactions with high relative
// weights and lower for transactions with the low relative weights.
EXPECT_GT(summary.measured_weight_, 0.9963);
EXPECT_LT(summary.measured_weight_, 0.9964);
});
handler3->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler3->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler3->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// Similarly, id3 was contenting with id1 and id4
// Average number of contentions for id3 is 3
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 3);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 3);
// this is a second level transaction where parent has
// no egress, depth == 2
EXPECT_EQ(summary.depth_.byTransactionBytes_, 2);
EXPECT_EQ(summary.depth_.bySessionBytes_, 2);
// the expected relative weight should be
// 1/257 * 256/257 ~= 0.00388. However, in the calculation of the
// allowed bytes to send we rounding to the lowest positive integer.
// Therefore, the measured relative weight tends to be less than
// it should be. In this example, the allowed bytes sent is
// 4096 * 0.00388 ~= 15.89, which is rounded to 15. Hence the measured
// relative weight is 15/(4096+15) ~= 0.00365
EXPECT_GT(summary.expected_weight_, 0.00388);
EXPECT_LT(summary.expected_weight_, 0.0039);
EXPECT_GT(summary.measured_weight_, 0.00364);
EXPECT_LT(summary.measured_weight_, 0.00366);
});
handler4->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler4->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler4->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// This is the priority-based blocking situation. id4 was blocked by
// higher priority transactions id1 and id3. Only when id1 and id3
// finished, id4 had a chance to transfer its data.
// Average contention number weighted by transaction bytes is 1, which
// means that when id4 had a chance to transfer bytes it did not contend
// with any other transactions.
// id4 was waiting for id1 and id3 during transfer of 4256 bytes (encoded)
// after which it tranferred 10 bytes (encoded) without contention.
// Therefore, the average number contentions weighted by session bytes is
// (4111*3 + 1*1)/(4111 + 1) = 12334/4112 ~= 2.999
// The difference in average contentions weighted by transaction and
// session bytes tells that id4 was mostly blocked by rather than blocking
// other transactions.
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 1);
EXPECT_GT(summary.contentions_.bySessionBytes_, 2.99);
EXPECT_LT(summary.contentions_.bySessionBytes_, 3.00);
// this is a second level transaction where parent has
// no egress, depth == 2
EXPECT_EQ(summary.depth_.byTransactionBytes_, 2);
EXPECT_EQ(summary.depth_.bySessionBytes_, 2);
// the expected relative weight should be
// 1/257 * 1/257 ~= 0.000015.
// Because no bytes of this transaction were sent during the previous
// egress, the expected relative weight was calculated as:
// (0*4111 + 1*1)/(4111 + 1) ~= 0.000243
EXPECT_GT(summary.expected_weight_, 0.000243);
EXPECT_LT(summary.expected_weight_, 0.000244);
// The measured weight is (0+1)/(4111+1) ~= 0.000243
// The difference between the theoretical value of 0.000015 and the
// measured one is not because of the arithmetical rounding, but because
// all other transactions are completed and the relative waight for the
// only survived transaction was elevated to 1.0
EXPECT_GT(summary.measured_weight_, 0.000243);
EXPECT_LT(summary.measured_weight_, 0.000244);
handler2->txn_->sendAbort();
});
handler2->expectDetachTransaction();
flushRequestsAndLoop();
httpSession_->closeWhenIdle();
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityDependentTransactions) {
// Create a dependent transaction to test the priority blocked by dependency.
// ratio*4096 < 1.
//
// root
// \ level 1
// 16
// \ level 2
// 16
InSequence enforceOrder;
auto req1 = getGetRequest();
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 15});
auto id1 = sendRequest(req1);
auto req2 = getGetRequest();
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{id1, false, 15});
sendRequest(req2);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 1024);
});
handler1->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler1->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler1->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// id1 is contending with id2 during the entire transfer.
// Average number of contentions for id1 is 2 in both cases.
// The same number of average contentions weighted by both transaction
// and session bytes tells that id1 was not blocked by any other
// transaction during the entire transfer.
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 2);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 2);
// this is a first level transaction, depth == 1
EXPECT_EQ(summary.depth_.byTransactionBytes_, 1);
EXPECT_EQ(summary.depth_.bySessionBytes_, 1);
// dependent transaction is blocked, the parent is egressing on 100%
EXPECT_EQ(summary.expected_weight_, 1);
EXPECT_EQ(summary.measured_weight_, 1);
});
handler2->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler2->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler2->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// This is the dependency-based blocking. id2 is blocked by id1.
// When id2 had a chance to transfer bytes, it was no longer contended
// with any other transaction. Hence the average contention weighted by
// transaction bytes is 1.
// The average number of contentions weighted by the session bytes is
// computed as (1024*2 + 1024*1)/(1024 + 1024) = 3072/2048 = 1.5
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 1);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 1.5);
// The transaction transferred bytes only when its parent transaction
// completed. At that time its level decreased to 1. The average depth
// weighted by session bytes is (2*1024 + 1*1024)/(2048) = 1.5.
EXPECT_EQ(summary.depth_.byTransactionBytes_, 1);
EXPECT_EQ(summary.depth_.bySessionBytes_, 1.5);
// this dependent transaction was bloted, so it was egressiong only 1/2
// of the session bytes.
EXPECT_EQ(summary.expected_weight_, 0.5);
EXPECT_EQ(summary.measured_weight_, 0.5);
handler2->txn_->sendAbort();
});
flushRequestsAndLoop();
httpSession_->closeWhenIdle();
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestDisablePriorities) {
// turn off HTTP2 priorities
httpSession_->setHTTP2PrioritiesEnabled(false);
InSequence enforceOrder;
HTTPMessage req1 = getGetRequest();
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 0});
sendRequest(req1);
HTTPMessage req2 = getGetRequest();
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 255});
sendRequest(req2);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 4 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 4 * 1024);
});
// expecting handler 1 to finish first irrespective of
// request 2 having higher weight
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoop();
httpSession_->closeWhenIdle();
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityWeights) {
// virtual priority node with pri=4
auto priGroupID = clientCodec_->createStream();
clientCodec_->generatePriority(
requests_, priGroupID, HTTPMessage::HTTPPriority(0, false, 3));
// Both txn's are at equal pri=16
auto id1 = sendRequest();
auto id2 = sendRequest();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendHeaders(200, 12 * 1024);
handler1->txn_->sendBody(makeBuf(4 * 1024));
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendHeaders(200, 12 * 1024);
handler2->txn_->sendBody(makeBuf(4 * 1024));
});
// twice- once to send and once to receive
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onSettings(_));
EXPECT_CALL(callbacks_, onMessageBegin(id1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id1, _));
EXPECT_CALL(callbacks_, onMessageBegin(id2, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id2, _));
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
parseOutput(*clientCodec_);
// update handler2 to be in the pri-group (which has lower weight)
clientCodec_->generatePriority(
requests_, id2, HTTPMessage::HTTPPriority(priGroupID, false, 15));
eventBase_.runInLoop([&] {
handler1->txn_->sendBody(makeBuf(4 * 1024));
handler2->txn_->sendBody(makeBuf(4 * 1024));
});
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(1 * 1024))
.WillOnce(ExpectBodyLen(3 * 1024));
parseOutput(*clientCodec_);
// update vnode weight to match txn1 weight
clientCodec_->generatePriority(requests_, priGroupID,
HTTPMessage::HTTPPriority(0, false, 15));
eventBase_.runInLoop([&] {
handler1->txn_->sendBody(makeBuf(4 * 1024));
handler1->txn_->sendEOM();
handler2->txn_->sendBody(makeBuf(4 * 1024));
handler2->txn_->sendEOM();
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoopN(2);
// expect 32/32
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onMessageComplete(id1, _));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onMessageComplete(id2, _));
parseOutput(*clientCodec_);
httpSession_->closeWhenIdle();
expectDetachSession();
this->eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityWeightsTinyWindow) {
httpSession_->setWriteBufferLimit(2 * 65536);
InSequence enforceOrder;
auto id1 = sendRequest();
auto id2 = sendRequest();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 32 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 32 * 1024);
});
handler1->expectDetachTransaction();
// twice- once to send and once to receive
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onSettings(_));
EXPECT_CALL(callbacks_, onMessageBegin(id1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id1, _));
EXPECT_CALL(callbacks_, onMessageBegin(id2, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id2, _));
for (auto i = 0; i < 7; i++) {
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
}
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024 - 1));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024 - 1));
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(1));
EXPECT_CALL(callbacks_, onMessageComplete(id1, _));
parseOutput(*clientCodec_);
// open the window
clientCodec_->generateWindowUpdate(requests_, 0, 100);
handler2->expectDetachTransaction();
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(1));
EXPECT_CALL(callbacks_, onMessageComplete(id2, _));
parseOutput(*clientCodec_);
httpSession_->closeWhenIdle();
expectDetachSession();
this->eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestShortContentLength) {
auto req = getPostRequest(10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectError([&handler1] (const HTTPException& ex) {
EXPECT_EQ(ex.getProxygenError(), kErrorParseBody);
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
/**
* If handler chooses to untie itself with transaction during onError,
* detachTransaction shouldn't be expected
*/
TEST_F(HTTP2DownstreamSessionTest, TestBadContentLengthUntieHandler) {
auto req = getPostRequest(10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(
requests_,
streamID,
makeBuf(20),
HTTPCodec::NoPadding,
true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectError([&] (const HTTPException&) {
if (handler1->txn_) {
handler1->txn_->setHandler(nullptr);
}
handler1->txn_ = nullptr;
});
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestLongContentLength) {
auto req = getPostRequest(30);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectBody();
handler1->expectError([&handler1] (const HTTPException& ex) {
EXPECT_EQ(ex.getProxygenError(), kErrorParseBody);
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestMalformedContentLength) {
auto req = getPostRequest();
req.getHeaders().set(HTTP_HEADER_CONTENT_LENGTH, "malformed");
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectBody();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 100);
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestHeadContentLength) {
InSequence enforceOrder;
auto req = getGetRequest();
req.setMethod(HTTPMethod::HEAD);
sendRequest(req);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendHeaders(200, 100);
// no body for head
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, Test304ContentLength) {
InSequence enforceOrder;
auto req = getGetRequest();
req.setMethod(HTTPMethod::HEAD);
sendRequest(req);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendHeaders(304, 100);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
// chunked with wrong content-length
TEST_F(HTTPDownstreamSessionTest, HttpShortContentLength) {
InSequence enforceOrder;
auto req = getPostRequest(10);
req.setIsChunked(true);
req.getHeaders().add(HTTP_HEADER_TRANSFER_ENCODING, "chunked");
auto streamID = sendRequest(req, false);
clientCodec_->generateChunkHeader(requests_, streamID, 20);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, false);
clientCodec_->generateChunkTerminator(requests_, streamID);
clientCodec_->generateEOM(requests_, streamID);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
EXPECT_CALL(*handler1, onChunkHeader(20));
handler1->expectError([&handler1] (const HTTPException& ex) {
EXPECT_EQ(ex.getProxygenError(), kErrorParseBody);
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTP2DownstreamSessionTest, TestSessionStallByFlowControl) {
NiceMock<MockHTTPSessionStats> stats;
// By default the send and receive windows are 64K each.
// If we use only a single transaction, that transaction
// will be paused on reaching 64K. Therefore, to pause the session,
// it is used 2 transactions each sending 32K.
// Make write buffer limit exceding 64K, for example 128K
httpSession_->setWriteBufferLimit(128 * 1024);
httpSession_->setSessionStats(&stats);
InSequence enforceOrder;
sendRequest();
sendRequest();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 32 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 32 * 1024);
});
EXPECT_CALL(stats, recordSessionStalled()).Times(1);
handler1->expectDetachTransaction();
// twice- once to send and once to receive
flushRequestsAndLoopN(2);
// open the window
clientCodec_->generateWindowUpdate(requests_, 0, 100);
handler2->expectDetachTransaction();
flushRequestsAndLoopN(2);
httpSession_->closeWhenIdle();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTP2DownstreamSessionTest, TestTransactionStallByFlowControl) {
StrictMock<MockHTTPSessionStats> stats;
httpSession_->setSessionStats(&stats);
// Set the client side stream level flow control wind to 500 bytes,
// and try to send 1000 bytes through it.
// Then the flow control kicks in and stalls the transaction.
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec_->generateSettings(requests_);
auto streamID = sendRequest();
EXPECT_CALL(stats, recordTransactionOpened());
InSequence handlerSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&] {
handler->sendReplyWithBody(200, 1000);
});
EXPECT_CALL(stats, recordTransactionStalled());
handler->expectEgressPaused();
handler->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("ingress timeout, streamID=", streamID),
std::string(ex.what()));
handler->terminate();
});
handler->expectDetachTransaction();
EXPECT_CALL(stats, recordTransactionClosed());
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestTransactionNotStallByFlowControl) {
StrictMock<MockHTTPSessionStats> stats;
httpSession_->setSessionStats(&stats);
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec_->generateSettings(requests_);
sendRequest();
EXPECT_CALL(stats, recordTransactionOpened());
InSequence handlerSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&] {
handler->sendReplyWithBody(200, 500);
});
// The egtress paused is notified due to existing logics,
// but egress transaction should not be counted as stalled by flow control,
// because there is nore more bytes to send
handler->expectEgressPaused();
handler->expectDetachTransaction();
EXPECT_CALL(stats, recordTransactionClosed());
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestSetEgressSettings) {
SettingsList settings = {{ SettingsId::HEADER_TABLE_SIZE, 5555 },
{ SettingsId::MAX_FRAME_SIZE, 16384 },
{ SettingsId::ENABLE_PUSH, 1 }};
const HTTPSettings* codecSettings = rawCodec_->getEgressSettings();
for (const auto& setting: settings) {
const HTTPSetting* currSetting = codecSettings->getSetting(setting.id);
if (currSetting) {
EXPECT_EQ(setting.value, currSetting->value);
}
}
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestDuplicateRequestStream) {
// Send the following:
// HEADERS id=1
// HEADERS id=2
// HEADERS id=1 (trailers)
// HEADERS id=2 -> contains pseudo-headers after EOM so ignored
auto handler2 = addSimpleStrictHandler();
auto handler1 = addSimpleStrictHandler();
auto streamID1 = sendRequest("/withtrailers", 0, false);
auto streamID2 = sendRequest();
HTTPHeaders trailers;
trailers.add("Foo", "Bar");
clientCodec_->generateTrailers(requests_, streamID1, trailers);
clientCodec_->generateEOM(requests_, streamID1);
clientCodec_->generateHeader(requests_, streamID2, getGetRequest(), false);
handler1->expectHeaders();
handler2->expectHeaders();
handler2->expectEOM();
handler1->expectTrailers();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 100);
// 2 got an error after EOM, which gets ignored - need a response to
// cleanly terminate it
handler2->sendReplyWithBody(200, 100);
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_600_2 |
crossvul-cpp_data_good_4220_2 | /* -*- C++ -*-
* Copyright 2019-2020 LibRaw LLC (info@libraw.org)
*
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
*/
#include "../../internal/libraw_cxx_defs.h"
libraw_processed_image_t *LibRaw::dcraw_make_mem_thumb(int *errcode)
{
if (!T.thumb)
{
if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
load_raw == &LibRaw::broadcom_load_raw) // RPi
)
{
if (errcode)
*errcode = LIBRAW_NO_THUMBNAIL;
}
else
{
if (errcode)
*errcode = LIBRAW_OUT_OF_ORDER_CALL;
}
return NULL;
}
if (T.tlength < 64u)
{
if (errcode)
*errcode = EINVAL;
return NULL;
}
if (INT64(T.tlength) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB)
{
if (errcode)
*errcode = LIBRAW_TOO_BIG;
return NULL;
}
if (T.tformat == LIBRAW_THUMBNAIL_BITMAP)
{
libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(
sizeof(libraw_processed_image_t) + T.tlength);
if (!ret)
{
if (errcode)
*errcode = ENOMEM;
return NULL;
}
memset(ret, 0, sizeof(libraw_processed_image_t));
ret->type = LIBRAW_IMAGE_BITMAP;
ret->height = T.theight;
ret->width = T.twidth;
ret->colors = 3;
ret->bits = 8;
ret->data_size = T.tlength;
memmove(ret->data, T.thumb, T.tlength);
if (errcode)
*errcode = 0;
return ret;
}
else if (T.tformat == LIBRAW_THUMBNAIL_JPEG)
{
ushort exif[5];
int mk_exif = 0;
if (strcmp(T.thumb + 6, "Exif"))
mk_exif = 1;
int dsize = T.tlength + mk_exif * (sizeof(exif) + sizeof(tiff_hdr));
libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(
sizeof(libraw_processed_image_t) + dsize);
if (!ret)
{
if (errcode)
*errcode = ENOMEM;
return NULL;
}
memset(ret, 0, sizeof(libraw_processed_image_t));
ret->type = LIBRAW_IMAGE_JPEG;
ret->data_size = dsize;
ret->data[0] = 0xff;
ret->data[1] = 0xd8;
if (mk_exif)
{
struct tiff_hdr th;
memcpy(exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons(8 + sizeof th);
memmove(ret->data + 2, exif, sizeof(exif));
tiff_head(&th, 0);
memmove(ret->data + (2 + sizeof(exif)), &th, sizeof(th));
memmove(ret->data + (2 + sizeof(exif) + sizeof(th)), T.thumb + 2,
T.tlength - 2);
}
else
{
memmove(ret->data + 2, T.thumb + 2, T.tlength - 2);
}
if (errcode)
*errcode = 0;
return ret;
}
else
{
if (errcode)
*errcode = LIBRAW_UNSUPPORTED_THUMBNAIL;
return NULL;
}
}
// jlb
// macros for copying pixels to either BGR or RGB formats
#define FORBGR for (c = P1.colors - 1; c >= 0; c--)
#define FORRGB for (c = 0; c < P1.colors; c++)
void LibRaw::get_mem_image_format(int *width, int *height, int *colors,
int *bps) const
{
*width = S.width;
*height = S.height;
if (imgdata.progress_flags < LIBRAW_PROGRESS_FUJI_ROTATE)
{
if (O.use_fuji_rotate)
{
if (IO.fuji_width)
{
int fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink;
*width = (ushort)(fuji_width / sqrt(0.5));
*height = (ushort)((*height - fuji_width) / sqrt(0.5));
}
else
{
if (S.pixel_aspect < 0.995)
*height = (ushort)(*height / S.pixel_aspect + 0.5);
if (S.pixel_aspect > 1.005)
*width = (ushort)(*width * S.pixel_aspect + 0.5);
}
}
}
if (S.flip & 4)
{
std::swap(*width, *height);
}
*colors = P1.colors;
*bps = O.output_bps;
}
int LibRaw::copy_mem_image(void *scan0, int stride, int bgr)
{
// the image memory pointed to by scan0 is assumed to be in the format
// returned by get_mem_image_format
if ((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) <
LIBRAW_PROGRESS_PRE_INTERPOLATE)
return LIBRAW_OUT_OF_ORDER_CALL;
if (libraw_internal_data.output_data.histogram)
{
int perc, val, total, t_white = 0x2000, c;
perc = S.width * S.height * O.auto_bright_thr;
if (IO.fuji_width)
perc /= 2;
if (!((O.highlight & ~2) || O.no_auto_bright))
for (t_white = c = 0; c < P1.colors; c++)
{
for (val = 0x2000, total = 0; --val > 32;)
if ((total += libraw_internal_data.output_data.histogram[c][val]) >
perc)
break;
if (t_white < val)
t_white = val;
}
gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright);
}
int s_iheight = S.iheight;
int s_iwidth = S.iwidth;
int s_width = S.width;
int s_hwight = S.height;
S.iheight = S.height;
S.iwidth = S.width;
if (S.flip & 4)
SWAP(S.height, S.width);
uchar *ppm;
ushort *ppm2;
int c, row, col, soff, rstep, cstep;
soff = flip_index(0, 0);
cstep = flip_index(0, 1) - soff;
rstep = flip_index(1, 0) - flip_index(0, S.width);
for (row = 0; row < S.height; row++, soff += rstep)
{
uchar *bufp = ((uchar *)scan0) + row * stride;
ppm2 = (ushort *)(ppm = bufp);
// keep trivial decisions in the outer loop for speed
if (bgr)
{
if (O.output_bps == 8)
{
for (col = 0; col < S.width; col++, soff += cstep)
FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8;
}
else
{
for (col = 0; col < S.width; col++, soff += cstep)
FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]];
}
}
else
{
if (O.output_bps == 8)
{
for (col = 0; col < S.width; col++, soff += cstep)
FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8;
}
else
{
for (col = 0; col < S.width; col++, soff += cstep)
FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]];
}
}
// bufp += stride; // go to the next line
}
S.iheight = s_iheight;
S.iwidth = s_iwidth;
S.width = s_width;
S.height = s_hwight;
return 0;
}
#undef FORBGR
#undef FORRGB
libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode)
{
int width, height, colors, bps;
get_mem_image_format(&width, &height, &colors, &bps);
int stride = width * (bps / 8) * colors;
unsigned ds = height * stride;
libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(
sizeof(libraw_processed_image_t) + ds);
if (!ret)
{
if (errcode)
*errcode = ENOMEM;
return NULL;
}
memset(ret, 0, sizeof(libraw_processed_image_t));
// metadata init
ret->type = LIBRAW_IMAGE_BITMAP;
ret->height = height;
ret->width = width;
ret->colors = colors;
ret->bits = bps;
ret->data_size = ds;
copy_mem_image(ret->data, stride, 0);
return ret;
}
void LibRaw::dcraw_clear_mem(libraw_processed_image_t *p)
{
if (p)
::free(p);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_4220_2 |
crossvul-cpp_data_bad_3853_0 | /* +------------------------------------+
* | Inspire Internet Relay Chat Daemon |
* +------------------------------------+
*
* InspIRCd: (C) 2002-2010 InspIRCd Development Team
* See: http://wiki.inspircd.org/Credits
*
* This program is free but copyrighted software; see
* the file COPYING for details.
*
* ---------------------------------------------------
*/
/* $Core */
/*
dns.cpp - Nonblocking DNS functions.
Very very loosely based on the firedns library,
Copyright (C) 2002 Ian Gulliver. This file is no
longer anything like firedns, there are many major
differences between this code and the original.
Please do not assume that firedns works like this,
looks like this, walks like this or tastes like this.
*/
#ifndef WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#include "inspircd_win32wrapper.h"
#endif
#include "inspircd.h"
#include "socketengine.h"
#include "configreader.h"
#include "socket.h"
#define DN_COMP_BITMASK 0xC000 /* highest 6 bits in a DN label header */
/** Masks to mask off the responses we get from the DNSRequest methods
*/
enum QueryInfo
{
ERROR_MASK = 0x10000 /* Result is an error */
};
/** Flags which can be ORed into a request or reply for different meanings
*/
enum QueryFlags
{
FLAGS_MASK_RD = 0x01, /* Recursive */
FLAGS_MASK_TC = 0x02,
FLAGS_MASK_AA = 0x04, /* Authoritative */
FLAGS_MASK_OPCODE = 0x78,
FLAGS_MASK_QR = 0x80,
FLAGS_MASK_RCODE = 0x0F, /* Request */
FLAGS_MASK_Z = 0x70,
FLAGS_MASK_RA = 0x80
};
/** Represents a dns resource record (rr)
*/
struct ResourceRecord
{
QueryType type; /* Record type */
unsigned int rr_class; /* Record class */
unsigned long ttl; /* Time to live */
unsigned int rdlength; /* Record length */
};
/** Represents a dns request/reply header, and its payload as opaque data.
*/
class DNSHeader
{
public:
unsigned char id[2]; /* Request id */
unsigned int flags1; /* Flags */
unsigned int flags2; /* Flags */
unsigned int qdcount;
unsigned int ancount; /* Answer count */
unsigned int nscount; /* Nameserver count */
unsigned int arcount;
unsigned char payload[512]; /* Packet payload */
};
class DNSRequest
{
public:
unsigned char id[2]; /* Request id */
unsigned char* res; /* Result processing buffer */
unsigned int rr_class; /* Request class */
QueryType type; /* Request type */
DNS* dnsobj; /* DNS caller (where we get our FD from) */
unsigned long ttl; /* Time to live */
std::string orig; /* Original requested name/ip */
DNSRequest(DNS* dns, int id, const std::string &original);
~DNSRequest();
DNSInfo ResultIsReady(DNSHeader &h, unsigned length);
int SendRequests(const DNSHeader *header, const int length, QueryType qt);
};
class CacheTimer : public Timer
{
private:
DNS* dns;
public:
CacheTimer(DNS* thisdns)
: Timer(3600, ServerInstance->Time(), true), dns(thisdns) { }
virtual void Tick(time_t)
{
dns->PruneCache();
}
};
class RequestTimeout : public Timer
{
DNSRequest* watch;
int watchid;
public:
RequestTimeout(unsigned long n, DNSRequest* watching, int id) : Timer(n, ServerInstance->Time()), watch(watching), watchid(id)
{
}
~RequestTimeout()
{
if (ServerInstance->Res)
Tick(0);
}
void Tick(time_t)
{
if (ServerInstance->Res->requests[watchid] == watch)
{
/* Still exists, whack it */
if (ServerInstance->Res->Classes[watchid])
{
ServerInstance->Res->Classes[watchid]->OnError(RESOLVER_TIMEOUT, "Request timed out");
delete ServerInstance->Res->Classes[watchid];
ServerInstance->Res->Classes[watchid] = NULL;
}
ServerInstance->Res->requests[watchid] = NULL;
delete watch;
}
}
};
CachedQuery::CachedQuery(const std::string &res, unsigned int ttl) : data(res)
{
expires = ServerInstance->Time() + ttl;
}
int CachedQuery::CalcTTLRemaining()
{
int n = expires - ServerInstance->Time();
return (n < 0 ? 0 : n);
}
/* Allocate the processing buffer */
DNSRequest::DNSRequest(DNS* dns, int rid, const std::string &original) : dnsobj(dns)
{
/* hardening against overflow here: make our work buffer twice the theoretical
* maximum size so that hostile input doesn't screw us over.
*/
res = new unsigned char[sizeof(DNSHeader) * 2];
*res = 0;
orig = original;
RequestTimeout* RT = new RequestTimeout(ServerInstance->Config->dns_timeout ? ServerInstance->Config->dns_timeout : 5, this, rid);
ServerInstance->Timers->AddTimer(RT); /* The timer manager frees this */
}
/* Deallocate the processing buffer */
DNSRequest::~DNSRequest()
{
delete[] res;
}
/** Fill a ResourceRecord class based on raw data input */
inline void DNS::FillResourceRecord(ResourceRecord* rr, const unsigned char *input)
{
rr->type = (QueryType)((input[0] << 8) + input[1]);
rr->rr_class = (input[2] << 8) + input[3];
rr->ttl = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + input[7];
rr->rdlength = (input[8] << 8) + input[9];
}
/** Fill a DNSHeader class based on raw data input of a given length */
inline void DNS::FillHeader(DNSHeader *header, const unsigned char *input, const int length)
{
header->id[0] = input[0];
header->id[1] = input[1];
header->flags1 = input[2];
header->flags2 = input[3];
header->qdcount = (input[4] << 8) + input[5];
header->ancount = (input[6] << 8) + input[7];
header->nscount = (input[8] << 8) + input[9];
header->arcount = (input[10] << 8) + input[11];
memcpy(header->payload,&input[12],length);
}
/** Empty a DNSHeader class out into raw data, ready for transmission */
inline void DNS::EmptyHeader(unsigned char *output, const DNSHeader *header, const int length)
{
output[0] = header->id[0];
output[1] = header->id[1];
output[2] = header->flags1;
output[3] = header->flags2;
output[4] = header->qdcount >> 8;
output[5] = header->qdcount & 0xFF;
output[6] = header->ancount >> 8;
output[7] = header->ancount & 0xFF;
output[8] = header->nscount >> 8;
output[9] = header->nscount & 0xFF;
output[10] = header->arcount >> 8;
output[11] = header->arcount & 0xFF;
memcpy(&output[12],header->payload,length);
}
/** Send requests we have previously built down the UDP socket */
int DNSRequest::SendRequests(const DNSHeader *header, const int length, QueryType qt)
{
ServerInstance->Logs->Log("RESOLVER", DEBUG,"DNSRequest::SendRequests");
unsigned char payload[sizeof(DNSHeader)];
this->rr_class = 1;
this->type = qt;
DNS::EmptyHeader(payload,header,length);
if (ServerInstance->SE->SendTo(dnsobj, payload, length + 12, 0, &(dnsobj->myserver.sa), sa_size(dnsobj->myserver)) != length+12)
return -1;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Sent OK");
return 0;
}
/** Add a query with a predefined header, and allocate an ID for it. */
DNSRequest* DNS::AddQuery(DNSHeader *header, int &id, const char* original)
{
/* Is the DNS connection down? */
if (this->GetFd() == -1)
return NULL;
/* Create an id */
do {
id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
} while (requests[id]);
DNSRequest* req = new DNSRequest(this, id, original);
header->id[0] = req->id[0] = id >> 8;
header->id[1] = req->id[1] = id & 0xFF;
header->flags1 = FLAGS_MASK_RD;
header->flags2 = 0;
header->qdcount = 1;
header->ancount = 0;
header->nscount = 0;
header->arcount = 0;
/* At this point we already know the id doesnt exist,
* so there needs to be no second check for the ::end()
*/
requests[id] = req;
/* According to the C++ spec, new never returns NULL. */
return req;
}
int DNS::ClearCache()
{
/* This ensures the buckets are reset to sane levels */
int rv = this->cache->size();
delete this->cache;
this->cache = new dnscache();
return rv;
}
int DNS::PruneCache()
{
int n = 0;
dnscache* newcache = new dnscache();
for (dnscache::iterator i = this->cache->begin(); i != this->cache->end(); i++)
/* Dont include expired items (theres no point) */
if (i->second.CalcTTLRemaining())
newcache->insert(*i);
else
n++;
delete this->cache;
this->cache = newcache;
return n;
}
void DNS::Rehash()
{
if (this->GetFd() > -1)
{
ServerInstance->SE->DelFd(this);
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
/* Rehash the cache */
this->PruneCache();
}
else
{
/* Create initial dns cache */
this->cache = new dnscache();
}
irc::sockets::aptosa(ServerInstance->Config->DNSServer, DNS::QUERY_PORT, myserver);
/* Initialize mastersocket */
int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
this->SetFd(s);
/* Have we got a socket and is it nonblocking? */
if (this->GetFd() != -1)
{
ServerInstance->SE->SetReuse(s);
ServerInstance->SE->NonBlocking(s);
irc::sockets::sockaddrs bindto;
memset(&bindto, 0, sizeof(bindto));
bindto.sa.sa_family = myserver.sa.sa_family;
if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0)
{
/* Failed to bind */
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error binding dns socket - hostnames will NOT resolve");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Internal error starting DNS - hostnames will NOT resolve.");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
}
else
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error creating DNS socket - hostnames will NOT resolve");
}
}
/** Initialise the DNS UDP socket so that we can send requests */
DNS::DNS()
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::DNS");
/* Clear the Resolver class table */
memset(Classes,0,sizeof(Classes));
/* Clear the requests class table */
memset(requests,0,sizeof(requests));
/* Set the id of the next request to 0
*/
currid = 0;
/* DNS::Rehash() sets this to a valid ptr
*/
this->cache = NULL;
/* Again, DNS::Rehash() sets this to a
* valid value
*/
this->SetFd(-1);
/* Actually read the settings
*/
this->Rehash();
this->PruneTimer = new CacheTimer(this);
ServerInstance->Timers->AddTimer(this->PruneTimer);
}
/** Build a payload to be placed after the header, based upon input data, a resource type, a class and a pointer to a buffer */
int DNS::MakePayload(const char * const name, const QueryType rr, const unsigned short rr_class, unsigned char * const payload)
{
short payloadpos = 0;
const char* tempchr, *tempchr2 = name;
unsigned short length;
/* split name up into labels, create query */
while ((tempchr = strchr(tempchr2,'.')) != NULL)
{
length = tempchr - tempchr2;
if (payloadpos + length + 1 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
tempchr2 = &tempchr[1];
}
length = strlen(tempchr2);
if (length)
{
if (payloadpos + length + 2 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
payload[payloadpos++] = 0;
}
if (payloadpos > 508)
return -1;
length = htons(rr);
memcpy(&payload[payloadpos],&length,2);
length = htons(rr_class);
memcpy(&payload[payloadpos + 2],&length,2);
return payloadpos + 4;
}
/** Start lookup of an hostname to an IP address */
int DNS::GetIP(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_A, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_A) == -1))
return -1;
return id;
}
/** Start lookup of an hostname to an IPv6 address */
int DNS::GetIP6(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_AAAA, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_AAAA) == -1))
return -1;
return id;
}
/** Start lookup of a cname to another name */
int DNS::GetCName(const char *alias)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(alias, DNS_QUERY_CNAME, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, alias);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_CNAME) == -1))
return -1;
return id;
}
/** Start lookup of an IP address to a hostname */
int DNS::GetNameForce(const char *ip, ForceProtocol fp)
{
char query[128];
DNSHeader h;
int id;
int length;
if (fp == PROTOCOL_IPV6)
{
in6_addr i;
if (inet_pton(AF_INET6, ip, &i) > 0)
{
DNS::MakeIP6Int(query, &i);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv6 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
else
{
in_addr i;
if (inet_aton(ip, &i))
{
unsigned char* c = (unsigned char*)&i.s_addr;
sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv4 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
length = this->MakePayload(query, DNS_QUERY_PTR, 1, (unsigned char*)&h.payload);
if (length == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't query '%s' using '%s' because it's too long", ip, query);
return -1;
}
DNSRequest* req = this->AddQuery(&h, id, ip);
if (!req)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't add query (resolver down?)");
return -1;
}
if (req->SendRequests(&h, length, DNS_QUERY_PTR) == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't send (firewall?)");
return -1;
}
return id;
}
/** Build an ipv6 reverse domain from an in6_addr
*/
void DNS::MakeIP6Int(char* query, const in6_addr *ip)
{
const char* hex = "0123456789abcdef";
for (int index = 31; index >= 0; index--) /* for() loop steps twice per byte */
{
if (index % 2)
/* low nibble */
*query++ = hex[ip->s6_addr[index / 2] & 0x0F];
else
/* high nibble */
*query++ = hex[(ip->s6_addr[index / 2] & 0xF0) >> 4];
*query++ = '.'; /* Seperator */
}
strcpy(query,"ip6.arpa"); /* Suffix the string */
}
/** Return the next id which is ready, and the result attached to it */
DNSResult DNS::GetResult()
{
/* Fetch dns query response and decide where it belongs */
DNSHeader header;
DNSRequest *req;
unsigned char buffer[sizeof(DNSHeader)];
irc::sockets::sockaddrs from;
memset(&from, 0, sizeof(from));
socklen_t x = sizeof(from);
int length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x);
/* Did we get the whole header? */
if (length < 12)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"GetResult didn't get a full packet (len=%d)", length);
/* Nope - something screwed up. */
return DNSResult(-1,"",0,"");
}
/* Check wether the reply came from a different DNS
* server to the one we sent it to, or the source-port
* is not 53.
* A user could in theory still spoof dns packets anyway
* but this is less trivial than just sending garbage
* to the server, which is possible without this check.
*
* -- Thanks jilles for pointing this one out.
*/
if (from != myserver)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
from.str().c_str(), myserver.str().c_str());
return DNSResult(-1,"",0,"");
}
/* Put the read header info into a header class */
DNS::FillHeader(&header,buffer,length - 12);
/* Get the id of this request.
* Its a 16 bit value stored in two char's,
* so we use logic shifts to create the value.
*/
unsigned long this_id = header.id[1] + (header.id[0] << 8);
/* Do we have a pending request matching this id? */
if (!requests[this_id])
{
/* Somehow we got a DNS response for a request we never made... */
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.", this_id);
return DNSResult(-1,"",0,"");
}
else
{
/* Remove the query from the list of pending queries */
req = requests[this_id];
requests[this_id] = NULL;
}
/* Inform the DNSRequest class that it has a result to be read.
* When its finished it will return a DNSInfo which is a pair of
* unsigned char* resource record data, and an error message.
*/
DNSInfo data = req->ResultIsReady(header, length);
std::string resultstr;
/* Check if we got a result, if we didnt, its an error */
if (data.first == NULL)
{
/* An error.
* Mask the ID with the value of ERROR_MASK, so that
* the dns_deal_with_classes() function knows that its
* an error response and needs to be treated uniquely.
* Put the error message in the second field.
*/
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, data.second, 0, ro);
}
else
{
unsigned long ttl = req->ttl;
char formatted[128];
/* Forward lookups come back as binary data. We must format them into ascii */
switch (req->type)
{
case DNS_QUERY_A:
snprintf(formatted,16,"%u.%u.%u.%u",data.first[0],data.first[1],data.first[2],data.first[3]);
resultstr = formatted;
break;
case DNS_QUERY_AAAA:
{
inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted));
char* c = strstr(formatted,":0:");
if (c != NULL)
{
memmove(c+1,c+2,strlen(c+2) + 1);
c += 2;
while (memcmp(c,"0:",2) == 0)
memmove(c,c+2,strlen(c+2) + 1);
if (memcmp(c,"0",2) == 0)
*c = 0;
if (memcmp(formatted,"0::",3) == 0)
memmove(formatted,formatted + 1, strlen(formatted + 1) + 1);
}
resultstr = formatted;
/* Special case. Sending ::1 around between servers
* and to clients is dangerous, because the : on the
* start makes the client or server interpret the IP
* as the last parameter on the line with a value ":1".
*/
if (*formatted == ':')
resultstr.insert(0, "0");
}
break;
case DNS_QUERY_CNAME:
/* Identical handling to PTR */
case DNS_QUERY_PTR:
/* Reverse lookups just come back as char* */
resultstr = std::string((const char*)data.first);
break;
default:
break;
}
/* Build the reply with the id and hostname/ip in it */
std::string ro = req->orig;
delete req;
return DNSResult(this_id,resultstr,ttl,ro);
}
}
/** A result is ready, process it */
DNSInfo DNSRequest::ResultIsReady(DNSHeader &header, unsigned length)
{
unsigned i = 0, o;
int q = 0;
int curanswer;
ResourceRecord rr;
unsigned short ptr;
/* This is just to keep _FORTIFY_SOURCE happy */
rr.type = DNS_QUERY_NONE;
rr.rdlength = 0;
rr.ttl = 1; /* GCC is a whiney bastard -- see the XXX below. */
rr.rr_class = 0; /* Same for VC++ */
if (!(header.flags1 & FLAGS_MASK_QR))
return std::make_pair((unsigned char*)NULL,"Not a query result");
if (header.flags1 & FLAGS_MASK_OPCODE)
return std::make_pair((unsigned char*)NULL,"Unexpected value in DNS reply packet");
if (header.flags2 & FLAGS_MASK_RCODE)
return std::make_pair((unsigned char*)NULL,"Domain name not found");
if (header.ancount < 1)
return std::make_pair((unsigned char*)NULL,"No resource records returned");
/* Subtract the length of the header from the length of the packet */
length -= 12;
while ((unsigned int)q < header.qdcount && i < length)
{
if (header.payload[i] > 63)
{
i += 6;
q++;
}
else
{
if (header.payload[i] == 0)
{
q++;
i += 5;
}
else i += header.payload[i] + 1;
}
}
curanswer = 0;
while ((unsigned)curanswer < header.ancount)
{
q = 0;
while (q == 0 && i < length)
{
if (header.payload[i] > 63)
{
i += 2;
q = 1;
}
else
{
if (header.payload[i] == 0)
{
i++;
q = 1;
}
else i += header.payload[i] + 1; /* skip length and label */
}
}
if (length - i < 10)
return std::make_pair((unsigned char*)NULL,"Incorrectly sized DNS reply");
/* XXX: We actually initialise 'rr' here including its ttl field */
DNS::FillResourceRecord(&rr,&header.payload[i]);
i += 10;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver: rr.type is %d and this.type is %d rr.class %d this.class %d", rr.type, this->type, rr.rr_class, this->rr_class);
if (rr.type != this->type)
{
curanswer++;
i += rr.rdlength;
continue;
}
if (rr.rr_class != this->rr_class)
{
curanswer++;
i += rr.rdlength;
continue;
}
break;
}
if ((unsigned int)curanswer == header.ancount)
return std::make_pair((unsigned char*)NULL,"No A, AAAA or PTR type answers (" + ConvToStr(header.ancount) + " answers)");
if (i + rr.rdlength > (unsigned int)length)
return std::make_pair((unsigned char*)NULL,"Resource record larger than stated");
if (rr.rdlength > 1023)
return std::make_pair((unsigned char*)NULL,"Resource record too large");
this->ttl = rr.ttl;
switch (rr.type)
{
/*
* CNAME and PTR are compressed. We need to decompress them.
*/
case DNS_QUERY_CNAME:
case DNS_QUERY_PTR:
o = 0;
q = 0;
while (q == 0 && i < length && o + 256 < 1023)
{
/* DN label found (byte over 63) */
if (header.payload[i] > 63)
{
memcpy(&ptr,&header.payload[i],2);
i = ntohs(ptr);
/* check that highest two bits are set. if not, we've been had */
if (!(i & DN_COMP_BITMASK))
return std::make_pair((unsigned char *) NULL, "DN label decompression header is bogus");
/* mask away the two highest bits. */
i &= ~DN_COMP_BITMASK;
/* and decrease length by 12 bytes. */
i =- 12;
}
else
{
if (header.payload[i] == 0)
{
q = 1;
}
else
{
res[o] = 0;
if (o != 0)
res[o++] = '.';
if (o + header.payload[i] > sizeof(DNSHeader))
return std::make_pair((unsigned char *) NULL, "DN label decompression is impossible -- malformed/hostile packet?");
memcpy(&res[o], &header.payload[i + 1], header.payload[i]);
o += header.payload[i];
i += header.payload[i] + 1;
}
}
}
res[o] = 0;
break;
case DNS_QUERY_AAAA:
if (rr.rdlength != sizeof(struct in6_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 16 bytes for an ipv6 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
case DNS_QUERY_A:
if (rr.rdlength != sizeof(struct in_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 4 bytes for an ipv4 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
default:
return std::make_pair((unsigned char *) NULL, "don't know how to handle undefined type (" + ConvToStr(rr.type) + ") -- rejecting");
break;
}
return std::make_pair(res,"No error");
}
/** Close the master socket */
DNS::~DNS()
{
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
ServerInstance->Timers->DelTimer(this->PruneTimer);
if (cache)
delete cache;
}
CachedQuery* DNS::GetCache(const std::string &source)
{
dnscache::iterator x = cache->find(source.c_str());
if (x != cache->end())
return &(x->second);
else
return NULL;
}
void DNS::DelCache(const std::string &source)
{
cache->erase(source.c_str());
}
void Resolver::TriggerCachedResult()
{
if (CQ)
OnLookupComplete(CQ->data, time_left, true);
}
/** High level abstraction of dns used by application at large */
Resolver::Resolver(const std::string &source, QueryType qt, bool &cached, Module* creator) : Creator(creator), input(source), querytype(qt)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver::Resolver");
cached = false;
CQ = ServerInstance->Res->GetCache(source);
if (CQ)
{
time_left = CQ->CalcTTLRemaining();
if (!time_left)
{
ServerInstance->Res->DelCache(source);
}
else
{
cached = true;
return;
}
}
switch (querytype)
{
case DNS_QUERY_A:
this->myid = ServerInstance->Res->GetIP(source.c_str());
break;
case DNS_QUERY_PTR4:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV4);
break;
case DNS_QUERY_PTR6:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV6);
break;
case DNS_QUERY_AAAA:
this->myid = ServerInstance->Res->GetIP6(source.c_str());
break;
case DNS_QUERY_CNAME:
this->myid = ServerInstance->Res->GetCName(source.c_str());
break;
default:
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request with unknown query type %d", querytype);
this->myid = -1;
break;
}
if (this->myid == -1)
{
throw ModuleException("Resolver: Couldn't get an id to make a request");
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request id %d", this->myid);
}
}
/** Called when an error occurs */
void Resolver::OnError(ResolverError, const std::string&)
{
/* Nothing in here */
}
/** Destroy a resolver */
Resolver::~Resolver()
{
/* Nothing here (yet) either */
}
/** Get the request id associated with this class */
int Resolver::GetId()
{
return this->myid;
}
Module* Resolver::GetCreator()
{
return this->Creator;
}
/** Process a socket read event */
void DNS::HandleEvent(EventType, int)
{
/* Fetch the id and result of the next available packet */
DNSResult res(0,"",0,"");
res.id = 0;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Handle DNS event");
res = this->GetResult();
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Result id %d", res.id);
/* Is there a usable request id? */
if (res.id != -1)
{
/* Its an error reply */
if (res.id & ERROR_MASK)
{
/* Mask off the error bit */
res.id -= ERROR_MASK;
/* Marshall the error to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsBad++;
Classes[res.id]->OnError(RESOLVER_NXDOMAIN, res.result);
delete Classes[res.id];
Classes[res.id] = NULL;
}
return;
}
else
{
/* It is a non-error result, marshall the result to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsGood++;
if (!this->GetCache(res.original.c_str()))
this->cache->insert(std::make_pair(res.original.c_str(), CachedQuery(res.result, res.ttl)));
Classes[res.id]->OnLookupComplete(res.result, res.ttl, false);
delete Classes[res.id];
Classes[res.id] = NULL;
}
}
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDns++;
}
}
/** Add a derived Resolver to the working set */
bool DNS::AddResolverClass(Resolver* r)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"AddResolverClass 0x%08lx", (unsigned long)r);
/* Check the pointers validity and the id's validity */
if ((r) && (r->GetId() > -1))
{
/* Check the slot isnt already occupied -
* This should NEVER happen unless we have
* a severely broken DNS server somewhere
*/
if (!Classes[r->GetId()])
{
/* Set up the pointer to the class */
Classes[r->GetId()] = r;
return true;
}
else
/* Duplicate id */
return false;
}
else
{
/* Pointer or id not valid.
* Free the item and return
*/
if (r)
delete r;
return false;
}
}
void DNS::CleanResolvers(Module* module)
{
for (int i = 0; i < MAX_REQUEST_ID; i++)
{
if (Classes[i])
{
if (Classes[i]->GetCreator() == module)
{
Classes[i]->OnError(RESOLVER_FORCEUNLOAD, "Parent module is unloading");
delete Classes[i];
Classes[i] = NULL;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_3853_0 |
crossvul-cpp_data_bad_4220_1 | /* -*- C++ -*-
* Copyright 2019-2020 LibRaw LLC (info@libraw.org)
*
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
*/
#include "../../internal/libraw_cxx_defs.h"
#ifndef NO_JPEG
struct jpegErrorManager
{
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
static void jpegErrorExit(j_common_ptr cinfo)
{
jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err;
longjmp(myerr->setjmp_buffer, 1);
}
#endif
int LibRaw::unpack_thumb(void)
{
CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY);
CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD);
try
{
if (!libraw_internal_data.internal_data.input)
return LIBRAW_INPUT_CLOSED;
int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7;
int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8;
if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
load_raw == &LibRaw::broadcom_load_raw) // RPi
)
{
return LIBRAW_NO_THUMBNAIL;
}
else if (thumb_load_raw)
{
kodak_thumb_loader();
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else
{
#ifdef USE_X3FTOOLS
if (write_thumb == &LibRaw::x3f_thumb_loader)
{
INT64 tsize = x3f_thumb_size();
if (tsize < 2048 || INT64(ID.toffset) + tsize < 1)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND)
throw LIBRAW_EXCEPTION_IO_EOF;
}
#else
if (0) {}
#endif
else
{
if (INT64(ID.toffset) + INT64(T.tlength) < 1)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (INT64(ID.toffset) + INT64(T.tlength) >
ID.input->size() + THUMB_READ_BEYOND)
throw LIBRAW_EXCEPTION_IO_EOF;
}
ID.input->seek(ID.toffset, SEEK_SET);
if (write_thumb == &LibRaw::jpeg_thumb)
{
if (T.thumb)
free(T.thumb);
T.thumb = (char *)malloc(T.tlength);
merror(T.thumb, "jpeg_thumb()");
ID.input->read(T.thumb, 1, T.tlength);
unsigned char *tthumb = (unsigned char *)T.thumb;
tthumb[0] = 0xff;
tthumb[1] = 0xd8;
#ifdef NO_JPEG
T.tcolors = 3;
#else
{
jpegErrorManager jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jpegErrorExit;
if (setjmp(jerr.setjmp_buffer))
{
err2:
// Error in original JPEG thumb, read it again because
// original bytes 0-1 was damaged above
jpeg_destroy_decompress(&cinfo);
T.tcolors = 3;
T.tformat = LIBRAW_THUMBNAIL_UNKNOWN;
ID.input->seek(ID.toffset, SEEK_SET);
ID.input->read(T.thumb, 1, T.tlength);
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength);
int rc = jpeg_read_header(&cinfo, TRUE);
if (rc != 1)
goto err2;
T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3)
? cinfo.num_components
: 3;
jpeg_destroy_decompress(&cinfo);
}
#endif
T.tformat = LIBRAW_THUMBNAIL_JPEG;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::layer_thumb)
{
int colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7;
if (colors != 1 && colors != 3)
return LIBRAW_UNSUPPORTED_THUMBNAIL;
int tlength = T.twidth * T.theight;
if (T.thumb)
free(T.thumb);
T.thumb = (char *)calloc(colors, tlength);
merror(T.thumb, "layer_thumb()");
unsigned char *tbuf = (unsigned char *)calloc(colors, tlength);
merror(tbuf, "layer_thumb()");
ID.input->read(tbuf, colors, T.tlength);
if (libraw_internal_data.unpacker_data.thumb_misc >> 8 &&
colors == 3) // GRB order
for (int i = 0; i < tlength; i++)
{
T.thumb[i * 3] = tbuf[i + tlength];
T.thumb[i * 3 + 1] = tbuf[i];
T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength];
}
else if (colors == 3) // RGB or 1-channel
for (int i = 0; i < tlength; i++)
{
T.thumb[i * 3] = tbuf[i];
T.thumb[i * 3 + 1] = tbuf[i + tlength];
T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength];
}
else if (colors == 1)
{
free(T.thumb);
T.thumb = (char *)tbuf;
tbuf = 0;
}
if (tbuf)
free(tbuf);
T.tcolors = colors;
T.tlength = colors * tlength;
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::rollei_thumb)
{
int i;
int tlength = T.twidth * T.theight;
if (T.thumb)
free(T.thumb);
T.tcolors = 3;
T.thumb = (char *)calloc(T.tcolors, tlength);
merror(T.thumb, "layer_thumb()");
unsigned short *tbuf = (unsigned short *)calloc(2, tlength);
merror(tbuf, "layer_thumb()");
read_shorts(tbuf, tlength);
for (i = 0; i < tlength; i++)
{
T.thumb[i * 3] = (tbuf[i] << 3) & 0xff;
T.thumb[i * 3 + 1] = (tbuf[i] >> 5 << 2) & 0xff;
T.thumb[i * 3 + 2] = (tbuf[i] >> 11 << 3) & 0xff;
}
free(tbuf);
T.tlength = T.tcolors * tlength;
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::ppm_thumb)
{
if (t_bytesps > 1)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more
// bits
int t_length = T.twidth * T.theight * t_colors;
if (T.tlength &&
(int)T.tlength < t_length) // try to find tiff ifd with needed offset
{
int pifd = find_ifd_by_offset(libraw_internal_data.internal_data.toffset);
if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count &&
tiff_ifd[pifd].strip_byte_counts_count)
{
// We found it, calculate final size
unsigned total_size = 0;
for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++)
total_size += tiff_ifd[pifd].strip_byte_counts[i];
if (total_size != (unsigned)t_length) // recalculate colors
{
if (total_size == T.twidth * T.tlength * 3)
T.tcolors = 3;
else if (total_size == T.twidth * T.tlength)
T.tcolors = 1;
}
T.tlength = total_size;
if (T.thumb)
free(T.thumb);
T.thumb = (char *)malloc(T.tlength);
merror(T.thumb, "ppm_thumb()");
char *dest = T.thumb;
INT64 pos = ID.input->tell();
for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count &&
i < tiff_ifd[pifd].strip_offsets_count;
i++)
{
int remain = T.tlength;
int sz = tiff_ifd[pifd].strip_byte_counts[i];
int off = tiff_ifd[pifd].strip_offsets[i];
if (off >= 0 && off + sz <= ID.input->size() && sz <= remain)
{
ID.input->seek(off, SEEK_SET);
ID.input->read(dest, sz, 1);
remain -= sz;
dest += sz;
}
}
ID.input->seek(pos, SEEK_SET);
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
}
if (!T.tlength)
T.tlength = t_length;
if (T.thumb)
free(T.thumb);
T.thumb = (char *)malloc(T.tlength);
if (!T.tcolors)
T.tcolors = t_colors;
merror(T.thumb, "ppm_thumb()");
ID.input->read(T.thumb, 1, T.tlength);
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::ppm16_thumb)
{
if (t_bytesps > 2)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for
// more bits
int o_bps = (imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_USE_PPM16_THUMBS)
? 2
: 1;
int o_length = T.twidth * T.theight * t_colors * o_bps;
int i_length = T.twidth * T.theight * t_colors * 2;
if (!T.tlength)
T.tlength = o_length;
ushort *t_thumb = (ushort *)calloc(i_length, 1);
ID.input->read(t_thumb, 1, i_length);
if ((libraw_internal_data.unpacker_data.order == 0x4949) ==
(ntohs(0x1234) == 0x1234))
swab((char *)t_thumb, (char *)t_thumb, i_length);
if (T.thumb)
free(T.thumb);
if ((imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_USE_PPM16_THUMBS))
{
T.thumb = (char *)t_thumb;
T.tformat = LIBRAW_THUMBNAIL_BITMAP16;
}
else
{
T.thumb = (char *)malloc(o_length);
merror(T.thumb, "ppm_thumb()");
for (int i = 0; i < o_length; i++)
T.thumb[i] = t_thumb[i] >> 8;
free(t_thumb);
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
}
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
#ifdef USE_X3FTOOLS
else if (write_thumb == &LibRaw::x3f_thumb_loader)
{
x3f_thumb_loader();
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
#endif
else
{
return LIBRAW_UNSUPPORTED_THUMBNAIL;
}
}
// last resort
return LIBRAW_UNSUPPORTED_THUMBNAIL;
}
catch (LibRaw_exceptions err)
{
EXCEPTION_HANDLER(err);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_4220_1 |
crossvul-cpp_data_bad_2181_0 | /**
* Copyright (C) 2010 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/commands/authentication_commands.h"
#include <boost/scoped_ptr.hpp>
#include <string>
#include <vector>
#include "mongo/base/status.h"
#include "mongo/bson/mutable/algorithm.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/client/sasl_client_authenticate.h"
#include "mongo/db/audit.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_manager_global.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/mongo_authentication_session.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/auth/security_key.h"
#include "mongo/db/client_basic.h"
#include "mongo/db/commands.h"
#include "mongo/db/jsobj.h"
#include "mongo/platform/random.h"
#include "mongo/util/concurrency/mutex.h"
#include "mongo/util/md5.hpp"
#include "mongo/util/net/ssl_manager.h"
namespace mongo {
static bool _isCRAuthDisabled;
static bool _isX509AuthDisabled;
static const char _nonceAuthenticationDisabledMessage[] =
"Challenge-response authentication using getnonce and authenticate commands is disabled.";
static const char _x509AuthenticationDisabledMessage[] =
"x.509 authentication is disabled.";
void CmdAuthenticate::disableAuthMechanism(std::string authMechanism) {
if (authMechanism == "MONGODB-CR") {
_isCRAuthDisabled = true;
}
if (authMechanism == "MONGODB-X509") {
_isX509AuthDisabled = true;
}
}
/* authentication
system.users contains
{ user : <username>, pwd : <pwd_digest>, ... }
getnonce sends nonce to client
client then sends { authenticate:1, nonce64:<nonce_str>, user:<username>, key:<key> }
where <key> is md5(<nonce_str><username><pwd_digest_str>) as a string
*/
class CmdGetNonce : public Command {
public:
CmdGetNonce() :
Command("getnonce"),
_randMutex("getnonce"),
_random(SecureRandom::create()) {
}
virtual bool logTheOp() { return false; }
virtual bool slaveOk() const {
return true;
}
void help(stringstream& h) const { h << "internal"; }
virtual bool isWriteCommandForConfigServer() const { return false; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
bool run(const string&, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
nonce64 n = getNextNonce();
stringstream ss;
ss << hex << n;
result.append("nonce", ss.str() );
ClientBasic::getCurrent()->resetAuthenticationSession(
new MongoAuthenticationSession(n));
return true;
}
private:
nonce64 getNextNonce() {
SimpleMutex::scoped_lock lk(_randMutex);
return _random->nextInt64();
}
SimpleMutex _randMutex; // Synchronizes accesses to _random.
boost::scoped_ptr<SecureRandom> _random;
} cmdGetNonce;
void CmdAuthenticate::redactForLogging(mutablebson::Document* cmdObj) {
namespace mmb = mutablebson;
static const int numRedactedFields = 2;
static const char* redactedFields[numRedactedFields] = { "key", "nonce" };
for (int i = 0; i < numRedactedFields; ++i) {
for (mmb::Element element = mmb::findFirstChildNamed(cmdObj->root(), redactedFields[i]);
element.ok();
element = mmb::findElementNamed(element.rightSibling(), redactedFields[i])) {
element.setValueString("xxx");
}
}
}
bool CmdAuthenticate::run(const string& dbname,
BSONObj& cmdObj,
int,
string& errmsg,
BSONObjBuilder& result,
bool fromRepl) {
mutablebson::Document cmdToLog(cmdObj, mutablebson::Document::kInPlaceDisabled);
redactForLogging(&cmdToLog);
log() << " authenticate db: " << dbname << " " << cmdToLog << endl;
UserName user(cmdObj.getStringField("user"), dbname);
if (Command::testCommandsEnabled &&
user.getDB() == "admin" &&
user.getUser() == internalSecurity.user->getName().getUser()) {
// Allows authenticating as the internal user against the admin database. This is to
// support the auth passthrough test framework on mongos (since you can't use the local
// database on a mongos, so you can't auth as the internal user without this).
user = internalSecurity.user->getName();
}
std::string mechanism = cmdObj.getStringField("mechanism");
if (mechanism.empty()) {
mechanism = "MONGODB-CR";
}
Status status = _authenticate(mechanism, user, cmdObj);
audit::logAuthentication(ClientBasic::getCurrent(),
mechanism,
user,
status.code());
if (!status.isOK()) {
log() << "Failed to authenticate " << user << " with mechanism " << mechanism << ": " <<
status;
if (status.code() == ErrorCodes::AuthenticationFailed) {
// Statuses with code AuthenticationFailed may contain messages we do not wish to
// reveal to the user, so we return a status with the message "auth failed".
appendCommandStatus(result,
Status(ErrorCodes::AuthenticationFailed, "auth failed"));
}
else {
appendCommandStatus(result, status);
}
return false;
}
result.append("dbname", user.getDB());
result.append("user", user.getUser());
return true;
}
Status CmdAuthenticate::_authenticate(const std::string& mechanism,
const UserName& user,
const BSONObj& cmdObj) {
if (mechanism == "MONGODB-CR") {
return _authenticateCR(user, cmdObj);
}
#ifdef MONGO_SSL
if (mechanism == "MONGODB-X509") {
return _authenticateX509(user, cmdObj);
}
#endif
return Status(ErrorCodes::BadValue, "Unsupported mechanism: " + mechanism);
}
Status CmdAuthenticate::_authenticateCR(const UserName& user, const BSONObj& cmdObj) {
if (user == internalSecurity.user->getName() &&
serverGlobalParams.clusterAuthMode.load() ==
ServerGlobalParams::ClusterAuthMode_x509) {
return Status(ErrorCodes::AuthenticationFailed,
"Mechanism x509 is required for internal cluster authentication");
}
if (_isCRAuthDisabled) {
// SERVER-8461, MONGODB-CR must be enabled for authenticating the internal user, so that
// cluster members may communicate with each other.
if (user != internalSecurity.user->getName()) {
return Status(ErrorCodes::BadValue, _nonceAuthenticationDisabledMessage);
}
}
string key = cmdObj.getStringField("key");
string received_nonce = cmdObj.getStringField("nonce");
if( user.getUser().empty() || key.empty() || received_nonce.empty() ) {
sleepmillis(10);
return Status(ErrorCodes::ProtocolError,
"field missing/wrong type in received authenticate command");
}
stringstream digestBuilder;
{
ClientBasic *client = ClientBasic::getCurrent();
boost::scoped_ptr<AuthenticationSession> session;
client->swapAuthenticationSession(session);
if (!session || session->getType() != AuthenticationSession::SESSION_TYPE_MONGO) {
sleepmillis(30);
return Status(ErrorCodes::ProtocolError, "No pending nonce");
}
else {
nonce64 nonce = static_cast<MongoAuthenticationSession*>(session.get())->getNonce();
digestBuilder << hex << nonce;
if (digestBuilder.str() != received_nonce) {
sleepmillis(30);
return Status(ErrorCodes::AuthenticationFailed, "Received wrong nonce.");
}
}
}
User* userObj;
Status status = getGlobalAuthorizationManager()->acquireUser(user, &userObj);
if (!status.isOK()) {
// Failure to find the privilege document indicates no-such-user, a fact that we do not
// wish to reveal to the client. So, we return AuthenticationFailed rather than passing
// through the returned status.
return Status(ErrorCodes::AuthenticationFailed, status.toString());
}
string pwd = userObj->getCredentials().password;
getGlobalAuthorizationManager()->releaseUser(userObj);
md5digest d;
{
digestBuilder << user.getUser() << pwd;
string done = digestBuilder.str();
md5_state_t st;
md5_init(&st);
md5_append(&st, (const md5_byte_t *) done.c_str(), done.size());
md5_finish(&st, d);
}
string computed = digestToString( d );
if ( key != computed ) {
return Status(ErrorCodes::AuthenticationFailed, "key mismatch");
}
AuthorizationSession* authorizationSession =
ClientBasic::getCurrent()->getAuthorizationSession();
status = authorizationSession->addAndAuthorizeUser(user);
if (!status.isOK()) {
return status;
}
return Status::OK();
}
#ifdef MONGO_SSL
Status CmdAuthenticate::_authenticateX509(const UserName& user, const BSONObj& cmdObj) {
if (!getSSLManager()) {
return Status(ErrorCodes::ProtocolError,
"SSL support is required for the MONGODB-X509 mechanism.");
}
if(user.getDB() != "$external") {
return Status(ErrorCodes::ProtocolError,
"X.509 authentication must always use the $external database.");
}
ClientBasic *client = ClientBasic::getCurrent();
AuthorizationSession* authorizationSession = client->getAuthorizationSession();
std::string subjectName = client->port()->getX509SubjectName();
if (user.getUser() != subjectName) {
return Status(ErrorCodes::AuthenticationFailed,
"There is no x.509 client certificate matching the user.");
}
else {
std::string srvSubjectName = getSSLManager()->getServerSubjectName();
std::string srvClusterId = srvSubjectName.substr(srvSubjectName.find(",OU="));
std::string peerClusterId = subjectName.substr(subjectName.find(",OU="));
fassert(17002, !srvClusterId.empty() && srvClusterId != srvSubjectName);
// Handle internal cluster member auth, only applies to server-server connections
int clusterAuthMode = serverGlobalParams.clusterAuthMode.load();
if (srvClusterId == peerClusterId) {
if (clusterAuthMode == ServerGlobalParams::ClusterAuthMode_undefined ||
clusterAuthMode == ServerGlobalParams::ClusterAuthMode_keyFile) {
return Status(ErrorCodes::AuthenticationFailed, "The provided certificate "
"can only be used for cluster authentication, not client "
"authentication. The current configuration does not allow "
"x.509 cluster authentication, check the --clusterAuthMode flag");
}
authorizationSession->grantInternalAuthorization();
}
// Handle normal client authentication, only applies to client-server connections
else {
if (_isX509AuthDisabled) {
return Status(ErrorCodes::BadValue,
_x509AuthenticationDisabledMessage);
}
Status status = authorizationSession->addAndAuthorizeUser(user);
if (!status.isOK()) {
return status;
}
}
return Status::OK();
}
}
#endif
CmdAuthenticate cmdAuthenticate;
class CmdLogout : public Command {
public:
virtual bool logTheOp() {
return false;
}
virtual bool slaveOk() const {
return true;
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
void help(stringstream& h) const { h << "de-authenticate"; }
virtual bool isWriteCommandForConfigServer() const { return false; }
CmdLogout() : Command("logout") {}
bool run(const string& dbname,
BSONObj& cmdObj,
int options,
string& errmsg,
BSONObjBuilder& result,
bool fromRepl) {
AuthorizationSession* authSession =
ClientBasic::getCurrent()->getAuthorizationSession();
authSession->logoutDatabase(dbname);
return true;
}
} cmdLogout;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_2181_0 |
crossvul-cpp_data_good_1692_0 | /*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "lazy_entry.hpp"
#include <cstring>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
namespace
{
const int lazy_entry_grow_factor = 150; // percent
const int lazy_entry_dict_init = 5;
const int lazy_entry_list_init = 5;
}
namespace libtorrent
{
namespace
{
int fail(int* error_pos
, std::vector<lazy_entry*>& stack
, char const* start
, char const* orig_start)
{
while (!stack.empty()) {
lazy_entry* top = stack.back();
if (top->type() == lazy_entry::dict_t || top->type() == lazy_entry::list_t)
{
top->pop();
break;
}
stack.pop_back();
}
if (error_pos) *error_pos = start - orig_start;
return -1;
}
}
#define TORRENT_FAIL_BDECODE(code) do { ec = make_error_code(code); return fail(error_pos, stack, start, orig_start); } while (false)
namespace { bool numeric(char c) { return c >= '0' && c <= '9'; } }
// fills in 'val' with what the string between start and the
// first occurance of the delimiter is interpreted as an int.
// return the pointer to the delimiter, or 0 if there is a
// parse error. val should be initialized to zero
char const* parse_int(char const* start, char const* end, char delimiter
, boost::int64_t& val, bdecode_errors::error_code_enum& ec)
{
while (start < end && *start != delimiter)
{
if (!numeric(*start))
{
ec = bdecode_errors::expected_string;
return start;
}
if (val > INT64_MAX / 10)
{
ec = bdecode_errors::overflow;
return start;
}
val *= 10;
int digit = *start - '0';
if (val > INT64_MAX - digit)
{
ec = bdecode_errors::overflow;
return start;
}
val += digit;
++start;
}
if (*start != delimiter)
ec = bdecode_errors::expected_colon;
return start;
}
char const* find_char(char const* start, char const* end, char delimiter)
{
while (start < end && *start != delimiter) ++start;
return start;
}
// return 0 = success
int lazy_bdecode(char const* start, char const* end, lazy_entry& ret
, error_code& ec, int* error_pos, int depth_limit, int item_limit)
{
char const* const orig_start = start;
ret.clear();
if (start == end) return 0;
std::vector<lazy_entry*> stack;
stack.push_back(&ret);
while (start <= end)
{
if (stack.empty()) break; // done!
lazy_entry* top = stack.back();
if (int(stack.size()) > depth_limit) TORRENT_FAIL_BDECODE(bdecode_errors::depth_exceeded);
if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
char t = *start;
++start;
if (start >= end && t != 'e') TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
switch (top->type())
{
case lazy_entry::dict_t:
{
if (t == 'e')
{
top->set_end(start);
stack.pop_back();
continue;
}
if (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_string);
boost::int64_t len = t - '0';
bdecode_errors::error_code_enum e = bdecode_errors::no_error;
start = parse_int(start, end, ':', len, e);
if (e)
TORRENT_FAIL_BDECODE(e);
// remaining buffer size excluding ':'
const ptrdiff_t buff_size = end - start - 1;
if (len > buff_size)
TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
if (len < 0)
TORRENT_FAIL_BDECODE(bdecode_errors::overflow);
++start;
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
lazy_entry* ent = top->dict_append(start);
if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);
start += len;
if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
stack.push_back(ent);
t = *start;
++start;
break;
}
case lazy_entry::list_t:
{
if (t == 'e')
{
top->set_end(start);
stack.pop_back();
continue;
}
lazy_entry* ent = top->list_append();
if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);
stack.push_back(ent);
break;
}
default: break;
}
--item_limit;
if (item_limit <= 0) TORRENT_FAIL_BDECODE(bdecode_errors::limit_exceeded);
top = stack.back();
switch (t)
{
case 'd':
top->construct_dict(start - 1);
continue;
case 'l':
top->construct_list(start - 1);
continue;
case 'i':
{
char const* int_start = start;
start = find_char(start, end, 'e');
top->construct_int(int_start, start - int_start);
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
TORRENT_ASSERT(*start == 'e');
++start;
stack.pop_back();
continue;
}
default:
{
if (!numeric(t))
TORRENT_FAIL_BDECODE(bdecode_errors::expected_value);
boost::int64_t len = t - '0';
bdecode_errors::error_code_enum e = bdecode_errors::no_error;
start = parse_int(start, end, ':', len, e);
if (e)
TORRENT_FAIL_BDECODE(e);
// remaining buffer size excluding ':'
const ptrdiff_t buff_size = end - start - 1;
if (len > buff_size)
TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
if (len < 0)
TORRENT_FAIL_BDECODE(bdecode_errors::overflow);
++start;
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
top->construct_string(start, int(len));
stack.pop_back();
start += len;
continue;
}
}
return 0;
}
return 0;
}
boost::int64_t lazy_entry::int_value() const
{
TORRENT_ASSERT(m_type == int_t);
boost::int64_t val = 0;
bool negative = false;
if (*m_data.start == '-') negative = true;
bdecode_errors::error_code_enum ec = bdecode_errors::no_error;
parse_int(m_data.start + negative
, m_data.start + m_size, 'e', val, ec);
if (ec) return 0;
if (negative) val = -val;
return val;
}
lazy_entry* lazy_entry::dict_append(char const* name)
{
TORRENT_ASSERT(m_type == dict_t);
TORRENT_ASSERT(m_size <= m_capacity);
if (m_capacity == 0)
{
int capacity = lazy_entry_dict_init;
m_data.dict = new (std::nothrow) lazy_dict_entry[capacity];
if (m_data.dict == 0) return 0;
m_capacity = capacity;
}
else if (m_size == m_capacity)
{
int capacity = m_capacity * lazy_entry_grow_factor / 100;
lazy_dict_entry* tmp = new (std::nothrow) lazy_dict_entry[capacity];
if (tmp == 0) return 0;
std::memcpy(tmp, m_data.dict, sizeof(lazy_dict_entry) * m_size);
for (int i = 0; i < int(m_size); ++i) m_data.dict[i].val.release();
delete[] m_data.dict;
m_data.dict = tmp;
m_capacity = capacity;
}
TORRENT_ASSERT(m_size < m_capacity);
lazy_dict_entry& ret = m_data.dict[m_size++];
ret.name = name;
return &ret.val;
}
void lazy_entry::pop()
{
if (m_size > 0) --m_size;
}
namespace
{
// the number of decimal digits needed
// to represent the given value
int num_digits(int val)
{
int ret = 1;
while (val >= 10)
{
++ret;
val /= 10;
}
return ret;
}
}
void lazy_entry::construct_string(char const* start, int length)
{
TORRENT_ASSERT(m_type == none_t);
m_type = string_t;
m_data.start = start;
m_size = length;
m_begin = start - 1 - num_digits(length);
m_len = start - m_begin + length;
}
namespace
{
// str1 is null-terminated
// str2 is not, str2 is len2 chars
bool string_equal(char const* str1, char const* str2, int len2)
{
while (len2 > 0)
{
if (*str1 != *str2) return false;
if (*str1 == 0) return false;
++str1;
++str2;
--len2;
}
return *str1 == 0;
}
}
std::pair<std::string, lazy_entry const*> lazy_entry::dict_at(int i) const
{
TORRENT_ASSERT(m_type == dict_t);
TORRENT_ASSERT(i < int(m_size));
lazy_dict_entry const& e = m_data.dict[i];
return std::make_pair(std::string(e.name, e.val.m_begin - e.name), &e.val);
}
std::string lazy_entry::dict_find_string_value(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::string_t) return std::string();
return e->string_value();
}
pascal_string lazy_entry::dict_find_pstr(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::string_t) return pascal_string(0, 0);
return e->string_pstr();
}
lazy_entry const* lazy_entry::dict_find_string(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::string_t) return 0;
return e;
}
lazy_entry const* lazy_entry::dict_find_int(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::int_t) return 0;
return e;
}
boost::int64_t lazy_entry::dict_find_int_value(char const* name, boost::int64_t default_val) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::int_t) return default_val;
return e->int_value();
}
lazy_entry const* lazy_entry::dict_find_dict(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::dict_t) return 0;
return e;
}
lazy_entry const* lazy_entry::dict_find_dict(std::string const& name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::dict_t) return 0;
return e;
}
lazy_entry const* lazy_entry::dict_find_list(char const* name) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::list_t) return 0;
return e;
}
lazy_entry* lazy_entry::dict_find(char const* name)
{
TORRENT_ASSERT(m_type == dict_t);
for (int i = 0; i < int(m_size); ++i)
{
lazy_dict_entry& e = m_data.dict[i];
if (string_equal(name, e.name, e.val.m_begin - e.name))
return &e.val;
}
return 0;
}
lazy_entry* lazy_entry::dict_find(std::string const& name)
{
TORRENT_ASSERT(m_type == dict_t);
for (int i = 0; i < int(m_size); ++i)
{
lazy_dict_entry& e = m_data.dict[i];
if (name.size() != e.val.m_begin - e.name) continue;
if (std::equal(name.begin(), name.end(), e.name))
return &e.val;
}
return 0;
}
lazy_entry* lazy_entry::list_append()
{
TORRENT_ASSERT(m_type == list_t);
TORRENT_ASSERT(m_size <= m_capacity);
if (m_capacity == 0)
{
int capacity = lazy_entry_list_init;
m_data.list = new (std::nothrow) lazy_entry[capacity];
if (m_data.list == 0) return 0;
m_capacity = capacity;
}
else if (m_size == m_capacity)
{
int capacity = m_capacity * lazy_entry_grow_factor / 100;
lazy_entry* tmp = new (std::nothrow) lazy_entry[capacity];
if (tmp == 0) return 0;
std::memcpy(tmp, m_data.list, sizeof(lazy_entry) * m_size);
for (int i = 0; i < int(m_size); ++i) m_data.list[i].release();
delete[] m_data.list;
m_data.list = tmp;
m_capacity = capacity;
}
TORRENT_ASSERT(m_size < m_capacity);
return m_data.list + (m_size++);
}
std::string lazy_entry::list_string_value_at(int i) const
{
lazy_entry const* e = list_at(i);
if (e == 0 || e->type() != lazy_entry::string_t) return std::string();
return e->string_value();
}
pascal_string lazy_entry::list_pstr_at(int i) const
{
lazy_entry const* e = list_at(i);
if (e == 0 || e->type() != lazy_entry::string_t) return pascal_string(0, 0);
return e->string_pstr();
}
boost::int64_t lazy_entry::list_int_value_at(int i, boost::int64_t default_val) const
{
lazy_entry const* e = list_at(i);
if (e == 0 || e->type() != lazy_entry::int_t) return default_val;
return e->int_value();
}
void lazy_entry::clear()
{
switch (m_type)
{
case list_t: delete[] m_data.list; break;
case dict_t: delete[] m_data.dict; break;
default: break;
}
m_data.start = 0;
m_size = 0;
m_capacity = 0;
m_type = none_t;
}
std::pair<char const*, int> lazy_entry::data_section() const
{
typedef std::pair<char const*, int> return_t;
return return_t(m_begin, m_len);
}
int line_longer_than(lazy_entry const& e, int limit)
{
int line_len = 0;
switch (e.type())
{
case lazy_entry::list_t:
line_len += 4;
if (line_len > limit) return -1;
for (int i = 0; i < e.list_size(); ++i)
{
int ret = line_longer_than(*e.list_at(i), limit - line_len);
if (ret == -1) return -1;
line_len += ret + 2;
}
break;
case lazy_entry::dict_t:
line_len += 4;
if (line_len > limit) return -1;
for (int i = 0; i < e.dict_size(); ++i)
{
line_len += 4 + e.dict_at(i).first.size();
if (line_len > limit) return -1;
int ret = line_longer_than(*e.dict_at(i).second, limit - line_len);
if (ret == -1) return -1;
line_len += ret + 1;
}
break;
case lazy_entry::string_t:
line_len += 3 + e.string_length();
break;
case lazy_entry::int_t:
{
boost::int64_t val = e.int_value();
while (val > 0)
{
++line_len;
val /= 10;
}
line_len += 2;
}
break;
case lazy_entry::none_t:
line_len += 4;
break;
}
if (line_len > limit) return -1;
return line_len;
}
std::string print_entry(lazy_entry const& e, bool single_line, int indent)
{
char indent_str[200];
memset(indent_str, ' ', 200);
indent_str[0] = ',';
indent_str[1] = '\n';
indent_str[199] = 0;
if (indent < 197 && indent >= 0) indent_str[indent+2] = 0;
std::string ret;
switch (e.type())
{
case lazy_entry::none_t: return "none";
case lazy_entry::int_t:
{
char str[100];
snprintf(str, sizeof(str), "%" PRId64, e.int_value());
return str;
}
case lazy_entry::string_t:
{
bool printable = true;
char const* str = e.string_ptr();
for (int i = 0; i < e.string_length(); ++i)
{
char c = str[i];
if (c >= 32 && c < 127) continue;
printable = false;
break;
}
ret += "'";
if (printable)
{
if (single_line && e.string_length() > 30)
{
ret.append(e.string_ptr(), 14);
ret += "...";
ret.append(e.string_ptr() + e.string_length()-14, 14);
}
else
ret.append(e.string_ptr(), e.string_length());
ret += "'";
return ret;
}
if (single_line && e.string_length() > 20)
{
for (int i = 0; i < 9; ++i)
{
char tmp[5];
snprintf(tmp, sizeof(tmp), "%02x", (unsigned char)str[i]);
ret += tmp;
}
ret += "...";
for (int i = e.string_length() - 9
, len(e.string_length()); i < len; ++i)
{
char tmp[5];
snprintf(tmp, sizeof(tmp), "%02x", (unsigned char)str[i]);
ret += tmp;
}
}
else
{
for (int i = 0; i < e.string_length(); ++i)
{
char tmp[5];
snprintf(tmp, sizeof(tmp), "%02x", (unsigned char)str[i]);
ret += tmp;
}
}
ret += "'";
return ret;
}
case lazy_entry::list_t:
{
ret += '[';
bool one_liner = line_longer_than(e, 200) != -1 || single_line;
if (!one_liner) ret += indent_str + 1;
for (int i = 0; i < e.list_size(); ++i)
{
if (i == 0 && one_liner) ret += " ";
ret += print_entry(*e.list_at(i), single_line, indent + 2);
if (i < e.list_size() - 1) ret += (one_liner?", ":indent_str);
else ret += (one_liner?" ":indent_str+1);
}
ret += "]";
return ret;
}
case lazy_entry::dict_t:
{
ret += "{";
bool one_liner = line_longer_than(e, 200) != -1 || single_line;
if (!one_liner) ret += indent_str+1;
for (int i = 0; i < e.dict_size(); ++i)
{
if (i == 0 && one_liner) ret += " ";
std::pair<std::string, lazy_entry const*> ent = e.dict_at(i);
ret += "'";
ret += ent.first;
ret += "': ";
ret += print_entry(*ent.second, single_line, indent + 2);
if (i < e.dict_size() - 1) ret += (one_liner?", ":indent_str);
else ret += (one_liner?" ":indent_str+1);
}
ret += "}";
return ret;
}
}
return ret;
}
struct bdecode_error_category : boost::system::error_category
{
virtual const char* name() const BOOST_SYSTEM_NOEXCEPT;
virtual std::string message(int ev) const BOOST_SYSTEM_NOEXCEPT;
virtual boost::system::error_condition default_error_condition(int ev) const BOOST_SYSTEM_NOEXCEPT
{ return boost::system::error_condition(ev, *this); }
};
const char* bdecode_error_category::name() const BOOST_SYSTEM_NOEXCEPT
{
return "bdecode error";
}
std::string bdecode_error_category::message(int ev) const BOOST_SYSTEM_NOEXCEPT
{
static char const* msgs[] =
{
"no error",
"expected string in bencoded string",
"expected colon in bencoded string",
"unexpected end of file in bencoded string",
"expected value (list, dict, int or string) in bencoded string",
"bencoded nesting depth exceeded",
"bencoded item count limit exceeded",
"integer overflow",
};
if (ev < 0 || ev >= int(sizeof(msgs)/sizeof(msgs[0])))
return "Unknown error";
return msgs[ev];
}
boost::system::error_category& get_bdecode_category()
{
static bdecode_error_category bdecode_category;
return bdecode_category;
}
namespace bdecode_errors
{
boost::system::error_code make_error_code(error_code_enum e)
{
return boost::system::error_code(e, get_bdecode_category());
}
}
};
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1692_0 |
crossvul-cpp_data_good_1442_1 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <znc/FileUtils.h>
#include <znc/Config.h>
#include <znc/IRCSock.h>
#include <znc/Server.h>
#include <znc/Chan.h>
#include <znc/Query.h>
#include <znc/Message.h>
#include <algorithm>
#include <memory>
using std::vector;
using std::set;
class CIRCNetworkPingTimer : public CCron {
public:
CIRCNetworkPingTimer(CIRCNetwork* pNetwork)
: CCron(), m_pNetwork(pNetwork) {
SetName("CIRCNetworkPingTimer::" +
m_pNetwork->GetUser()->GetUserName() + "::" +
m_pNetwork->GetName());
Start(m_pNetwork->GetUser()->GetPingSlack());
}
~CIRCNetworkPingTimer() override {}
CIRCNetworkPingTimer(const CIRCNetworkPingTimer&) = delete;
CIRCNetworkPingTimer& operator=(const CIRCNetworkPingTimer&) = delete;
protected:
void RunJob() override {
CIRCSock* pIRCSock = m_pNetwork->GetIRCSock();
auto uFrequency = m_pNetwork->GetUser()->GetPingFrequency();
if (pIRCSock &&
pIRCSock->GetTimeSinceLastDataTransaction() >= uFrequency) {
pIRCSock->PutIRC("PING :ZNC");
}
const vector<CClient*>& vClients = m_pNetwork->GetClients();
for (CClient* pClient : vClients) {
if (pClient->GetTimeSinceLastDataTransaction() >= uFrequency) {
pClient->PutClient("PING :ZNC");
}
}
// Restart timer for the case if the period had changed. Usually this is
// noop
Start(m_pNetwork->GetUser()->GetPingSlack());
}
private:
CIRCNetwork* m_pNetwork;
};
class CIRCNetworkJoinTimer : public CCron {
constexpr static int JOIN_FREQUENCY = 30 /* seconds */;
public:
CIRCNetworkJoinTimer(CIRCNetwork* pNetwork)
: CCron(), m_bDelayed(false), m_pNetwork(pNetwork) {
SetName("CIRCNetworkJoinTimer::" +
m_pNetwork->GetUser()->GetUserName() + "::" +
m_pNetwork->GetName());
Start(JOIN_FREQUENCY);
}
~CIRCNetworkJoinTimer() override {}
CIRCNetworkJoinTimer(const CIRCNetworkJoinTimer&) = delete;
CIRCNetworkJoinTimer& operator=(const CIRCNetworkJoinTimer&) = delete;
void Delay(unsigned short int uDelay) {
m_bDelayed = true;
Start(uDelay);
}
protected:
void RunJob() override {
if (m_bDelayed) {
m_bDelayed = false;
Start(JOIN_FREQUENCY);
}
if (m_pNetwork->IsIRCConnected()) {
m_pNetwork->JoinChans();
}
}
private:
bool m_bDelayed;
CIRCNetwork* m_pNetwork;
};
bool CIRCNetwork::IsValidNetwork(const CString& sNetwork) {
// ^[-\w]+$
if (sNetwork.empty()) {
return false;
}
const char* p = sNetwork.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
CIRCNetwork::CIRCNetwork(CUser* pUser, const CString& sName)
: m_sName(sName),
m_pUser(nullptr),
m_sNick(""),
m_sAltNick(""),
m_sIdent(""),
m_sRealName(""),
m_sBindHost(""),
m_sEncoding(""),
m_sQuitMsg(""),
m_ssTrustedFingerprints(),
m_pModules(new CModules),
m_vClients(),
m_pIRCSock(nullptr),
m_vChans(),
m_vQueries(),
m_sChanPrefixes(""),
m_bIRCConnectEnabled(true),
m_bTrustAllCerts(false),
m_bTrustPKI(true),
m_sIRCServer(""),
m_vServers(),
m_uServerIdx(0),
m_IRCNick(),
m_bIRCAway(false),
m_fFloodRate(2),
m_uFloodBurst(9),
m_RawBuffer(),
m_MotdBuffer(),
m_NoticeBuffer(),
m_pPingTimer(nullptr),
m_pJoinTimer(nullptr),
m_uJoinDelay(0),
m_uBytesRead(0),
m_uBytesWritten(0) {
SetUser(pUser);
// This should be more than enough raws, especially since we are buffering
// the MOTD separately
m_RawBuffer.SetLineCount(100, true);
// This should be more than enough motd lines
m_MotdBuffer.SetLineCount(200, true);
m_NoticeBuffer.SetLineCount(250, true);
m_pPingTimer = new CIRCNetworkPingTimer(this);
CZNC::Get().GetManager().AddCron(m_pPingTimer);
m_pJoinTimer = new CIRCNetworkJoinTimer(this);
CZNC::Get().GetManager().AddCron(m_pJoinTimer);
SetIRCConnectEnabled(true);
}
CIRCNetwork::CIRCNetwork(CUser* pUser, const CIRCNetwork& Network)
: CIRCNetwork(pUser, "") {
Clone(Network);
}
void CIRCNetwork::Clone(const CIRCNetwork& Network, bool bCloneName) {
if (bCloneName) {
m_sName = Network.GetName();
}
m_fFloodRate = Network.GetFloodRate();
m_uFloodBurst = Network.GetFloodBurst();
m_uJoinDelay = Network.GetJoinDelay();
SetNick(Network.GetNick());
SetAltNick(Network.GetAltNick());
SetIdent(Network.GetIdent());
SetRealName(Network.GetRealName());
SetBindHost(Network.GetBindHost());
SetEncoding(Network.GetEncoding());
SetQuitMsg(Network.GetQuitMsg());
m_ssTrustedFingerprints = Network.m_ssTrustedFingerprints;
// Servers
const vector<CServer*>& vServers = Network.GetServers();
CString sServer;
CServer* pCurServ = GetCurrentServer();
if (pCurServ) {
sServer = pCurServ->GetName();
}
DelServers();
for (CServer* pServer : vServers) {
AddServer(pServer->GetName(), pServer->GetPort(), pServer->GetPass(),
pServer->IsSSL());
}
m_uServerIdx = 0;
for (size_t a = 0; a < m_vServers.size(); a++) {
if (sServer.Equals(m_vServers[a]->GetName())) {
m_uServerIdx = a + 1;
break;
}
}
if (m_uServerIdx == 0) {
m_uServerIdx = m_vServers.size();
CIRCSock* pSock = GetIRCSock();
if (pSock) {
PutStatus(
t_s("Jumping servers because this server is no longer in the "
"list"));
pSock->Quit();
}
}
// !Servers
// Chans
const vector<CChan*>& vChans = Network.GetChans();
for (CChan* pNewChan : vChans) {
CChan* pChan = FindChan(pNewChan->GetName());
if (pChan) {
pChan->SetInConfig(pNewChan->InConfig());
} else {
AddChan(pNewChan->GetName(), pNewChan->InConfig());
}
}
for (CChan* pChan : m_vChans) {
CChan* pNewChan = Network.FindChan(pChan->GetName());
if (!pNewChan) {
pChan->SetInConfig(false);
} else {
pChan->Clone(*pNewChan);
}
}
// !Chans
// Modules
set<CString> ssUnloadMods;
CModules& vCurMods = GetModules();
const CModules& vNewMods = Network.GetModules();
for (CModule* pNewMod : vNewMods) {
CString sModRet;
CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName());
if (!pCurMod) {
vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
CModInfo::NetworkModule, m_pUser, this,
sModRet);
} else if (pNewMod->GetArgs() != pCurMod->GetArgs()) {
vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
m_pUser, this, sModRet);
}
}
for (CModule* pCurMod : vCurMods) {
CModule* pNewMod = vNewMods.FindModule(pCurMod->GetModName());
if (!pNewMod) {
ssUnloadMods.insert(pCurMod->GetModName());
}
}
for (const CString& sMod : ssUnloadMods) {
vCurMods.UnloadModule(sMod);
}
// !Modules
SetIRCConnectEnabled(Network.GetIRCConnectEnabled());
}
CIRCNetwork::~CIRCNetwork() {
if (m_pIRCSock) {
CZNC::Get().GetManager().DelSockByAddr(m_pIRCSock);
m_pIRCSock = nullptr;
}
// Delete clients
while (!m_vClients.empty()) {
CZNC::Get().GetManager().DelSockByAddr(m_vClients[0]);
}
m_vClients.clear();
// Delete servers
DelServers();
// Delete modules (this unloads all modules)
delete m_pModules;
m_pModules = nullptr;
// Delete Channels
for (CChan* pChan : m_vChans) {
delete pChan;
}
m_vChans.clear();
// Delete Queries
for (CQuery* pQuery : m_vQueries) {
delete pQuery;
}
m_vQueries.clear();
CUser* pUser = GetUser();
SetUser(nullptr);
// Make sure we are not in the connection queue
CZNC::Get().GetConnectionQueue().remove(this);
CZNC::Get().GetManager().DelCronByAddr(m_pPingTimer);
CZNC::Get().GetManager().DelCronByAddr(m_pJoinTimer);
if (pUser) {
pUser->AddBytesRead(m_uBytesRead);
pUser->AddBytesWritten(m_uBytesWritten);
} else {
CZNC::Get().AddBytesRead(m_uBytesRead);
CZNC::Get().AddBytesWritten(m_uBytesWritten);
}
}
void CIRCNetwork::DelServers() {
for (CServer* pServer : m_vServers) {
delete pServer;
}
m_vServers.clear();
}
CString CIRCNetwork::GetNetworkPath() const {
CString sNetworkPath = m_pUser->GetUserPath() + "/networks/" + m_sName;
if (!CFile::Exists(sNetworkPath)) {
CDir::MakeDir(sNetworkPath);
}
return sNetworkPath;
}
template <class T>
struct TOption {
const char* name;
void (CIRCNetwork::*pSetter)(T);
};
bool CIRCNetwork::ParseConfig(CConfig* pConfig, CString& sError,
bool bUpgrade) {
VCString vsList;
if (!bUpgrade) {
TOption<const CString&> StringOptions[] = {
{"nick", &CIRCNetwork::SetNick},
{"altnick", &CIRCNetwork::SetAltNick},
{"ident", &CIRCNetwork::SetIdent},
{"realname", &CIRCNetwork::SetRealName},
{"bindhost", &CIRCNetwork::SetBindHost},
{"encoding", &CIRCNetwork::SetEncoding},
{"quitmsg", &CIRCNetwork::SetQuitMsg},
};
TOption<bool> BoolOptions[] = {
{"ircconnectenabled", &CIRCNetwork::SetIRCConnectEnabled},
{"trustallcerts", &CIRCNetwork::SetTrustAllCerts},
{"trustpki", &CIRCNetwork::SetTrustPKI},
};
TOption<double> DoubleOptions[] = {
{"floodrate", &CIRCNetwork::SetFloodRate},
};
TOption<short unsigned int> SUIntOptions[] = {
{"floodburst", &CIRCNetwork::SetFloodBurst},
{"joindelay", &CIRCNetwork::SetJoinDelay},
};
for (const auto& Option : StringOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue);
}
for (const auto& Option : BoolOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue.ToBool());
}
for (const auto& Option : DoubleOptions) {
double fValue;
if (pConfig->FindDoubleEntry(Option.name, fValue))
(this->*Option.pSetter)(fValue);
}
for (const auto& Option : SUIntOptions) {
unsigned short value;
if (pConfig->FindUShortEntry(Option.name, value))
(this->*Option.pSetter)(value);
}
pConfig->FindStringVector("loadmodule", vsList);
for (const CString& sValue : vsList) {
CString sModName = sValue.Token(0);
CString sNotice = "Loading network module [" + sModName + "]";
// XXX Legacy crap, added in ZNC 0.203, modified in 0.207
// Note that 0.203 == 0.207
if (sModName == "away") {
sNotice =
"NOTICE: [away] was renamed, loading [awaystore] instead";
sModName = "awaystore";
}
// XXX Legacy crap, added in ZNC 0.207
if (sModName == "autoaway") {
sNotice =
"NOTICE: [autoaway] was renamed, loading [awaystore] "
"instead";
sModName = "awaystore";
}
// XXX Legacy crap, added in 1.1; fakeonline module was dropped in
// 1.0 and returned in 1.1
if (sModName == "fakeonline") {
sNotice =
"NOTICE: [fakeonline] was renamed, loading "
"[modules_online] instead";
sModName = "modules_online";
}
CString sModRet;
CString sArgs = sValue.Token(1, true);
bool bModRet = LoadModule(sModName, sArgs, sNotice, sModRet);
if (!bModRet) {
// XXX The awaynick module was retired in 1.6 (still available
// as external module)
if (sModName == "awaynick") {
// load simple_away instead, unless it's already on the list
bool bFound = false;
for (const CString& sLoadMod : vsList) {
if (sLoadMod.Token(0).Equals("simple_away")) {
bFound = true;
}
}
if (!bFound) {
sNotice =
"NOTICE: awaynick was retired, loading network "
"module [simple_away] instead; if you still need "
"awaynick, install it as an external module";
sModName = "simple_away";
// not a fatal error if simple_away is not available
LoadModule(sModName, sArgs, sNotice, sModRet);
}
} else {
sError = sModRet;
return false;
}
}
}
}
pConfig->FindStringVector("server", vsList);
for (const CString& sServer : vsList) {
CUtils::PrintAction("Adding server [" + sServer + "]");
CUtils::PrintStatus(AddServer(sServer));
}
pConfig->FindStringVector("trustedserverfingerprint", vsList);
for (const CString& sFP : vsList) {
AddTrustedFingerprint(sFP);
}
pConfig->FindStringVector("chan", vsList);
for (const CString& sChan : vsList) {
AddChan(sChan, true);
}
CConfig::SubConfig subConf;
CConfig::SubConfig::const_iterator subIt;
pConfig->FindSubConfig("chan", subConf);
for (subIt = subConf.begin(); subIt != subConf.end(); ++subIt) {
const CString& sChanName = subIt->first;
CConfig* pSubConf = subIt->second.m_pSubConfig;
CChan* pChan = new CChan(sChanName, this, true, pSubConf);
if (!pSubConf->empty()) {
sError = "Unhandled lines in config for User [" +
m_pUser->GetUserName() + "], Network [" + GetName() +
"], Channel [" + sChanName + "]!";
CUtils::PrintError(sError);
CZNC::DumpConfig(pSubConf);
delete pChan;
return false;
}
// Save the channel name, because AddChan
// deletes the CChannel*, if adding fails
sError = pChan->GetName();
if (!AddChan(pChan)) {
sError = "Channel [" + sError + "] defined more than once";
CUtils::PrintError(sError);
return false;
}
sError.clear();
}
return true;
}
CConfig CIRCNetwork::ToConfig() const {
CConfig config;
if (!m_sNick.empty()) {
config.AddKeyValuePair("Nick", m_sNick);
}
if (!m_sAltNick.empty()) {
config.AddKeyValuePair("AltNick", m_sAltNick);
}
if (!m_sIdent.empty()) {
config.AddKeyValuePair("Ident", m_sIdent);
}
if (!m_sRealName.empty()) {
config.AddKeyValuePair("RealName", m_sRealName);
}
if (!m_sBindHost.empty()) {
config.AddKeyValuePair("BindHost", m_sBindHost);
}
config.AddKeyValuePair("IRCConnectEnabled",
CString(GetIRCConnectEnabled()));
config.AddKeyValuePair("TrustAllCerts", CString(GetTrustAllCerts()));
config.AddKeyValuePair("TrustPKI", CString(GetTrustPKI()));
config.AddKeyValuePair("FloodRate", CString(GetFloodRate()));
config.AddKeyValuePair("FloodBurst", CString(GetFloodBurst()));
config.AddKeyValuePair("JoinDelay", CString(GetJoinDelay()));
config.AddKeyValuePair("Encoding", m_sEncoding);
if (!m_sQuitMsg.empty()) {
config.AddKeyValuePair("QuitMsg", m_sQuitMsg);
}
// Modules
const CModules& Mods = GetModules();
if (!Mods.empty()) {
for (CModule* pMod : Mods) {
CString sArgs = pMod->GetArgs();
if (!sArgs.empty()) {
sArgs = " " + sArgs;
}
config.AddKeyValuePair("LoadModule", pMod->GetModName() + sArgs);
}
}
// Servers
for (CServer* pServer : m_vServers) {
config.AddKeyValuePair("Server", pServer->GetString());
}
for (const CString& sFP : m_ssTrustedFingerprints) {
config.AddKeyValuePair("TrustedServerFingerprint", sFP);
}
// Chans
for (CChan* pChan : m_vChans) {
if (pChan->InConfig()) {
config.AddSubConfig("Chan", pChan->GetName(), pChan->ToConfig());
}
}
return config;
}
void CIRCNetwork::BounceAllClients() {
for (CClient* pClient : m_vClients) {
pClient->BouncedOff();
}
m_vClients.clear();
}
bool CIRCNetwork::IsUserOnline() const {
for (CClient* pClient : m_vClients) {
if (!pClient->IsAway()) {
return true;
}
}
return false;
}
void CIRCNetwork::ClientConnected(CClient* pClient) {
if (!m_pUser->MultiClients()) {
BounceAllClients();
}
m_vClients.push_back(pClient);
size_t uIdx, uSize;
if (m_pIRCSock) {
pClient->NotifyServerDependentCaps(m_pIRCSock->GetAcceptedCaps());
}
pClient->SetPlaybackActive(true);
if (m_RawBuffer.IsEmpty()) {
pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() +
" :" + t_s("Welcome to ZNC"));
} else {
const CString& sClientNick = pClient->GetNick(false);
MCString msParams;
msParams["target"] = sClientNick;
uSize = m_RawBuffer.Size();
for (uIdx = 0; uIdx < uSize; uIdx++) {
pClient->PutClient(m_RawBuffer.GetLine(uIdx, *pClient, msParams));
}
const CNick& Nick = GetIRCNick();
if (sClientNick != Nick.GetNick()) { // case-sensitive match
pClient->PutClient(":" + sClientNick + "!" + Nick.GetIdent() + "@" +
Nick.GetHost() + " NICK :" + Nick.GetNick());
pClient->SetNick(Nick.GetNick());
}
}
MCString msParams;
msParams["target"] = GetIRCNick().GetNick();
// Send the cached MOTD
uSize = m_MotdBuffer.Size();
if (uSize > 0) {
for (uIdx = 0; uIdx < uSize; uIdx++) {
pClient->PutClient(m_MotdBuffer.GetLine(uIdx, *pClient, msParams));
}
}
if (GetIRCSock() != nullptr) {
CString sUserMode("");
const set<char>& scUserModes = GetIRCSock()->GetUserModes();
for (char cMode : scUserModes) {
sUserMode += cMode;
}
if (!sUserMode.empty()) {
pClient->PutClient(":" + GetIRCNick().GetNickMask() + " MODE " +
GetIRCNick().GetNick() + " :+" + sUserMode);
}
}
if (m_bIRCAway) {
// If they want to know their away reason they'll have to whois
// themselves. At least we can tell them their away status...
pClient->PutClient(":irc.znc.in 306 " + GetIRCNick().GetNick() +
" :You have been marked as being away");
}
const vector<CChan*>& vChans = GetChans();
for (CChan* pChan : vChans) {
if ((pChan->IsOn()) && (!pChan->IsDetached())) {
pChan->AttachUser(pClient);
}
}
bool bClearQuery = m_pUser->AutoClearQueryBuffer();
for (CQuery* pQuery : m_vQueries) {
pQuery->SendBuffer(pClient);
if (bClearQuery) {
delete pQuery;
}
}
if (bClearQuery) {
m_vQueries.clear();
}
uSize = m_NoticeBuffer.Size();
for (uIdx = 0; uIdx < uSize; uIdx++) {
const CBufLine& BufLine = m_NoticeBuffer.GetBufLine(uIdx);
CMessage Message(BufLine.GetLine(*pClient, msParams));
Message.SetNetwork(this);
Message.SetClient(pClient);
Message.SetTime(BufLine.GetTime());
Message.SetTags(BufLine.GetTags());
bool bContinue = false;
NETWORKMODULECALL(OnPrivBufferPlayMessage(Message), m_pUser, this,
nullptr, &bContinue);
if (bContinue) continue;
pClient->PutClient(Message);
}
m_NoticeBuffer.Clear();
pClient->SetPlaybackActive(false);
// Tell them why they won't connect
if (!GetIRCConnectEnabled())
pClient->PutStatus(
t_s("You are currently disconnected from IRC. Use 'connect' to "
"reconnect."));
}
void CIRCNetwork::ClientDisconnected(CClient* pClient) {
auto it = std::find(m_vClients.begin(), m_vClients.end(), pClient);
if (it != m_vClients.end()) {
m_vClients.erase(it);
}
}
CUser* CIRCNetwork::GetUser() const { return m_pUser; }
const CString& CIRCNetwork::GetName() const { return m_sName; }
std::vector<CClient*> CIRCNetwork::FindClients(
const CString& sIdentifier) const {
std::vector<CClient*> vClients;
for (CClient* pClient : m_vClients) {
if (pClient->GetIdentifier().Equals(sIdentifier)) {
vClients.push_back(pClient);
}
}
return vClients;
}
void CIRCNetwork::SetUser(CUser* pUser) {
for (CClient* pClient : m_vClients) {
pClient->PutStatus(
t_s("This network is being deleted or moved to another user."));
pClient->SetNetwork(nullptr);
}
m_vClients.clear();
if (m_pUser) {
m_pUser->RemoveNetwork(this);
}
m_pUser = pUser;
if (m_pUser) {
m_pUser->AddNetwork(this);
}
}
bool CIRCNetwork::SetName(const CString& sName) {
if (IsValidNetwork(sName)) {
m_sName = sName;
return true;
}
return false;
}
bool CIRCNetwork::PutUser(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutClient(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CIRCNetwork::PutUser(const CMessage& Message, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutClient(Message);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CIRCNetwork::PutStatus(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutStatus(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CIRCNetwork::PutModule(const CString& sModule, const CString& sLine,
CClient* pClient, CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutModule(sModule, sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
// Channels
const vector<CChan*>& CIRCNetwork::GetChans() const { return m_vChans; }
CChan* CIRCNetwork::FindChan(CString sName) const {
if (GetIRCSock()) {
// See
// https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.16
sName.TrimLeft(GetIRCSock()->GetISupport("STATUSMSG", ""));
}
for (CChan* pChan : m_vChans) {
if (sName.Equals(pChan->GetName())) {
return pChan;
}
}
return nullptr;
}
std::vector<CChan*> CIRCNetwork::FindChans(const CString& sWild) const {
std::vector<CChan*> vChans;
vChans.reserve(m_vChans.size());
const CString sLower = sWild.AsLower();
for (CChan* pChan : m_vChans) {
if (pChan->GetName().AsLower().WildCmp(sLower)) vChans.push_back(pChan);
}
return vChans;
}
bool CIRCNetwork::AddChan(CChan* pChan) {
if (!pChan) {
return false;
}
for (CChan* pEachChan : m_vChans) {
if (pEachChan->GetName().Equals(pChan->GetName())) {
delete pChan;
return false;
}
}
m_vChans.push_back(pChan);
return true;
}
bool CIRCNetwork::AddChan(const CString& sName, bool bInConfig) {
if (sName.empty() || FindChan(sName)) {
return false;
}
CChan* pChan = new CChan(sName, this, bInConfig);
m_vChans.push_back(pChan);
return true;
}
bool CIRCNetwork::DelChan(const CString& sName) {
for (vector<CChan*>::iterator a = m_vChans.begin(); a != m_vChans.end();
++a) {
if (sName.Equals((*a)->GetName())) {
delete *a;
m_vChans.erase(a);
return true;
}
}
return false;
}
void CIRCNetwork::JoinChans() {
// Avoid divsion by zero, it's bad!
if (m_vChans.empty()) return;
// We start at a random offset into the channel list so that if your
// first 3 channels are invite-only and you got MaxJoins == 3, ZNC will
// still be able to join the rest of your channels.
unsigned int start = rand() % m_vChans.size();
unsigned int uJoins = m_pUser->MaxJoins();
set<CChan*> sChans;
for (unsigned int a = 0; a < m_vChans.size(); a++) {
unsigned int idx = (start + a) % m_vChans.size();
CChan* pChan = m_vChans[idx];
if (!pChan->IsOn() && !pChan->IsDisabled()) {
if (!JoinChan(pChan)) continue;
sChans.insert(pChan);
// Limit the number of joins
if (uJoins != 0 && --uJoins == 0) {
// Reset the timer.
m_pJoinTimer->Reset();
break;
}
}
}
while (!sChans.empty()) JoinChans(sChans);
}
void CIRCNetwork::JoinChans(set<CChan*>& sChans) {
CString sKeys, sJoin;
bool bHaveKey = false;
size_t uiJoinLength = strlen("JOIN ");
while (!sChans.empty()) {
set<CChan*>::iterator it = sChans.begin();
const CString& sName = (*it)->GetName();
const CString& sKey = (*it)->GetKey();
size_t len = sName.length() + sKey.length();
len += 2; // two comma
if (!sKeys.empty() && uiJoinLength + len >= 512) break;
if (!sJoin.empty()) {
sJoin += ",";
sKeys += ",";
}
uiJoinLength += len;
sJoin += sName;
if (!sKey.empty()) {
sKeys += sKey;
bHaveKey = true;
}
sChans.erase(it);
}
if (bHaveKey)
PutIRC("JOIN " + sJoin + " " + sKeys);
else
PutIRC("JOIN " + sJoin);
}
bool CIRCNetwork::JoinChan(CChan* pChan) {
bool bReturn = false;
NETWORKMODULECALL(OnJoining(*pChan), m_pUser, this, nullptr, &bReturn);
if (bReturn) return false;
if (m_pUser->JoinTries() != 0 &&
pChan->GetJoinTries() >= m_pUser->JoinTries()) {
PutStatus(t_f("The channel {1} could not be joined, disabling it.")(
pChan->GetName()));
pChan->Disable();
} else {
pChan->IncJoinTries();
bool bFailed = false;
NETWORKMODULECALL(OnTimerAutoJoin(*pChan), m_pUser, this, nullptr,
&bFailed);
if (bFailed) return false;
return true;
}
return false;
}
bool CIRCNetwork::IsChan(const CString& sChan) const {
if (sChan.empty()) return false; // There is no way this is a chan
if (GetChanPrefixes().empty())
return true; // We can't know, so we allow everything
// Thanks to the above if (empty), we can do sChan[0]
return GetChanPrefixes().find(sChan[0]) != CString::npos;
}
// Queries
const vector<CQuery*>& CIRCNetwork::GetQueries() const { return m_vQueries; }
CQuery* CIRCNetwork::FindQuery(const CString& sName) const {
for (CQuery* pQuery : m_vQueries) {
if (sName.Equals(pQuery->GetName())) {
return pQuery;
}
}
return nullptr;
}
std::vector<CQuery*> CIRCNetwork::FindQueries(const CString& sWild) const {
std::vector<CQuery*> vQueries;
vQueries.reserve(m_vQueries.size());
const CString sLower = sWild.AsLower();
for (CQuery* pQuery : m_vQueries) {
if (pQuery->GetName().AsLower().WildCmp(sLower))
vQueries.push_back(pQuery);
}
return vQueries;
}
CQuery* CIRCNetwork::AddQuery(const CString& sName) {
if (sName.empty()) {
return nullptr;
}
CQuery* pQuery = FindQuery(sName);
if (!pQuery) {
pQuery = new CQuery(sName, this);
m_vQueries.push_back(pQuery);
if (m_pUser->MaxQueryBuffers() > 0) {
while (m_vQueries.size() > m_pUser->MaxQueryBuffers()) {
delete *m_vQueries.begin();
m_vQueries.erase(m_vQueries.begin());
}
}
}
return pQuery;
}
bool CIRCNetwork::DelQuery(const CString& sName) {
for (vector<CQuery*>::iterator a = m_vQueries.begin();
a != m_vQueries.end(); ++a) {
if (sName.Equals((*a)->GetName())) {
delete *a;
m_vQueries.erase(a);
return true;
}
}
return false;
}
// Server list
const vector<CServer*>& CIRCNetwork::GetServers() const { return m_vServers; }
CServer* CIRCNetwork::FindServer(const CString& sName) const {
for (CServer* pServer : m_vServers) {
if (sName.Equals(pServer->GetName())) {
return pServer;
}
}
return nullptr;
}
bool CIRCNetwork::DelServer(const CString& sName, unsigned short uPort,
const CString& sPass) {
if (sName.empty()) {
return false;
}
unsigned int a = 0;
bool bSawCurrentServer = false;
CServer* pCurServer = GetCurrentServer();
for (vector<CServer*>::iterator it = m_vServers.begin();
it != m_vServers.end(); ++it, a++) {
CServer* pServer = *it;
if (pServer == pCurServer) bSawCurrentServer = true;
if (!pServer->GetName().Equals(sName)) continue;
if (uPort != 0 && pServer->GetPort() != uPort) continue;
if (!sPass.empty() && pServer->GetPass() != sPass) continue;
m_vServers.erase(it);
if (pServer == pCurServer) {
CIRCSock* pIRCSock = GetIRCSock();
// Make sure we don't skip the next server in the list!
if (m_uServerIdx) {
m_uServerIdx--;
}
if (pIRCSock) {
pIRCSock->Quit();
PutStatus(t_s("Your current server was removed, jumping..."));
}
} else if (!bSawCurrentServer) {
// Our current server comes after the server which we
// are removing. This means that it now got a different
// index in m_vServers!
m_uServerIdx--;
}
delete pServer;
return true;
}
return false;
}
bool CIRCNetwork::AddServer(const CString& sName) {
if (sName.empty()) {
return false;
}
bool bSSL = false;
CString sLine = sName;
sLine.Trim();
CString sHost = sLine.Token(0);
CString sPort = sLine.Token(1);
if (sPort.TrimPrefix("+")) {
bSSL = true;
}
unsigned short uPort = sPort.ToUShort();
CString sPass = sLine.Token(2, true);
return AddServer(sHost, uPort, sPass, bSSL);
}
bool CIRCNetwork::AddServer(const CString& sName, unsigned short uPort,
const CString& sPass, bool bSSL) {
#ifndef HAVE_LIBSSL
if (bSSL) {
return false;
}
#endif
if (sName.empty()) {
return false;
}
if (!uPort) {
uPort = 6667;
}
// Check if server is already added
for (CServer* pServer : m_vServers) {
if (!sName.Equals(pServer->GetName())) continue;
if (uPort != pServer->GetPort()) continue;
if (sPass != pServer->GetPass()) continue;
if (bSSL != pServer->IsSSL()) continue;
// Server is already added
return false;
}
CServer* pServer = new CServer(sName, uPort, sPass, bSSL);
m_vServers.push_back(pServer);
CheckIRCConnect();
return true;
}
CServer* CIRCNetwork::GetNextServer(bool bAdvance) {
if (m_vServers.empty()) {
return nullptr;
}
if (m_uServerIdx >= m_vServers.size()) {
m_uServerIdx = 0;
}
if (bAdvance) {
return m_vServers[m_uServerIdx++];
} else {
return m_vServers[m_uServerIdx];
}
}
CServer* CIRCNetwork::GetCurrentServer() const {
size_t uIdx = (m_uServerIdx) ? m_uServerIdx - 1 : 0;
if (uIdx >= m_vServers.size()) {
return nullptr;
}
return m_vServers[uIdx];
}
void CIRCNetwork::SetIRCServer(const CString& s) { m_sIRCServer = s; }
bool CIRCNetwork::SetNextServer(const CServer* pServer) {
for (unsigned int a = 0; a < m_vServers.size(); a++) {
if (m_vServers[a] == pServer) {
m_uServerIdx = a;
return true;
}
}
return false;
}
bool CIRCNetwork::IsLastServer() const {
return (m_uServerIdx >= m_vServers.size());
}
const CString& CIRCNetwork::GetIRCServer() const { return m_sIRCServer; }
const CNick& CIRCNetwork::GetIRCNick() const { return m_IRCNick; }
void CIRCNetwork::SetIRCNick(const CNick& n) {
m_IRCNick = n;
for (CClient* pClient : m_vClients) {
pClient->SetNick(n.GetNick());
}
}
CString CIRCNetwork::GetCurNick() const {
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
return pIRCSock->GetNick();
}
if (!m_vClients.empty()) {
return m_vClients[0]->GetNick();
}
return "";
}
bool CIRCNetwork::Connect() {
if (!GetIRCConnectEnabled() || m_pIRCSock || !HasServers()) return false;
CServer* pServer = GetNextServer();
if (!pServer) return false;
if (CZNC::Get().GetServerThrottle(pServer->GetName())) {
// Can't connect right now, schedule retry later
CZNC::Get().AddNetworkToQueue(this);
return false;
}
CZNC::Get().AddServerThrottle(pServer->GetName());
bool bSSL = pServer->IsSSL();
#ifndef HAVE_LIBSSL
if (bSSL) {
PutStatus(
t_f("Cannot connect to {1}, because ZNC is not compiled with SSL "
"support.")(pServer->GetString(false)));
CZNC::Get().AddNetworkToQueue(this);
return false;
}
#endif
CIRCSock* pIRCSock = new CIRCSock(this);
pIRCSock->SetPass(pServer->GetPass());
pIRCSock->SetSSLTrustedPeerFingerprints(m_ssTrustedFingerprints);
pIRCSock->SetTrustAllCerts(GetTrustAllCerts());
pIRCSock->SetTrustPKI(GetTrustPKI());
DEBUG("Connecting user/network [" << m_pUser->GetUserName() << "/"
<< m_sName << "]");
bool bAbort = false;
NETWORKMODULECALL(OnIRCConnecting(pIRCSock), m_pUser, this, nullptr,
&bAbort);
if (bAbort) {
DEBUG("Some module aborted the connection attempt");
PutStatus(t_s("Some module aborted the connection attempt"));
delete pIRCSock;
CZNC::Get().AddNetworkToQueue(this);
return false;
}
CString sSockName = "IRC::" + m_pUser->GetUserName() + "::" + m_sName;
CZNC::Get().GetManager().Connect(pServer->GetName(), pServer->GetPort(),
sSockName, 120, bSSL, GetBindHost(),
pIRCSock);
return true;
}
bool CIRCNetwork::IsIRCConnected() const {
const CIRCSock* pSock = GetIRCSock();
return (pSock && pSock->IsAuthed());
}
void CIRCNetwork::SetIRCSocket(CIRCSock* pIRCSock) { m_pIRCSock = pIRCSock; }
void CIRCNetwork::IRCConnected() {
const SCString& ssCaps = m_pIRCSock->GetAcceptedCaps();
for (CClient* pClient : m_vClients) {
pClient->NotifyServerDependentCaps(ssCaps);
}
if (m_uJoinDelay > 0) {
m_pJoinTimer->Delay(m_uJoinDelay);
} else {
JoinChans();
}
}
void CIRCNetwork::IRCDisconnected() {
for (CClient* pClient : m_vClients) {
pClient->ClearServerDependentCaps();
}
m_pIRCSock = nullptr;
SetIRCServer("");
m_bIRCAway = false;
// Get the reconnect going
CheckIRCConnect();
}
void CIRCNetwork::SetIRCConnectEnabled(bool b) {
m_bIRCConnectEnabled = b;
if (m_bIRCConnectEnabled) {
CheckIRCConnect();
} else if (GetIRCSock()) {
if (GetIRCSock()->IsConnected()) {
GetIRCSock()->Quit();
} else {
GetIRCSock()->Close();
}
}
}
void CIRCNetwork::CheckIRCConnect() {
// Do we want to connect?
if (GetIRCConnectEnabled() && GetIRCSock() == nullptr)
CZNC::Get().AddNetworkToQueue(this);
}
bool CIRCNetwork::PutIRC(const CString& sLine) {
CIRCSock* pIRCSock = GetIRCSock();
if (!pIRCSock) {
return false;
}
pIRCSock->PutIRC(sLine);
return true;
}
bool CIRCNetwork::PutIRC(const CMessage& Message) {
CIRCSock* pIRCSock = GetIRCSock();
if (!pIRCSock) {
return false;
}
pIRCSock->PutIRC(Message);
return true;
}
void CIRCNetwork::ClearQueryBuffer() {
std::for_each(m_vQueries.begin(), m_vQueries.end(),
std::default_delete<CQuery>());
m_vQueries.clear();
}
const CString& CIRCNetwork::GetNick(const bool bAllowDefault) const {
if (m_sNick.empty()) {
return m_pUser->GetNick(bAllowDefault);
}
return m_sNick;
}
const CString& CIRCNetwork::GetAltNick(const bool bAllowDefault) const {
if (m_sAltNick.empty()) {
return m_pUser->GetAltNick(bAllowDefault);
}
return m_sAltNick;
}
const CString& CIRCNetwork::GetIdent(const bool bAllowDefault) const {
if (m_sIdent.empty()) {
return m_pUser->GetIdent(bAllowDefault);
}
return m_sIdent;
}
CString CIRCNetwork::GetRealName() const {
if (m_sRealName.empty()) {
return m_pUser->GetRealName();
}
return m_sRealName;
}
const CString& CIRCNetwork::GetBindHost() const {
if (m_sBindHost.empty()) {
return m_pUser->GetBindHost();
}
return m_sBindHost;
}
const CString& CIRCNetwork::GetEncoding() const { return m_sEncoding; }
CString CIRCNetwork::GetQuitMsg() const {
if (m_sQuitMsg.empty()) {
return m_pUser->GetQuitMsg();
}
return m_sQuitMsg;
}
void CIRCNetwork::SetNick(const CString& s) {
if (m_pUser->GetNick().Equals(s)) {
m_sNick = "";
} else {
m_sNick = s;
}
}
void CIRCNetwork::SetAltNick(const CString& s) {
if (m_pUser->GetAltNick().Equals(s)) {
m_sAltNick = "";
} else {
m_sAltNick = s;
}
}
void CIRCNetwork::SetIdent(const CString& s) {
if (m_pUser->GetIdent().Equals(s)) {
m_sIdent = "";
} else {
m_sIdent = s;
}
}
void CIRCNetwork::SetRealName(const CString& s) {
if (m_pUser->GetRealName().Equals(s)) {
m_sRealName = "";
} else {
m_sRealName = s;
}
}
void CIRCNetwork::SetBindHost(const CString& s) {
if (m_pUser->GetBindHost().Equals(s)) {
m_sBindHost = "";
} else {
m_sBindHost = s;
}
}
void CIRCNetwork::SetEncoding(const CString& s) {
m_sEncoding = CZNC::Get().FixupEncoding(s);
if (GetIRCSock()) {
GetIRCSock()->SetEncoding(m_sEncoding);
}
}
void CIRCNetwork::SetQuitMsg(const CString& s) {
if (m_pUser->GetQuitMsg().Equals(s)) {
m_sQuitMsg = "";
} else {
m_sQuitMsg = s;
}
}
CString CIRCNetwork::ExpandString(const CString& sStr) const {
CString sRet;
return ExpandString(sStr, sRet);
}
CString& CIRCNetwork::ExpandString(const CString& sStr, CString& sRet) const {
sRet = sStr;
sRet.Replace("%altnick%", GetAltNick());
sRet.Replace("%bindhost%", GetBindHost());
sRet.Replace("%defnick%", GetNick());
sRet.Replace("%ident%", GetIdent());
sRet.Replace("%network%", GetName());
sRet.Replace("%nick%", GetCurNick());
sRet.Replace("%realname%", GetRealName());
return m_pUser->ExpandString(sRet, sRet);
}
bool CIRCNetwork::LoadModule(const CString& sModName, const CString& sArgs,
const CString& sNotice, CString& sError) {
CUtils::PrintAction(sNotice);
CString sModRet;
bool bModRet = GetModules().LoadModule(
sModName, sArgs, CModInfo::NetworkModule, GetUser(), this, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
sError = sModRet;
}
return bModRet;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1442_1 |
crossvul-cpp_data_bad_660_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_660_0 |
crossvul-cpp_data_bad_1580_0 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: ParaNdis-Common.c
*
* This file contains NDIS driver procedures, common for NDIS5 and NDIS6
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
static VOID ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext);
static __inline pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue);
// TODO: remove when the problem solved
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue);
//#define ROUNDSIZE(sz) ((sz + 15) & ~15)
#define MAX_VLAN_ID 4095
#define ABSTRACT_PATHES_TAG 'APVR'
/**********************************************************
Validates MAC address
Valid MAC address is not broadcast, not multicast, not empty
if bLocal is set, it must be LOCAL
if not, is must be non-local or local
Parameters:
PUCHAR pcMacAddress - MAC address to validate
BOOLEAN bLocal - TRUE, if we validate locally administered address
Return value:
TRUE if valid
***********************************************************/
BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal)
{
BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE;
bBroadcast = ETH_IS_BROADCAST(pcMacAddress);
bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress);
bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress);
bEmpty = ETH_IS_EMPTY(pcMacAddress);
return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA);
}
typedef struct _tagConfigurationEntry
{
const char *Name;
ULONG ulValue;
ULONG ulMinimal;
ULONG ulMaximal;
}tConfigurationEntry;
typedef struct _tagConfigurationEntries
{
tConfigurationEntry PrioritySupport;
tConfigurationEntry ConnectRate;
tConfigurationEntry isLogEnabled;
tConfigurationEntry debugLevel;
tConfigurationEntry TxCapacity;
tConfigurationEntry RxCapacity;
tConfigurationEntry LogStatistics;
tConfigurationEntry OffloadTxChecksum;
tConfigurationEntry OffloadTxLSO;
tConfigurationEntry OffloadRxCS;
tConfigurationEntry stdIpcsV4;
tConfigurationEntry stdTcpcsV4;
tConfigurationEntry stdTcpcsV6;
tConfigurationEntry stdUdpcsV4;
tConfigurationEntry stdUdpcsV6;
tConfigurationEntry stdLsoV1;
tConfigurationEntry stdLsoV2ip4;
tConfigurationEntry stdLsoV2ip6;
tConfigurationEntry PriorityVlanTagging;
tConfigurationEntry VlanId;
tConfigurationEntry PublishIndices;
tConfigurationEntry MTU;
tConfigurationEntry NumberOfHandledRXPackersInDPC;
#if PARANDIS_SUPPORT_RSS
tConfigurationEntry RSSOffloadSupported;
tConfigurationEntry NumRSSQueues;
#endif
#if PARANDIS_SUPPORT_RSC
tConfigurationEntry RSCIPv4Supported;
tConfigurationEntry RSCIPv6Supported;
#endif
}tConfigurationEntries;
static const tConfigurationEntries defaultConfiguration =
{
{ "Priority", 0, 0, 1 },
{ "ConnectRate", 100,10,10000 },
{ "DoLog", 1, 0, 1 },
{ "DebugLevel", 2, 0, 8 },
{ "TxCapacity", 1024, 16, 1024 },
{ "RxCapacity", 256, 32, 1024 },
{ "LogStatistics", 0, 0, 10000},
{ "Offload.TxChecksum", 0, 0, 31},
{ "Offload.TxLSO", 0, 0, 2},
{ "Offload.RxCS", 0, 0, 31},
{ "*IPChecksumOffloadIPv4", 3, 0, 3 },
{ "*TCPChecksumOffloadIPv4",3, 0, 3 },
{ "*TCPChecksumOffloadIPv6",3, 0, 3 },
{ "*UDPChecksumOffloadIPv4",3, 0, 3 },
{ "*UDPChecksumOffloadIPv6",3, 0, 3 },
{ "*LsoV1IPv4", 1, 0, 1 },
{ "*LsoV2IPv4", 1, 0, 1 },
{ "*LsoV2IPv6", 1, 0, 1 },
{ "*PriorityVLANTag", 3, 0, 3},
{ "VlanId", 0, 0, MAX_VLAN_ID},
{ "PublishIndices", 1, 0, 1},
{ "MTU", 1500, 576, 65500},
{ "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000},
#if PARANDIS_SUPPORT_RSS
{ "*RSS", 1, 0, 1},
{ "*NumRssQueues", 8, 1, PARANDIS_RSS_MAX_RECEIVE_QUEUES},
#endif
#if PARANDIS_SUPPORT_RSC
{ "*RscIPv4", 1, 0, 1},
{ "*RscIPv6", 1, 0, 1},
#endif
};
static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext)
{
VirtIODeviceReset(pContext->IODevice);
DPrintf(0, ("[%s] Done\n", __FUNCTION__));
/* reset all the features in the device */
pContext->ulCurrentVlansFilterSet = 0;
}
/**********************************************************
Gets integer value for specifies in pEntry->Name name
Parameters:
NDIS_HANDLE cfg previously open configuration
tConfigurationEntry *pEntry - Entry to fill value in
***********************************************************/
static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry)
{
NDIS_STATUS status;
const char *statusName;
NDIS_STRING name = {0};
PNDIS_CONFIGURATION_PARAMETER pParam = NULL;
NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger;
NdisInitializeString(&name, (PUCHAR)pEntry->Name);
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadConfiguration(
&status,
&pParam,
cfg,
&name,
ParameterType);
if (status == NDIS_STATUS_SUCCESS)
{
ULONG ulValue = pParam->ParameterData.IntegerData;
if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal)
{
pEntry->ulValue = ulValue;
statusName = "value";
}
else
{
statusName = "out of range";
}
}
else
{
statusName = "nothing";
}
#pragma warning(pop)
DPrintf(2, ("[%s] %s read for %s - 0x%x\n",
__FUNCTION__,
statusName,
pEntry->Name,
pEntry->ulValue));
if (name.Buffer) NdisFreeString(name);
}
static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT4Lso)
{
DPrintf(0, ("[%s] Warning: %s", procname, reason));
pContext->Offload.flagsValue &= ~osbT4Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT6Lso)
{
DPrintf(0, ("[%s] Warning: %s\n", procname, reason));
pContext->Offload.flagsValue &= ~osbT6Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
/**********************************************************
Loads NIC parameters from adapter registry key
Parameters:
context
PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host
***********************************************************/
static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR pNewMACAddress)
{
NDIS_HANDLE cfg;
tConfigurationEntries *pConfiguration = (tConfigurationEntries *) ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries));
if (pConfiguration)
{
*pConfiguration = defaultConfiguration;
cfg = ParaNdis_OpenNICConfiguration(pContext);
if (cfg)
{
GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled);
GetConfigurationEntry(cfg, &pConfiguration->debugLevel);
GetConfigurationEntry(cfg, &pConfiguration->ConnectRate);
GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport);
GetConfigurationEntry(cfg, &pConfiguration->TxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->RxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->LogStatistics);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO);
GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS);
GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6);
GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging);
GetConfigurationEntry(cfg, &pConfiguration->VlanId);
GetConfigurationEntry(cfg, &pConfiguration->PublishIndices);
GetConfigurationEntry(cfg, &pConfiguration->MTU);
GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC);
#if PARANDIS_SUPPORT_RSS
GetConfigurationEntry(cfg, &pConfiguration->RSSOffloadSupported);
GetConfigurationEntry(cfg, &pConfiguration->NumRSSQueues);
#endif
#if PARANDIS_SUPPORT_RSC
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv4Supported);
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv6Supported);
#endif
bDebugPrint = pConfiguration->isLogEnabled.ulValue;
virtioDebugLevel = pConfiguration->debugLevel.ulValue;
pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue;
pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue;
pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue;
pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue;
pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0;
pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue;
pContext->ulFormalLinkSpeed *= 1000000;
pContext->Offload.flagsValue = 0;
// TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum;
if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp;
if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions;
// RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum;
/* full packet size that can be configured as GSO for VIRTIO is short */
/* NDIS test fails sometimes fails on segments 50-60K */
pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE;
pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue;
pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue;
pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue;
pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue;
pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue;
pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff;
pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue;
#if PARANDIS_SUPPORT_RSS
pContext->bRSSOffloadSupported = pConfiguration->RSSOffloadSupported.ulValue ? TRUE : FALSE;
pContext->RSSMaxQueuesNumber = (CCHAR) pConfiguration->NumRSSQueues.ulValue;
#endif
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4SupportedSW = (UCHAR)pConfiguration->RSCIPv4Supported.ulValue;
pContext->RSC.bIPv6SupportedSW = (UCHAR)pConfiguration->RSCIPv6Supported.ulValue;
#endif
if (!pContext->bDoSupportPriority)
pContext->ulPriorityVlanSetting = 0;
// if Vlan not supported
if (!IsVlanSupported(pContext)) {
pContext->VlanId = 0;
}
{
NDIS_STATUS status;
PVOID p;
UINT len = 0;
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadNetworkAddress(&status, &p, &len, cfg);
if (status == NDIS_STATUS_SUCCESS && len == ETH_LENGTH_OF_ADDRESS)
{
NdisMoveMemory(pNewMACAddress, p, len);
}
else if (len && len != ETH_LENGTH_OF_ADDRESS)
{
DPrintf(0, ("[%s] MAC address has wrong length of %d\n", __FUNCTION__, len));
}
else
{
DPrintf(4, ("[%s] Nothing read for MAC, error %X\n", __FUNCTION__, status));
}
#pragma warning(pop)
}
NdisCloseConfiguration(cfg);
}
NdisFreeMemory(pConfiguration, 0, 0);
}
}
void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from)
{
if (!pDest) pDest = &pContext->Offload.flags;
if (!from) from = &pContext->Offload.flagsValue;
pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum);
pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum);
pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum);
pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum);
pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum);
pDest->fTxLso = !!(*from & osbT4Lso);
pDest->fTxLsoIP = !!(*from & osbT4LsoIp);
pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp);
pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum);
pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum);
pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum);
pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum);
pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum);
pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum);
pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum);
pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum);
pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum);
pDest->fTxLsov6 = !!(*from & osbT6Lso);
pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt);
pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions);
pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum);
pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum);
pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum);
pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum);
}
/**********************************************************
Enumerates adapter resources and fills the structure holding them
Verifies that IO assigned and has correct size
Verifies that interrupt assigned
Parameters:
PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS
tAdapterResources *pResources - structure to fill
Return value:
TRUE if everything is OK
***********************************************************/
static BOOLEAN GetAdapterResources(PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources)
{
UINT i;
NdisZeroMemory(pResources, sizeof(*pResources));
for (i = 0; i < RList->Count; ++i)
{
ULONG type = RList->PartialDescriptors[i].Type;
if (type == CmResourceTypePort)
{
PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start;
ULONG len = RList->PartialDescriptors[i].u.Port.Length;
DPrintf(0, ("Found IO ports at %08lX(%d)\n", Start.LowPart, len));
pResources->ulIOAddress = Start.LowPart;
pResources->IOLength = len;
}
else if (type == CmResourceTypeInterrupt)
{
pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector;
pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level;
pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity;
pResources->InterruptFlags = RList->PartialDescriptors[i].Flags;
DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X\n",
pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags));
}
}
return pResources->ulIOAddress && pResources->Vector;
}
static void DumpVirtIOFeatures(PPARANDIS_ADAPTER pContext)
{
static const struct { ULONG bitmask; PCHAR Name; } Features[] =
{
{VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" },
{VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" },
{VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" },
{VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" },
{VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"},
{VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"},
{VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"},
{VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"},
{VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"},
{VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"},
{VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"},
{VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"},
{VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"},
{VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"},
{VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"},
{VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"},
{VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"},
{VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"},
{VIRTIO_NET_F_CTRL_MAC_ADDR, "VIRTIO_NET_F_CTRL_MAC_ADDR"},
{VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"},
{VIRTIO_F_ANY_LAYOUT, "VIRTIO_F_ANY_LAYOUT"},
{ VIRTIO_RING_F_EVENT_IDX, "VIRTIO_RING_F_EVENT_IDX" },
};
UINT i;
for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Features[i].bitmask))
{
DPrintf(0, ("VirtIO Host Feature %s\n", Features[i].Name));
}
}
}
static BOOLEAN
AckFeature(PPARANDIS_ADAPTER pContext, UINT32 Feature)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Feature))
{
VirtIOFeatureEnable(pContext->u32GuestFeatures, Feature);
return TRUE;
}
return FALSE;
}
/**********************************************************
Prints out statistics
***********************************************************/
static void PrintStatistics(PARANDIS_ADAPTER *pContext)
{
ULONG64 totalTxFrames =
pContext->Statistics.ifHCOutBroadcastPkts +
pContext->Statistics.ifHCOutMulticastPkts +
pContext->Statistics.ifHCOutUcastPkts;
ULONG64 totalRxFrames =
pContext->Statistics.ifHCInBroadcastPkts +
pContext->Statistics.ifHCInMulticastPkts +
pContext->Statistics.ifHCInUcastPkts;
#if 0 /* TODO - setup accessor functions*/
DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d\n",
pContext->CurrentMacAddress[5],
pContext->RXPath.m_NetNofReceiveBuffers,
pContext->NetMaxReceiveBuffers));
DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d\n",
pContext->TXPath.GetFreeTXDescriptors(),
pContext->maxFreeTxDescriptors,
pContext->TXPath.GetFreeHWBuffers()));
#endif
DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u\n",
pContext->Statistics.ifHCOutOctets,
pContext->Statistics.ifHCInOctets));
DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d\n",
totalTxFrames,
pContext->extraStatistics.framesCSOffload,
pContext->extraStatistics.framesLSO,
pContext->extraStatistics.framesIndirect));
DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d\n",
totalRxFrames, pContext->extraStatistics.framesRxPriority,
pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut));
if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood)
{
DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d\n",
pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood));
}
}
static
VOID InitializeRSCState(PPARANDIS_ADAPTER pContext)
{
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4Enabled = FALSE;
pContext->RSC.bIPv6Enabled = FALSE;
if(!pContext->bGuestChecksumSupported)
{
DPrintf(0, ("[%s] Guest TSO cannot be enabled without guest checksum\n", __FUNCTION__) );
return;
}
if(pContext->RSC.bIPv4SupportedSW)
{
pContext->RSC.bIPv4Enabled =
pContext->RSC.bIPv4SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO4);
}
else
{
pContext->RSC.bIPv4SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO4);
}
if(pContext->RSC.bIPv6SupportedSW)
{
pContext->RSC.bIPv6Enabled =
pContext->RSC.bIPv6SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO6);
}
else
{
pContext->RSC.bIPv6SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO6);
}
pContext->RSC.bHasDynamicConfig = (pContext->RSC.bIPv4Enabled || pContext->RSC.bIPv6Enabled) &&
AckFeature(pContext, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
DPrintf(0, ("[%s] Guest TSO state: IP4=%d, IP6=%d, Dynamic=%d\n", __FUNCTION__,
pContext->RSC.bIPv4Enabled, pContext->RSC.bIPv6Enabled, pContext->RSC.bHasDynamicConfig) );
#else
UNREFERENCED_PARAMETER(pContext);
#endif
}
static __inline void
DumpMac(int dbg_level, const char* header_str, UCHAR* mac)
{
DPrintf(dbg_level,("%s: %02x-%02x-%02x-%02x-%02x-%02x\n",
header_str, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]));
}
static __inline void
SetDeviceMAC(PPARANDIS_ADAPTER pContext, PUCHAR pDeviceMAC)
{
if(pContext->bCfgMACAddrSupported && !pContext->bCtrlMACAddrSupported)
{
VirtIODeviceSet(pContext->IODevice, 0, pDeviceMAC, ETH_LENGTH_OF_ADDRESS);
}
}
static void
InitializeMAC(PPARANDIS_ADAPTER pContext, PUCHAR pCurrentMAC)
{
//Acknowledge related features
pContext->bCfgMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_MAC);
pContext->bCtrlMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_CTRL_MAC_ADDR);
//Read and validate permanent MAC address
if (pContext->bCfgMACAddrSupported)
{
VirtIODeviceGet(pContext->IODevice, 0, &pContext->PermanentMacAddress, ETH_LENGTH_OF_ADDRESS);
if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE))
{
DumpMac(0, "Invalid device MAC ignored", pContext->PermanentMacAddress);
NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress));
}
}
if (ETH_IS_EMPTY(pContext->PermanentMacAddress))
{
pContext->PermanentMacAddress[0] = 0x02;
pContext->PermanentMacAddress[1] = 0x50;
pContext->PermanentMacAddress[2] = 0xF2;
pContext->PermanentMacAddress[3] = 0x00;
pContext->PermanentMacAddress[4] = 0x01;
pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF);
DumpMac(0, "No device MAC present, use default", pContext->PermanentMacAddress);
}
DumpMac(0, "Permanent device MAC", pContext->PermanentMacAddress);
//Read and validate configured MAC address
if (ParaNdis_ValidateMacAddress(pCurrentMAC, TRUE))
{
DPrintf(0, ("[%s] MAC address from configuration used\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pCurrentMAC);
}
else
{
DPrintf(0, ("No valid MAC configured\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pContext->PermanentMacAddress);
}
//If control channel message for MAC address configuration is not supported
// Configure device with actual MAC address via configurations space
//Else actual MAC address will be configured later via control queue
SetDeviceMAC(pContext, pContext->CurrentMacAddress);
DumpMac(0, "Actual MAC", pContext->CurrentMacAddress);
}
static __inline void
RestoreMAC(PPARANDIS_ADAPTER pContext)
{
SetDeviceMAC(pContext, pContext->PermanentMacAddress);
}
/**********************************************************
Initializes the context structure
Major variables, received from NDIS on initialization, must be be set before this call
(for ex. pContext->MiniportHandle)
If this procedure fails, no need to call
ParaNdis_CleanupContext
Parameters:
Return value:
SUCCESS, if resources are OK
NDIS_STATUS_RESOURCE_CONFLICT if not
***********************************************************/
NDIS_STATUS ParaNdis_InitializeContext(
PARANDIS_ADAPTER *pContext,
PNDIS_RESOURCE_LIST pResourceList)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
USHORT linkStatus = 0;
UCHAR CurrentMAC[ETH_LENGTH_OF_ADDRESS] = {0};
ULONG dependentOptions;
DEBUG_ENTRY(0);
ReadNicConfiguration(pContext, CurrentMAC);
pContext->fCurrentLinkState = MediaConnectStateUnknown;
pContext->powerState = NdisDeviceStateUnspecified;
pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS;
#if PARANDIS_SUPPORT_RSC
pContext->MaxPacketSize.nMaxDataSizeHwRx = MAX_HW_RX_PACKET_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = MAX_OS_RX_PACKET_SIZE;
#else
pContext->MaxPacketSize.nMaxDataSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = pContext->MaxPacketSize.nMaxFullSizeOS;
#endif
if (pContext->ulPriorityVlanSetting)
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
if (GetAdapterResources(pResourceList, &pContext->AdapterResources) &&
NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange(
&pContext->pIoPortOffset,
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength)
)
{
if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE)
{
DPrintf(0, ("[%s] Message interrupt assigned\n", __FUNCTION__));
pContext->bUsingMSIX = TRUE;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(*pContext->IODevice));
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER);
pContext->u32HostFeatures = VirtIODeviceReadHostFeatures(pContext->IODevice);
DumpVirtIOFeatures(pContext);
pContext->bLinkDetectSupported = AckFeature(pContext, VIRTIO_NET_F_STATUS);
if(pContext->bLinkDetectSupported) {
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0;
DPrintf(0, ("[%s] Link status on driver startup: %d\n", __FUNCTION__, pContext->bConnected));
}
InitializeMAC(pContext, CurrentMAC);
pContext->bUseMergedBuffers = AckFeature(pContext, VIRTIO_NET_F_MRG_RXBUF);
pContext->nVirtioHeaderSize = (pContext->bUseMergedBuffers) ? sizeof(virtio_net_hdr_ext) : sizeof(virtio_net_hdr_basic);
pContext->bDoPublishIndices = AckFeature(pContext, VIRTIO_RING_F_EVENT_IDX);
}
else
{
DPrintf(0, ("[%s] Error: Incomplete resources\n", __FUNCTION__));
/* avoid deregistering if failed */
pContext->AdapterResources.ulIOAddress = 0;
status = NDIS_STATUS_RESOURCE_CONFLICT;
}
pContext->bMultiQueue = AckFeature(pContext, VIRTIO_NET_F_CTRL_MQ);
if (pContext->bMultiQueue)
{
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS + sizeof(USHORT), &pContext->nHardwareQueues,
sizeof(pContext->nHardwareQueues));
}
else
{
pContext->nHardwareQueues = 1;
}
dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum;
if((pContext->Offload.flagsValue & dependentOptions) && !AckFeature(pContext, VIRTIO_NET_F_CSUM))
{
DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload\n", __FUNCTION__) );
pContext->Offload.flagsValue &= ~dependentOptions;
}
pContext->bGuestChecksumSupported = AckFeature(pContext, VIRTIO_NET_F_GUEST_CSUM);
AckFeature(pContext, VIRTIO_NET_F_CTRL_VQ);
InitializeRSCState(pContext);
// now, after we checked the capabilities, we can initialize current
// configuration of offload tasks
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
if (pContext->Offload.flags.fTxLso && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO4))
{
DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4\n");
}
if (pContext->Offload.flags.fTxLsov6 && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO6))
{
DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6");
}
pContext->bUseIndirect = AckFeature(pContext, VIRTIO_F_INDIRECT);
pContext->bAnyLaypout = AckFeature(pContext, VIRTIO_F_ANY_LAYOUT);
pContext->bHasHardwareFilters = AckFeature(pContext, VIRTIO_NET_F_CTRL_RX_EXTRA);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
NdisInitializeEvent(&pContext->ResetEvent);
DEBUG_EXIT_STATUS(0, status);
return status;
}
void ParaNdis_FreeRxBufferDescriptor(PARANDIS_ADAPTER *pContext, pRxNetDescriptor p)
{
ULONG i;
for(i = 0; i < p->PagesAllocated; i++)
{
ParaNdis_FreePhysicalMemory(pContext, &p->PhysicalPages[i]);
}
if(p->BufferSGArray) NdisFreeMemory(p->BufferSGArray, 0, 0);
if(p->PhysicalPages) NdisFreeMemory(p->PhysicalPages, 0, 0);
NdisFreeMemory(p, 0, 0);
}
/**********************************************************
Allocates maximum RX buffers for incoming packets
Buffers are chained in NetReceiveBuffers
Parameters:
context
***********************************************************/
void ParaNdis_DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa)
{
if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL);
*ppq = NULL;
if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa);
RtlZeroMemory(ppa, sizeof(*ppa));
}
#if PARANDIS_SUPPORT_RSS
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *pContext)
{
if (!pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] No MSIX, using 1 queue\n", __FUNCTION__));
return 1;
}
if (pContext->bMultiQueue)
{
DPrintf(0, ("[%s] Number of hardware queues = %d\n", __FUNCTION__, pContext->nHardwareQueues));
}
else
{
DPrintf(0, ("[%s] - CTRL_MQ not acked, # bindles set to 1\n", __FUNCTION__));
return 1;
}
ULONG lnProcessors;
#if NDIS_SUPPORT_NDIS620
lnProcessors = NdisGroupActiveProcessorCount(ALL_PROCESSOR_GROUPS);
#elif NDIS_SUPPORT_NDIS6
lnProcessors = NdisSystemProcessorCount();
#else
lnProcessors = 1;
#endif
ULONG lnMSIs = (pContext->pMSIXInfoTable->MessageCount - 1) / 2; /* RX/TX pairs + control queue*/
DPrintf(0, ("[%s] %lu CPUs reported\n", __FUNCTION__, lnProcessors));
DPrintf(0, ("[%s] %lu MSIs, %lu queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, lnMSIs));
USHORT nMSIs = USHORT(lnMSIs & 0xFFFF);
USHORT nProcessors = USHORT(lnProcessors & 0xFFFF);
DPrintf(0, ("[%s] %u CPUs reported\n", __FUNCTION__, nProcessors));
DPrintf(0, ("[%s] %lu MSIs, %u queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, nMSIs));
USHORT nBundles = (pContext->nHardwareQueues < nProcessors) ? pContext->nHardwareQueues : nProcessors;
nBundles = (nMSIs < nBundles) ? nMSIs : nBundles;
DPrintf(0, ("[%s] # of path bundles = %u\n", __FUNCTION__, nBundles));
return nBundles;
}
#else
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *)
{
return 1;
}
#endif
static NDIS_STATUS SetupDPCTarget(PARANDIS_ADAPTER *pContext)
{
ULONG i;
#if NDIS_SUPPORT_NDIS620
NDIS_STATUS status;
PROCESSOR_NUMBER procNumber;
#endif
for (i = 0; i < pContext->nPathBundles; i++)
{
#if NDIS_SUPPORT_NDIS620
status = KeGetProcessorNumberFromIndex(i, &procNumber);
if (status != NDIS_STATUS_SUCCESS)
{
DPrintf(0, ("[%s] - KeGetProcessorNumberFromIndex failed for index %lu - %d\n", __FUNCTION__, i, status));
return status;
}
ParaNdis_ProcessorNumberToGroupAffinity(&pContext->pPathBundles[i].rxPath.DPCAffinity, &procNumber);
pContext->pPathBundles[i].txPath.DPCAffinity = pContext->pPathBundles[i].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->pPathBundles[i].rxPath.DPCTargetProcessor = 1i64 << i;
pContext->pPathBundles[i].txPath.DPCTargetProcessor = pContext->pPathBundles[i].rxPath.DPCTargetProcessor;
#else
#error not supported
#endif
}
#if NDIS_SUPPORT_NDIS620
pContext->CXPath.DPCAffinity = pContext->pPathBundles[0].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->CXPath.DPCTargetProcessor = pContext->pPathBundles[0].rxPath.DPCTargetProcessor;
#else
#error not yet defined
#endif
return NDIS_STATUS_SUCCESS;
}
#if PARANDIS_SUPPORT_RSS
NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext)
{
USHORT rssIndex, bundleIndex;
ULONG cpuIndex;
ULONG rssTableSize = pContext->RSSParameters.RSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
rssIndex = 0;
bundleIndex = 0;
USHORT *cpuIndexTable;
ULONG cpuNumbers;
cpuNumbers = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
cpuIndexTable = (USHORT *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, cpuNumbers * sizeof(*cpuIndexTable),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (cpuIndexTable == nullptr)
{
DPrintf(0, ("[%s] cpu index table allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(cpuIndexTable, sizeof(*cpuIndexTable) * cpuNumbers);
for (bundleIndex = 0; bundleIndex < pContext->nPathBundles; ++bundleIndex)
{
cpuIndex = pContext->pPathBundles[bundleIndex].rxPath.getCPUIndex();
if (cpuIndex == INVALID_PROCESSOR_INDEX)
{
DPrintf(0, ("[%s] Invalid CPU index for path %u\n", __FUNCTION__, bundleIndex));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else if (cpuIndex >= cpuNumbers)
{
DPrintf(0, ("[%s] CPU index %lu exceeds CPU range %lu\n", __FUNCTION__, cpuIndex, cpuNumbers));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else
{
cpuIndexTable[cpuIndex] = bundleIndex;
}
}
DPrintf(0, ("[%s] Entering, RSS table size = %lu, # of path bundles = %u. RSS2QueueLength = %u, RSS2QueueMap =0x%p\n",
__FUNCTION__, rssTableSize, pContext->nPathBundles,
pContext->RSS2QueueLength, pContext->RSS2QueueMap));
if (pContext->RSS2QueueLength && pContext->RSS2QueueLength < rssTableSize)
{
DPrintf(0, ("[%s] Freeing RSS2Queue Map\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueLength = 0;
}
if (!pContext->RSS2QueueLength)
{
pContext->RSS2QueueLength = USHORT(rssTableSize);
pContext->RSS2QueueMap = (CPUPathesBundle **)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, rssTableSize * sizeof(*pContext->RSS2QueueMap),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->RSS2QueueMap == nullptr)
{
DPrintf(0, ("[%s] - Allocating RSS to queue mapping failed\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(pContext->RSS2QueueMap, sizeof(*pContext->RSS2QueueMap) * pContext->RSS2QueueLength);
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles;
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
cpuIndex = NdisProcessorNumberToIndex(pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex]);
bundleIndex = cpuIndexTable[cpuIndex];
DPrintf(3, ("[%s] filling the relationship, rssIndex = %u, bundleIndex = %u\n", __FUNCTION__, rssIndex, bundleIndex));
DPrintf(3, ("[%s] RSS proc number %u/%u, bundle affinity %u/%u\n", __FUNCTION__,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Group,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Number,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Group,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Mask));
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles + bundleIndex;
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SUCCESS;
}
#endif
/**********************************************************
Initializes VirtIO buffering and related stuff:
Allocates RX and TX queues and buffers
Parameters:
context
Return value:
TRUE if both queues are allocated
***********************************************************/
static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_RESOURCES;
DEBUG_ENTRY(0);
UINT i;
USHORT nVirtIOQueues = pContext->nHardwareQueues * 2 + 2;
pContext->nPathBundles = DetermineQueueNumber(pContext);
if (pContext->nPathBundles == 0)
{
DPrintf(0, ("[%s] - no I/O pathes\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
if (nVirtIOQueues > pContext->IODevice->maxQueues)
{
ULONG IODeviceSize = VirtIODeviceSizeRequired(nVirtIOQueues);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = (VirtIODevice *)NdisAllocateMemoryWithTagPriority(
pContext->MiniportHandle,
IODeviceSize,
PARANDIS_MEMORY_TAG,
NormalPoolPriority);
if (pContext->IODevice == nullptr)
{
DPrintf(0, ("[%s] - IODevice allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, IODeviceSize);
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
DPrintf(0, ("[%s] %u queues' slots reallocated for size %lu\n", __FUNCTION__, pContext->IODevice->maxQueues, IODeviceSize));
}
new (&pContext->CXPath, PLACEMENT_NEW) CParaNdisCX();
pContext->bCXPathAllocated = TRUE;
if (!pContext->CXPath.Create(pContext, 2 * pContext->nHardwareQueues))
{
DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__));
pContext->bHasHardwareFilters = FALSE;
pContext->bCtrlMACAddrSupported = FALSE;
}
else
{
pContext->bCXPathCreated = TRUE;
}
pContext->pPathBundles = (CPUPathesBundle *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, pContext->nPathBundles * sizeof(*pContext->pPathBundles),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->pPathBundles == nullptr)
{
DPrintf(0, ("[%s] Path bundles allocation failed\n", __FUNCTION__));
return status;
}
for (i = 0; i < pContext->nPathBundles; i++)
{
new (pContext->pPathBundles + i, PLACEMENT_NEW) CPUPathesBundle();
if (!pContext->pPathBundles[i].rxPath.Create(pContext, i * 2))
{
DPrintf(0, ("%s: CParaNdisRX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].rxCreated = true;
if (!pContext->pPathBundles[i].txPath.Create(pContext, i * 2 + 1))
{
DPrintf(0, ("%s: CParaNdisTX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].txCreated = true;
}
if (pContext->bCXPathCreated)
{
pContext->pPathBundles[0].cxPath = &pContext->CXPath;
}
status = NDIS_STATUS_SUCCESS;
return status;
}
static void ReadLinkState(PARANDIS_ADAPTER *pContext)
{
if (pContext->bLinkDetectSupported)
{
USHORT linkStatus = 0;
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = !!(linkStatus & VIRTIO_NET_S_LINK_UP);
}
else
{
pContext->bConnected = TRUE;
}
}
static void ParaNdis_RemoveDriverOKStatus(PPARANDIS_ADAPTER pContext )
{
VirtIODeviceRemoveStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
KeMemoryBarrier();
pContext->bDeviceInitialized = FALSE;
}
static VOID ParaNdis_AddDriverOKStatus(PPARANDIS_ADAPTER pContext)
{
pContext->bDeviceInitialized = TRUE;
KeMemoryBarrier();
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
}
/**********************************************************
Finishes initialization of context structure, calling also version dependent part
If this procedure failed, ParaNdis_CleanupContext must be called
Parameters:
context
Return value:
SUCCESS or some kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
DEBUG_ENTRY(0);
status = ParaNdis_FinishSpecificInitialization(pContext);
DPrintf(0, ("[%s] ParaNdis_FinishSpecificInitialization passed, status = %d\n", __FUNCTION__, status));
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_VirtIONetInit(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_ConfigureMSIXVectors(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = SetupDPCTarget(pContext);
DPrintf(0, ("[%s] SetupDPCTarget passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS && pContext->nPathBundles > 1)
{
u16 nPathes = u16(pContext->nPathBundles);
BOOLEAN sendSuccess = pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, VIRTIO_NET_CTRL_MQ_VQ_PAIR_SET, &nPathes, sizeof(nPathes), NULL, 0, 2);
if (!sendSuccess)
{
DPrintf(0, ("[%s] - Send MQ control message failed\n", __FUNCTION__));
status = NDIS_STATUS_DEVICE_FAILED;
}
}
pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1;
if (status == NDIS_STATUS_SUCCESS)
{
ReadLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
ParaNdis_AddDriverOKStatus(pContext);
ParaNdis_UpdateMAC(pContext);
}
DEBUG_EXIT_STATUS(0, status);
return status;
}
/**********************************************************
Releases VirtIO related resources - queues and buffers
Parameters:
context
Return value:
***********************************************************/
static void VirtIONetRelease(PARANDIS_ADAPTER *pContext)
{
BOOLEAN b;
ULONG i;
DEBUG_ENTRY(0);
/* list NetReceiveBuffersWaiting must be free */
for (i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
pRxNetDescriptor pBufferDescriptor;
while (NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pContext->ReceiveQueues + i)))
{
pBufferDescriptor->Queue->ReuseReceiveBuffer(FALSE, pBufferDescriptor);
}
}
do
{
b = pContext->m_upstreamPacketPending != 0;
if (b)
{
DPrintf(0, ("[%s] There are waiting buffers\n", __FUNCTION__));
PrintStatistics(pContext);
NdisMSleep(5000000);
}
} while (b);
RestoreMAC(pContext);
for (i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txCreated)
{
pContext->pPathBundles[i].txPath.Shutdown();
}
if (pContext->pPathBundles[i].rxCreated)
{
pContext->pPathBundles[i].rxPath.Shutdown();
/* this can be freed, queue shut down */
pContext->pPathBundles[i].rxPath.FreeRxDescriptorsFromList();
}
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
PrintStatistics(pContext);
}
static void PreventDPCServicing(PARANDIS_ADAPTER *pContext)
{
LONG inside;
pContext->bEnableInterruptHandlingDPC = FALSE;
KeMemoryBarrier();
do
{
inside = InterlockedIncrement(&pContext->counterDPCInside);
InterlockedDecrement(&pContext->counterDPCInside);
if (inside > 1)
{
DPrintf(0, ("[%s] waiting!\n", __FUNCTION__));
NdisMSleep(20000);
}
} while (inside > 1);
}
/**********************************************************
Frees all the resources allocated when the context initialized,
calling also version-dependent part
Parameters:
context
***********************************************************/
VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext)
{
/* disable any interrupt generation */
if (pContext->IODevice->addr)
{
if (pContext->bDeviceInitialized)
{
ParaNdis_RemoveDriverOKStatus(pContext);
}
}
PreventDPCServicing(pContext);
/****************************************
ensure all the incoming packets returned,
free all the buffers and their descriptors
*****************************************/
if (pContext->IODevice->addr)
{
ParaNdis_ResetVirtIONetDevice(pContext);
}
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
VirtIONetRelease(pContext);
ParaNdis_FinalizeCleanup(pContext);
if (pContext->ReceiveQueuesInitialized)
{
ULONG i;
for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
NdisFreeSpinLock(&pContext->ReceiveQueues[i].Lock);
}
}
pContext->m_PauseLock.~CNdisRWLock();
#if PARANDIS_SUPPORT_RSS
if (pContext->bRSSInitialized)
{
ParaNdis6_RSSCleanupConfiguration(&pContext->RSSParameters);
}
pContext->RSSParameters.rwLock.~CNdisRWLock();
#endif
if (pContext->bCXPathAllocated)
{
pContext->CXPath.~CParaNdisCX();
pContext->bCXPathAllocated = false;
}
if (pContext->pPathBundles != NULL)
{
USHORT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].~CPUPathesBundle();
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->pPathBundles, PARANDIS_MEMORY_TAG);
pContext->pPathBundles = nullptr;
}
if (pContext->RSS2QueueMap)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueMap = nullptr;
pContext->RSS2QueueLength = 0;
}
if (pContext->IODevice)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = nullptr;
}
if (pContext->AdapterResources.ulIOAddress)
{
NdisMDeregisterIoPortRange(
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength,
pContext->pIoPortOffset);
pContext->AdapterResources.ulIOAddress = 0;
}
}
/**********************************************************
System shutdown handler (shutdown, restart, bugcheck)
Parameters:
context
***********************************************************/
VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0); // this is only for kdbg :)
ParaNdis_ResetVirtIONetDevice(pContext);
}
static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo)
{
ULONG i;
if (pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
if ((pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx) && !pPacketInfo->hasVlanHeader)
return FALSE;
if (IsVlanSupported(pContext) && pPacketInfo->hasVlanHeader)
{
if (pContext->VlanId && pContext->VlanId != pPacketInfo->Vlan.VlanId)
{
return FALSE;
}
}
if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS)
return TRUE;
if(pPacketInfo->isUnicast)
{
ULONG Res;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED))
return FALSE;
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, pContext->CurrentMacAddress, &Res);
return !Res;
}
if(pPacketInfo->isBroadcast)
return (pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST);
// Multi-cast
if(pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST)
return TRUE;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST))
return FALSE;
for (i = 0; i < pContext->MulticastData.nofMulticastEntries; i++)
{
ULONG Res;
PUCHAR CurrMcastAddr = &pContext->MulticastData.MulticastList[i*ETH_LENGTH_OF_ADDRESS];
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, CurrMcastAddr, &Res);
if(!Res)
return TRUE;
}
return FALSE;
}
BOOLEAN ParaNdis_PerformPacketAnalyzis(
#if PARANDIS_SUPPORT_RSS
PPARANDIS_RSS_PARAMS RSSParameters,
#endif
PNET_PACKET_INFO PacketInfo,
PVOID HeadersBuffer,
ULONG DataLength)
{
if(!ParaNdis_AnalyzeReceivedPacket(HeadersBuffer, DataLength, PacketInfo))
return FALSE;
#if PARANDIS_SUPPORT_RSS
if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED)
{
ParaNdis6_RSSAnalyzeReceivedPacket(RSSParameters, HeadersBuffer, PacketInfo);
}
#endif
return TRUE;
}
VOID ParaNdis_ProcessorNumberToGroupAffinity(PGROUP_AFFINITY Affinity, const PPROCESSOR_NUMBER Processor)
{
Affinity->Group = Processor->Group;
Affinity->Mask = 1;
Affinity->Mask <<= Processor->Number;
}
CCHAR ParaNdis_GetScalingDataForPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo, PPROCESSOR_NUMBER pTargetProcessor)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetScalingDataForPacket(&pContext->RSSParameters, pPacketInfo, pTargetProcessor);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(pPacketInfo);
UNREFERENCED_PARAMETER(pTargetProcessor);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
static __inline
CCHAR GetReceiveQueueForCurrentCPU(PARANDIS_ADAPTER *pContext)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetCurrentCpuReceiveQueue(&pContext->RSSParameters);
#else
UNREFERENCED_PARAMETER(pContext);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
VOID ParaNdis_QueueRSSDpc(PARANDIS_ADAPTER *pContext, ULONG MessageIndex, PGROUP_AFFINITY pTargetAffinity)
{
#if PARANDIS_SUPPORT_RSS
NdisMQueueDpcEx(pContext->InterruptHandle, MessageIndex, pTargetAffinity, NULL);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(MessageIndex);
UNREFERENCED_PARAMETER(pTargetAffinity);
ASSERT(FALSE);
#endif
}
VOID ParaNdis_ReceiveQueueAddBuffer(PPARANDIS_RECEIVE_QUEUE pQueue, pRxNetDescriptor pBuffer)
{
NdisInterlockedInsertTailList( &pQueue->BuffersList,
&pBuffer->ReceiveQueueListEntry,
&pQueue->Lock);
}
VOID ParaMdis_TestPausing(PARANDIS_ADAPTER *pContext)
{
ONPAUSECOMPLETEPROC callback = nullptr;
if (pContext->m_upstreamPacketPending == 0)
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
if (pContext->m_upstreamPacketPending == 0 && (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc))
{
callback = pContext->ReceivePauseCompletionProc;
pContext->ReceiveState = srsDisabled;
pContext->ReceivePauseCompletionProc = NULL;
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
}
}
if (callback) callback(pContext);
}
static __inline
pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue)
{
PLIST_ENTRY pListEntry = NdisInterlockedRemoveHeadList(&pQueue->BuffersList, &pQueue->Lock);
return pListEntry ? CONTAINING_RECORD(pListEntry, RxNetDescriptor, ReceiveQueueListEntry) : NULL;
}
static __inline
BOOLEAN ReceiveQueueHasBuffers(PPARANDIS_RECEIVE_QUEUE pQueue)
{
BOOLEAN res;
NdisAcquireSpinLock(&pQueue->Lock);
res = !IsListEmpty(&pQueue->BuffersList);
NdisReleaseSpinLock(&pQueue->Lock);
return res;
}
static VOID
UpdateReceiveSuccessStatistics(PPARANDIS_ADAPTER pContext,
PNET_PACKET_INFO pPacketInfo,
UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifHCInOctets += pPacketInfo->dataLength;
if(pPacketInfo->isUnicast)
{
pContext->Statistics.ifHCInUcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInUcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isBroadcast)
{
pContext->Statistics.ifHCInBroadcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInBroadcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isMulticast)
{
pContext->Statistics.ifHCInMulticastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInMulticastOctets += pPacketInfo->dataLength;
}
else
{
ASSERT(FALSE);
}
}
static __inline VOID
UpdateReceiveFailStatistics(PPARANDIS_ADAPTER pContext, UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifInErrors++;
pContext->Statistics.ifInDiscards += nCoalescedSegmentsCount;
}
static BOOLEAN ProcessReceiveQueue(PARANDIS_ADAPTER *pContext,
PULONG pnPacketsToIndicateLeft,
CCHAR nQueueIndex,
PNET_BUFFER_LIST *indicate,
PNET_BUFFER_LIST *indicateTail,
ULONG *nIndicate)
{
pRxNetDescriptor pBufferDescriptor;
PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex];
if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1)
{
while( (*pnPacketsToIndicateLeft > 0) &&
(NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) )
{
PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo;
if( !pContext->bSurprizeRemoved &&
pContext->ReceiveState == srsEnabled &&
pContext->bConnected &&
ShallPassPacket(pContext, pPacketInfo))
{
UINT nCoalescedSegmentsCount;
PNET_BUFFER_LIST packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor, &nCoalescedSegmentsCount);
if(packet != NULL)
{
UpdateReceiveSuccessStatistics(pContext, pPacketInfo, nCoalescedSegmentsCount);
if (*indicate == nullptr)
{
*indicate = *indicateTail = packet;
}
else
{
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = packet;
*indicateTail = packet;
}
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = NULL;
(*pnPacketsToIndicateLeft)--;
(*nIndicate)++;
}
else
{
UpdateReceiveFailStatistics(pContext, nCoalescedSegmentsCount);
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
else
{
pContext->extraStatistics.framesFilteredOut++;
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
}
NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount);
return ReceiveQueueHasBuffers(pTargetReceiveQueue);
}
static
BOOLEAN RxDPCWorkBody(PARANDIS_ADAPTER *pContext, CPUPathesBundle *pathBundle, ULONG nPacketsToIndicate)
{
BOOLEAN res = FALSE;
BOOLEAN bMoreDataInRing;
PNET_BUFFER_LIST indicate, indicateTail;
ULONG nIndicate;
CCHAR CurrCpuReceiveQueue = GetReceiveQueueForCurrentCPU(pContext);
do
{
indicate = nullptr;
indicateTail = nullptr;
nIndicate = 0;
{
CNdisDispatchReadAutoLock tLock(pContext->m_PauseLock);
pathBundle->rxPath.ProcessRxRing(CurrCpuReceiveQueue);
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED,
&indicate, &indicateTail, &nIndicate);
if(CurrCpuReceiveQueue != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED)
{
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, CurrCpuReceiveQueue,
&indicate, &indicateTail, &nIndicate);
}
bMoreDataInRing = pathBundle->rxPath.RestartQueue();
}
if (nIndicate)
{
NdisMIndicateReceiveNetBufferLists(pContext->MiniportHandle,
indicate,
0,
nIndicate,
0);
}
ParaMdis_TestPausing(pContext);
} while (bMoreDataInRing);
return res;
}
bool ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate)
{
bool stillRequiresProcessing = false;
UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC);
DEBUG_ENTRY(5);
InterlockedIncrement(&pContext->counterDPCInside);
CPUPathesBundle *pathBundle = nullptr;
if (pContext->nPathBundles == 1)
{
pathBundle = pContext->pPathBundles;
}
else
{
ULONG procNumber = KeGetCurrentProcessorNumber();
if (procNumber < pContext->nPathBundles)
{
pathBundle = pContext->pPathBundles + procNumber;
}
}
if (pathBundle == nullptr)
{
return false;
}
if (pContext->bEnableInterruptHandlingDPC)
{
bool bDoKick = false;
InterlockedExchange(&pContext->bDPCInactive, 0);
if (RxDPCWorkBody(pContext, pathBundle, numOfPacketsToIndicate))
{
stillRequiresProcessing = true;
}
if (pContext->CXPath.WasInterruptReported() && pContext->bLinkDetectSupported)
{
ReadLinkState(pContext);
ParaNdis_SynchronizeLinkState(pContext);
pContext->CXPath.ClearInterruptReport();
}
if (!stillRequiresProcessing)
{
bDoKick = pathBundle->txPath.DoPendingTasks(true);
if (pathBundle->txPath.RestartQueue(bDoKick))
{
stillRequiresProcessing = true;
}
}
}
InterlockedDecrement(&pContext->counterDPCInside);
return stillRequiresProcessing;
}
VOID ParaNdis_ResetRxClassification(PARANDIS_ADAPTER *pContext)
{
ULONG i;
PPARANDIS_RECEIVE_QUEUE pUnclassified = &pContext->ReceiveQueues[PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED];
NdisAcquireSpinLock(&pUnclassified->Lock);
for(i = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED + 1; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
PPARANDIS_RECEIVE_QUEUE pCurrQueue = &pContext->ReceiveQueues[i];
NdisAcquireSpinLock(&pCurrQueue->Lock);
while(!IsListEmpty(&pCurrQueue->BuffersList))
{
PLIST_ENTRY pListEntry = RemoveHeadList(&pCurrQueue->BuffersList);
InsertTailList(&pUnclassified->BuffersList, pListEntry);
}
NdisReleaseSpinLock(&pCurrQueue->Lock);
}
NdisReleaseSpinLock(&pUnclassified->Lock);
}
/**********************************************************
Periodically called procedure, checking dpc activity
If DPC are not running, it does exactly the same that the DPC
Parameters:
context
***********************************************************/
static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext)
{
BOOLEAN bStopped;
BOOLEAN bReportHang = FALSE;
bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE);
if (bStopped)
{
pContext->nDetectedInactivity++;
}
else
{
pContext->nDetectedInactivity = 0;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txPath.HasHWBuffersIsUse())
{
if (pContext->nDetectedStoppedTx++ > 1)
{
DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!\n", __FUNCTION__, pContext->pPathBundles[i].txPath.GetFreeHWBuffers()));
//bReportHang = TRUE;
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 0);
#endif
break;
}
}
}
if (pContext->Limits.nPrintDiagnostic &&
++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic)
{
pContext->Counters.nPrintDiagnostic = 0;
// todo - collect more and put out optionally
PrintStatistics(pContext);
}
if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn)
{
pContext->Counters.nRxInactivity++;
if (pContext->Counters.nRxInactivity >= 10)
{
#if defined(CRASH_ON_NO_RX)
ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1;
proc(pContext);
#endif
}
}
else
{
pContext->Counters.nRxInactivity = 0;
pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets;
}
return bReportHang;
}
/**********************************************************
Common implementation of periodic poll
Parameters:
context
Return:
TRUE, if reset required
***********************************************************/
BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext)
{
static int nHangOn = 0;
BOOLEAN b = nHangOn >= 3 && nHangOn < 6;
DEBUG_ENTRY(3);
b |= CheckRunningDpc(pContext);
//uncomment to cause 3 consecutive resets
//nHangOn++;
DEBUG_EXIT_STATUS(b ? 0 : 6, b);
return b;
}
/////////////////////////////////////////////////////////////////////////////////////
//
// ReadVirtIODeviceRegister\WriteVirtIODeviceRegister
// NDIS specific implementation of the IO space read\write
//
/////////////////////////////////////////////////////////////////////////////////////
u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister)
{
ULONG ulValue;
NdisRawReadPortUlong(ulRegister, &ulValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
return ulValue;
}
void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
NdisRawWritePortUlong(ulRegister, ulValue);
}
u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister)
{
u8 bValue;
NdisRawReadPortUchar(ulRegister, &bValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
return bValue;
}
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
NdisRawWritePortUchar(ulRegister, bValue);
}
u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister)
{
u16 wValue;
NdisRawReadPortUshort(ulRegister, &wValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
return wValue;
}
void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue)
{
#if 1
NdisRawWritePortUshort(ulRegister, wValue);
#else
// test only to cause long TX waiting queue of NDIS packets
// to recognize it and request for reset via Hang handler
static int nCounterToFail = 0;
static const int StartFail = 200, StopFail = 600;
BOOLEAN bFail = FALSE;
DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
if ((ulRegister & 0x1F) == 0x10)
{
nCounterToFail++;
bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail;
}
if (!bFail) NdisRawWritePortUshort(ulRegister, wValue);
else
{
DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
}
#endif
}
/**********************************************************
Common handler of multicast address configuration
Parameters:
PVOID Buffer array of addresses from NDIS
ULONG BufferSize size of incoming buffer
PUINT pBytesRead update on success
PUINT pBytesNeeded update on wrong buffer size
Return value:
SUCCESS or kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_SetMulticastList(
PARANDIS_ADAPTER *pContext,
PVOID Buffer,
ULONG BufferSize,
PUINT pBytesRead,
PUINT pBytesNeeded)
{
NDIS_STATUS status;
ULONG length = BufferSize;
if (length > sizeof(pContext->MulticastData.MulticastList))
{
status = NDIS_STATUS_MULTICAST_FULL;
*pBytesNeeded = sizeof(pContext->MulticastData.MulticastList);
}
else if (length % ETH_LENGTH_OF_ADDRESS)
{
status = NDIS_STATUS_INVALID_LENGTH;
*pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS;
}
else
{
NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList));
if (length)
NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length);
pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS;
DPrintf(1, ("[%s] New multicast list of %d bytes\n", __FUNCTION__, length));
*pBytesRead = length;
status = NDIS_STATUS_SUCCESS;
}
return status;
}
/**********************************************************
Common handler of PnP events
Parameters:
Return value:
***********************************************************/
VOID ParaNdis_OnPnPEvent(
PARANDIS_ADAPTER *pContext,
NDIS_DEVICE_PNP_EVENT pEvent,
PVOID pInfo,
ULONG ulSize)
{
const char *pName = "";
UNREFERENCED_PARAMETER(pInfo);
UNREFERENCED_PARAMETER(ulSize);
DEBUG_ENTRY(0);
#undef MAKECASE
#define MAKECASE(x) case (x): pName = #x; break;
switch (pEvent)
{
MAKECASE(NdisDevicePnPEventQueryRemoved)
MAKECASE(NdisDevicePnPEventRemoved)
MAKECASE(NdisDevicePnPEventSurpriseRemoved)
MAKECASE(NdisDevicePnPEventQueryStopped)
MAKECASE(NdisDevicePnPEventStopped)
MAKECASE(NdisDevicePnPEventPowerProfileChanged)
MAKECASE(NdisDevicePnPEventFilterListChanged)
default:
break;
}
ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0);
DPrintf(0, ("[%s] (%s)\n", __FUNCTION__, pName));
if (pEvent == NdisDevicePnPEventSurpriseRemoved)
{
// on simulated surprise removal (under PnpTest) we need to reset the device
// to prevent any access of device queues to memory buffers
pContext->bSurprizeRemoved = TRUE;
ParaNdis_ResetVirtIONetDevice(pContext);
{
UINT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Pause();
}
}
}
pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent;
if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0]))
pContext->nPnpEventIndex = 0;
}
static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext)
{
u8 val;
ULONG f = pContext->PacketFilter;
val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2);
//SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2);
}
static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext)
{
u32 u32UniCastEntries = 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET,
&u32UniCastEntries,
sizeof(u32UniCastEntries),
&pContext->MulticastData,
sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS,
2);
}
static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK)
{
u16 val = vlanId & 0xfff;
UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK);
}
static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn)
{
ULONG i;
for (i = 0; i <= MAX_VLAN_ID; ++i)
SetSingleVlanFilter(pContext, i, bOn, 7);
}
/*
possible values of filter set (pContext->ulCurrentVlansFilterSet):
0 - all disabled
1..4095 - one selected enabled
4096 - all enabled
Note that only 0th vlan can't be enabled
*/
VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ULONG newFilterSet;
if (IsVlanSupported(pContext))
newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1);
else
newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0;
if (newFilterSet != pContext->ulCurrentVlansFilterSet)
{
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, FALSE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2);
pContext->ulCurrentVlansFilterSet = newFilterSet;
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, TRUE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2);
}
}
}
VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ParaNdis_DeviceFiltersUpdateRxMode(pContext);
ParaNdis_DeviceFiltersUpdateAddresses(pContext);
ParaNdis_DeviceFiltersUpdateVlanId(pContext);
}
}
static VOID
ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext)
{
if (pContext->bCtrlMACAddrSupported)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_ADDR_SET,
pContext->CurrentMacAddress,
ETH_LENGTH_OF_ADDRESS,
NULL, 0, 4);
}
}
#if PARANDIS_SUPPORT_RSC
VOID
ParaNdis_UpdateGuestOffloads(PARANDIS_ADAPTER *pContext, UINT64 Offloads)
{
if (pContext->RSC.bHasDynamicConfig)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_GUEST_OFFLOADS, VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET,
&Offloads,
sizeof(Offloads),
NULL, 0, 2);
}
}
#endif
VOID ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext)
{
UINT i;
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER);
/* GetHostFeature must be called with any mask once upon device initialization:
otherwise the device will not work properly */
VirtIODeviceReadHostFeatures(pContext->IODevice);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Renew();
pContext->pPathBundles[i].rxPath.Renew();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Renew();
}
ParaNdis_RestoreDeviceConfigurationAfterReset(pContext);
ParaNdis_UpdateDeviceFilters(pContext);
ParaNdis_UpdateMAC(pContext);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].rxPath.PopulateQueue();
}
ReadLinkState(pContext);
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_AddDriverOKStatus(pContext);
// if bFastSuspendInProcess is set by Win8 power-off procedure,
// the ParaNdis_Resume enables Tx and RX
// otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart)
ParaNdis_Resume(pContext);
pContext->bFastSuspendInProcess = FALSE;
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0);
}
VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0);
pContext->bConnected = FALSE;
// if bFastSuspendInProcess is set by Win8 power-off procedure
// the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis)
pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled;
ParaNdis_Suspend(pContext);
ParaNdis_RemoveDriverOKStatus(pContext);
if (pContext->bFastSuspendInProcess)
{
InterlockedExchange(&pContext->ReuseBufferRegular, FALSE);
}
#if !NDIS_SUPPORT_NDIS620
// WLK tests for Windows 2008 require media disconnect indication
// on power off. HCK tests for newer versions require media state unknown
// indication only and fail on disconnect indication
ParaNdis_SetLinkState(pContext, MediaConnectStateDisconnected);
#endif
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
PreventDPCServicing(pContext);
/*******************************************************************
shutdown queues to have all the receive buffers under our control
all the transmit buffers move to list of free buffers
********************************************************************/
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Shutdown();
pContext->pPathBundles[i].rxPath.Shutdown();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
ParaNdis_ResetVirtIONetDevice(pContext);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0);
}
void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext)
{
if (pContext->AdapterResources.ulIOAddress)
{
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 1);
#endif
}
}
tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
//VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS
//VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)
{
res.flags.IpOK = FALSE;
res.flags.IpFailed = TRUE;
return res;
}
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1580_0 |
crossvul-cpp_data_good_597_0 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/session/HTTPSession.h>
#include <chrono>
#include <fizz/protocol/AsyncFizzBase.h>
#include <folly/Conv.h>
#include <folly/CppAttributes.h>
#include <folly/Random.h>
#include <wangle/acceptor/ConnectionManager.h>
#include <wangle/acceptor/SocketOptions.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/codec/HTTPChecks.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/session/HTTPSessionController.h>
#include <proxygen/lib/http/session/HTTPSessionStats.h>
#include <folly/io/async/AsyncSSLSocket.h>
#include <folly/io/Cursor.h>
#include <folly/tracing/ScopedTraceSection.h>
using fizz::AsyncFizzBase;
using folly::AsyncSSLSocket;
using folly::AsyncSocket;
using folly::AsyncTransportWrapper;
using folly::AsyncTransport;
using folly::WriteFlags;
using folly::AsyncSocketException;
using folly::io::QueueAppender;
using folly::IOBuf;
using folly::IOBufQueue;
using folly::SocketAddress;
using wangle::TransportInfo;
using std::make_unique;
using std::pair;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
static const uint32_t kMinReadSize = 1460;
static const uint32_t kWriteReadyMax = 65536;
// Lower = higher latency, better prioritization
// Higher = lower latency, less prioritization
static const uint32_t kMaxWritesPerLoop = 32;
static constexpr folly::StringPiece kClientLabel =
"EXPORTER HTTP CERTIFICATE client";
static constexpr folly::StringPiece kServerLabel =
"EXPORTER HTTP CERTIFICATE server";
} // anonymous namespace
namespace proxygen {
HTTPSession::WriteSegment::WriteSegment(
HTTPSession* session,
uint64_t length)
: session_(session),
length_(length) {
}
void
HTTPSession::WriteSegment::remove() {
DCHECK(session_);
DCHECK(listHook.is_linked());
listHook.unlink();
}
void
HTTPSession::WriteSegment::detach() {
remove();
session_ = nullptr;
}
void
HTTPSession::WriteSegment::writeSuccess() noexcept {
// Unlink this write segment from the list before calling
// the session's onWriteSuccess() callback because, in the
// case where this is the last write for the connection,
// onWriteSuccess() looks for an empty write segment list
// as one of the criteria for shutting down the connection.
remove();
// session_ should never be nullptr for a successful write
// The session is only cleared after a write error or timeout, and all
// AsyncTransport write failures are fatal. If session_ is nullptr at this
// point it means the AsyncTransport implementation is not failing
// subsequent writes correctly after an error.
session_->onWriteSuccess(length_);
delete this;
}
void
HTTPSession::WriteSegment::writeErr(size_t bytesWritten,
const AsyncSocketException& ex) noexcept {
// After one segment fails to write, we clear the session_
// pointer in all subsequent write segments, so we ignore their
// writeError() callbacks.
if (session_) {
remove();
session_->onWriteError(bytesWritten, ex);
}
delete this;
}
HTTPSession::HTTPSession(
folly::HHWheelTimer* transactionTimeouts,
AsyncTransportWrapper::UniquePtr sock,
const SocketAddress& localAddr,
const SocketAddress& peerAddr,
HTTPSessionController* controller,
unique_ptr<HTTPCodec> codec,
const TransportInfo& tinfo,
InfoCallback* infoCallback):
HTTPSession(WheelTimerInstance(transactionTimeouts), std::move(sock),
localAddr, peerAddr, controller, std::move(codec),
tinfo, infoCallback) {
}
HTTPSession::HTTPSession(
const WheelTimerInstance& timeout,
AsyncTransportWrapper::UniquePtr sock,
const SocketAddress& localAddr,
const SocketAddress& peerAddr,
HTTPSessionController* controller,
unique_ptr<HTTPCodec> codec,
const TransportInfo& tinfo,
InfoCallback* infoCallback):
HTTPSessionBase(localAddr, peerAddr, controller, tinfo, infoCallback,
std::move(codec)),
writeTimeout_(this),
txnEgressQueue_(isHTTP2CodecProtocol(codec_->getProtocol()) ?
WheelTimerInstance(timeout) :
WheelTimerInstance()),
sock_(std::move(sock)),
timeout_(timeout),
draining_(false),
started_(false),
writesDraining_(false),
resetAfterDrainingWrites_(false),
ingressError_(false),
flowControlTimeout_(this),
drainTimeout_(this),
reads_(SocketState::PAUSED),
writes_(SocketState::UNPAUSED),
ingressUpgraded_(false),
resetSocketOnShutdown_(false),
inLoopCallback_(false),
inResume_(false),
pendingPause_(false) {
byteEventTracker_ = std::make_shared<ByteEventTracker>(this);
initialReceiveWindow_ = receiveStreamWindowSize_ =
receiveSessionWindowSize_ = codec_->getDefaultWindowSize();
codec_.add<HTTPChecks>();
setupCodec();
nextEgressResults_.reserve(maxConcurrentIncomingStreams_);
if (infoCallback_) {
infoCallback_->onCreate(*this);
}
auto controllerPtr = getController();
if (controllerPtr) {
flowControlTimeout_.setTimeoutDuration(
controllerPtr->getSessionFlowControlTimeout());
}
attachToSessionController();
if (!sock_->isReplaySafe()) {
sock_->setReplaySafetyCallback(this);
}
}
uint32_t HTTPSession::getCertAuthSettingVal() {
uint32_t certAuthSettingVal = 0;
constexpr uint16_t settingLen = 4;
std::unique_ptr<folly::IOBuf> ekm;
folly::StringPiece label;
if (isUpstream()) {
label = kClientLabel;
} else {
label = kServerLabel;
}
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
ekm = fizzBase->getEkm(label, nullptr, settingLen);
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return certAuthSettingVal;
}
if (ekm && ekm->computeChainDataLength() == settingLen) {
folly::io::Cursor cursor(ekm.get());
uint32_t ekmVal = cursor.readBE<uint32_t>();
certAuthSettingVal = (ekmVal & 0x3fffffff) | 0x80000000;
}
return certAuthSettingVal;
}
bool HTTPSession::verifyCertAuthSetting(uint32_t value) {
uint32_t certAuthSettingVal = 0;
constexpr uint16_t settingLen = 4;
std::unique_ptr<folly::IOBuf> ekm;
folly::StringPiece label;
if (isUpstream()) {
label = kServerLabel;
} else {
label = kClientLabel;
}
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
ekm = fizzBase->getEkm(label, nullptr, settingLen);
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return false;
}
if (ekm && ekm->computeChainDataLength() == settingLen) {
folly::io::Cursor cursor(ekm.get());
uint32_t ekmVal = cursor.readBE<uint32_t>();
certAuthSettingVal = (ekmVal & 0x3fffffff) | 0x80000000;
} else {
return false;
}
if (certAuthSettingVal == value) {
return true;
} else {
return false;
}
}
void HTTPSession::setupCodec() {
if (!codec_->supportsParallelRequests()) {
// until we support upstream pipelining
maxConcurrentIncomingStreams_ = 1;
maxConcurrentOutgoingStreamsRemote_ = isDownstream() ? 0 : 1;
}
// If a secondary authentication manager is configured for this session, set
// the SETTINGS_HTTP_CERT_AUTH to indicate support for HTTP-layer certificate
// authentication.
uint32_t certAuthSettingVal = 0;
if (secondAuthManager_) {
certAuthSettingVal = getCertAuthSettingVal();
}
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS,
maxConcurrentIncomingStreams_);
if (certAuthSettingVal != 0) {
settings->setSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH,
certAuthSettingVal);
}
}
codec_->generateConnectionPreface(writeBuf_);
if (codec_->supportsSessionFlowControl() && !connFlowControl_) {
connFlowControl_ = new FlowControlFilter(*this, writeBuf_, codec_.call());
codec_.addFilters(std::unique_ptr<FlowControlFilter>(connFlowControl_));
// if we really support switching from spdy <-> h2, we need to update
// existing flow control filter
}
codec_.setCallback(this);
}
HTTPSession::~HTTPSession() {
VLOG(4) << *this << " closing";
CHECK(transactions_.empty());
txnEgressQueue_.dropPriorityNodes();
CHECK(txnEgressQueue_.empty());
DCHECK(!sock_->getReadCallback());
if (writeTimeout_.isScheduled()) {
writeTimeout_.cancelTimeout();
}
if (flowControlTimeout_.isScheduled()) {
flowControlTimeout_.cancelTimeout();
}
runDestroyCallbacks();
}
void HTTPSession::startNow() {
CHECK(!started_);
started_ = true;
codec_->generateSettings(writeBuf_);
if (connFlowControl_) {
connFlowControl_->setReceiveWindowSize(writeBuf_,
receiveSessionWindowSize_);
}
// For HTTP/2 if we are currently draining it means we got notified to
// shutdown before we sent a SETTINGS frame, so we defer sending a GOAWAY
// util we've started and sent SETTINGS.
if (draining_) {
codec_->generateGoaway(writeBuf_,
getGracefulGoawayAck(),
ErrorCode::NO_ERROR);
}
scheduleWrite();
resumeReads();
}
void HTTPSession::setByteEventTracker(
std::shared_ptr<ByteEventTracker> byteEventTracker) {
if (byteEventTracker && byteEventTracker_) {
byteEventTracker->absorb(std::move(*byteEventTracker_));
}
byteEventTracker_ = byteEventTracker;
if (byteEventTracker_) {
byteEventTracker_->setCallback(this);
byteEventTracker_->setTTLBAStats(sessionStats_);
}
}
void HTTPSession::setSessionStats(HTTPSessionStats* stats) {
HTTPSessionBase::setSessionStats(stats);
if (byteEventTracker_) {
byteEventTracker_->setTTLBAStats(stats);
}
}
void HTTPSession::setFlowControl(size_t initialReceiveWindow,
size_t receiveStreamWindowSize,
size_t receiveSessionWindowSize) {
CHECK(!started_);
initialReceiveWindow_ = initialReceiveWindow;
receiveStreamWindowSize_ = receiveStreamWindowSize;
receiveSessionWindowSize_ = receiveSessionWindowSize;
HTTPSessionBase::setReadBufferLimit(receiveSessionWindowSize);
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
initialReceiveWindow_);
}
}
void HTTPSession::setEgressSettings(const SettingsList& inSettings) {
VLOG_IF(4, started_) << "Must flush egress settings to peer";
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
for (const auto& setting: inSettings) {
settings->setSetting(setting.id, setting.value);
}
}
}
void HTTPSession::setMaxConcurrentIncomingStreams(uint32_t num) {
CHECK(!started_);
if (codec_->supportsParallelRequests()) {
maxConcurrentIncomingStreams_ = num;
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS,
maxConcurrentIncomingStreams_);
}
}
}
void HTTPSession::setEgressBytesLimit(uint64_t bytesLimit) {
CHECK(!started_);
egressBytesLimit_ = bytesLimit;
}
void
HTTPSession::readTimeoutExpired() noexcept {
VLOG(3) << "session-level timeout on " << *this;
if (liveTransactions_ != 0) {
// There's at least one open transaction with a read timeout scheduled.
// We got here because the session timeout == the transaction timeout.
// Ignore, since the transaction is going to timeout very soon.
VLOG(4) << *this <<
"ignoring session timeout, transaction timeout imminent";
resetTimeout();
return;
}
if (!transactions_.empty()) {
// There are one or more transactions, but none of them are live.
// That's valid if they've all received their full ingress messages
// and are waiting for their Handlers to process those messages.
VLOG(4) << *this <<
"ignoring session timeout, no transactions awaiting reads";
resetTimeout();
return;
}
VLOG(4) << *this << " Timeout with nothing pending";
setCloseReason(ConnectionCloseReason::TIMEOUT);
auto controller = getController();
if (controller) {
timeout_.scheduleTimeout(&drainTimeout_,
controller->getGracefulShutdownTimeout());
}
notifyPendingShutdown();
}
void
HTTPSession::writeTimeoutExpired() noexcept {
VLOG(4) << "Write timeout for " << *this;
CHECK(!pendingWrites_.empty());
DestructorGuard g(this);
setCloseReason(ConnectionCloseReason::TIMEOUT);
shutdownTransportWithReset(kErrorWriteTimeout);
}
void
HTTPSession::flowControlTimeoutExpired() noexcept {
VLOG(4) << "Flow control timeout for " << *this;
DestructorGuard g(this);
setCloseReason(ConnectionCloseReason::TIMEOUT);
shutdownTransport(true, true);
}
void
HTTPSession::describe(std::ostream& os) const {
os << "proto=" << getCodecProtocolString(codec_->getProtocol());
if (isDownstream()) {
os << ", UA=" << codec_->getUserAgent()
<< ", downstream=" << getPeerAddress() << ", " << getLocalAddress()
<< "=local";
} else {
os << ", local=" << getLocalAddress() << ", " << getPeerAddress()
<< "=upstream";
}
}
bool
HTTPSession::isBusy() const {
return !transactions_.empty() || codec_->isBusy();
}
void
HTTPSession::notifyPendingEgress() noexcept {
scheduleWrite();
}
void
HTTPSession::notifyPendingShutdown() {
VLOG(4) << *this << " notified pending shutdown";
drain();
}
void
HTTPSession::closeWhenIdle() {
// If drain() already called, this is a noop
drain();
// Generate the second GOAWAY now. No-op if second GOAWAY already sent.
if (codec_->generateGoaway(writeBuf_,
codec_->getLastIncomingStreamID(),
ErrorCode::NO_ERROR)) {
scheduleWrite();
}
if (!isBusy() && !hasMoreWrites()) {
// if we're already idle, close now
dropConnection();
}
}
void HTTPSession::immediateShutdown() {
if (isLoopCallbackScheduled()) {
cancelLoopCallback();
}
if (shutdownTransportCb_) {
shutdownTransportCb_.reset();
}
// checkForShutdown only closes the connection if these conditions are true
DCHECK(writesShutdown());
DCHECK(transactions_.empty());
checkForShutdown();
}
void
HTTPSession::dropConnection() {
VLOG(4) << "dropping " << *this;
if (!sock_ || (readsShutdown() && writesShutdown())) {
VLOG(4) << *this << " already shutdown";
return;
}
setCloseReason(ConnectionCloseReason::SHUTDOWN);
if (transactions_.empty() && !hasMoreWrites()) {
DestructorGuard dg(this);
shutdownTransport(true, true);
// shutdownTransport might have generated a write (goaway)
// If so, writes will not be shutdown, so fall through to
// shutdownTransportWithReset.
if (readsShutdown() && writesShutdown()) {
immediateShutdown();
return;
}
}
shutdownTransportWithReset(kErrorDropped);
}
void HTTPSession::dumpConnectionState(uint8_t /*loglevel*/) {}
bool HTTPSession::isUpstream() const {
return codec_->getTransportDirection() == TransportDirection::UPSTREAM;
}
bool HTTPSession::isDownstream() const {
return codec_->getTransportDirection() == TransportDirection::DOWNSTREAM;
}
void
HTTPSession::getReadBuffer(void** buf, size_t* bufSize) {
FOLLY_SCOPED_TRACE_SECTION("HTTPSession - getReadBuffer");
pair<void*,uint32_t> readSpace =
readBuf_.preallocate(kMinReadSize, HTTPSessionBase::maxReadBufferSize_);
*buf = readSpace.first;
*bufSize = readSpace.second;
}
void
HTTPSession::readDataAvailable(size_t readSize) noexcept {
FOLLY_SCOPED_TRACE_SECTION(
"HTTPSession - readDataAvailable", "readSize", readSize);
VLOG(10) << "read completed on " << *this << ", bytes=" << readSize;
DestructorGuard dg(this);
resetTimeout();
readBuf_.postallocate(readSize);
if (infoCallback_) {
infoCallback_->onRead(*this, readSize);
}
processReadData();
}
bool
HTTPSession::isBufferMovable() noexcept {
return true;
}
void
HTTPSession::readBufferAvailable(std::unique_ptr<IOBuf> readBuf) noexcept {
size_t readSize = readBuf->computeChainDataLength();
FOLLY_SCOPED_TRACE_SECTION(
"HTTPSession - readBufferAvailable", "readSize", readSize);
VLOG(5) << "read completed on " << *this << ", bytes=" << readSize;
DestructorGuard dg(this);
resetTimeout();
readBuf_.append(std::move(readBuf));
if (infoCallback_) {
infoCallback_->onRead(*this, readSize);
}
processReadData();
}
void
HTTPSession::processReadData() {
FOLLY_SCOPED_TRACE_SECTION("HTTPSession - processReadData");
// skip any empty IOBufs before feeding CODEC.
while (readBuf_.front() != nullptr && readBuf_.front()->length() == 0) {
readBuf_.pop_front();
}
// Pass the ingress data through the codec to parse it. The codec
// will invoke various methods of the HTTPSession as callbacks.
const IOBuf* currentReadBuf;
// It's possible for the last buffer in a chain to be empty here.
// AsyncTransport saw fd activity so asked for a read buffer, but it was
// SSL traffic and not enough to decrypt a whole record. Later we invoke
// this function from the loop callback.
while (!ingressError_ &&
readsUnpaused() &&
((currentReadBuf = readBuf_.front()) != nullptr &&
currentReadBuf->length() != 0)) {
// We're about to parse, make sure the parser is not paused
codec_->setParserPaused(false);
size_t bytesParsed = codec_->onIngress(*currentReadBuf);
if (bytesParsed == 0) {
// If the codec didn't make any progress with current input, we
// better get more.
break;
}
readBuf_.trimStart(bytesParsed);
}
}
void
HTTPSession::readEOF() noexcept {
DestructorGuard guard(this);
VLOG(4) << "EOF on " << *this;
// for SSL only: error without any bytes from the client might happen
// due to client-side issues with the SSL cert. Note that it can also
// happen if the client sends a SPDY frame header but no body.
if (infoCallback_
&& transportInfo_.secure && getNumTxnServed() == 0 && readBuf_.empty()) {
infoCallback_->onIngressError(*this, kErrorClientSilent);
}
// Shut down reads, and also shut down writes if there are no
// transactions. (If there are active transactions, leave the
// write side of the socket open so those transactions can
// finish generating responses.)
setCloseReason(ConnectionCloseReason::READ_EOF);
shutdownTransport(true, transactions_.empty());
}
void
HTTPSession::readErr(const AsyncSocketException& ex) noexcept {
DestructorGuard guard(this);
VLOG(4) << "read error on " << *this << ": " << ex.what();
auto sslEx = dynamic_cast<const folly::SSLException*>(&ex);
if (infoCallback_ && sslEx) {
if (sslEx->getSSLError() == folly::SSLError::CLIENT_RENEGOTIATION) {
infoCallback_->onIngressError(*this, kErrorClientRenegotiation);
}
}
// We're definitely finished reading. Don't close the write side
// of the socket if there are outstanding transactions, though.
// Instead, give the transactions a chance to produce any remaining
// output.
if (sslEx && sslEx->getSSLError() == folly::SSLError::SSL_ERROR) {
transportInfo_.sslError = ex.what();
}
setCloseReason(ConnectionCloseReason::IO_READ_ERROR);
shutdownTransport(true, transactions_.empty(), ex.what());
}
HTTPTransaction*
HTTPSession::newPushedTransaction(
HTTPCodec::StreamID assocStreamId,
HTTPTransaction::PushHandler* handler) noexcept {
if (!codec_->supportsPushTransactions()) {
return nullptr;
}
CHECK(isDownstream());
CHECK_NOTNULL(handler);
if (draining_ || (outgoingStreams_ >= maxConcurrentOutgoingStreamsRemote_)) {
// This session doesn't support any more push transactions
// This could be an actual problem - since a single downstream SPDY session
// might be connected to N upstream hosts, each of which send M pushes,
// which exceeds the limit.
// should we queue?
return nullptr;
}
HTTPTransaction* txn = createTransaction(codec_->createStream(),
assocStreamId,
HTTPCodec::NoExAttributes);
if (!txn) {
return nullptr;
}
DestructorGuard dg(this);
auto txnID = txn->getID();
txn->setHandler(handler);
setNewTransactionPauseState(txnID);
return txn;
}
HTTPTransaction* FOLLY_NULLABLE
HTTPSession::newExTransaction(
HTTPTransaction::Handler* handler,
HTTPCodec::StreamID controlStream,
bool unidirectional) noexcept {
CHECK(handler && controlStream > 0);
auto eSettings = codec_->getEgressSettings();
if (!eSettings || !eSettings->getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
LOG(ERROR) << getCodecProtocolString(codec_->getProtocol())
<< " does not support ExTransaction";
return nullptr;
}
if (draining_ || (outgoingStreams_ >= maxConcurrentOutgoingStreamsRemote_)) {
LOG(ERROR) << "cannot support any more transactions in " << *this;
return nullptr;
}
DCHECK(started_);
HTTPTransaction* txn =
createTransaction(codec_->createStream(),
HTTPCodec::NoStream,
HTTPCodec::ExAttributes(controlStream, unidirectional));
if (!txn) {
return nullptr;
}
DestructorGuard dg(this);
txn->setHandler(handler);
setNewTransactionPauseState(txn->getID());
return txn;
}
size_t HTTPSession::getCodecSendWindowSize() const {
const HTTPSettings* settings = codec_->getIngressSettings();
if (settings) {
return settings->getSetting(SettingsId::INITIAL_WINDOW_SIZE,
codec_->getDefaultWindowSize());
}
return codec_->getDefaultWindowSize();
}
void
HTTPSession::setNewTransactionPauseState(HTTPCodec::StreamID streamID) {
if (!egressLimitExceeded()) {
return;
}
auto txn = findTransaction(streamID);
if (txn) {
// If writes are paused, start this txn off in the egress paused state
VLOG(4) << *this << " starting streamID=" << txn->getID()
<< " egress paused, numActiveWrites_=" << numActiveWrites_;
txn->pauseEgress();
}
}
http2::PriorityUpdate
HTTPSession::getMessagePriority(const HTTPMessage* msg) {
http2::PriorityUpdate h2Pri = http2::DefaultPriority;
// if HTTP2 priorities are enabled, get them from the message
// and ignore otherwise
if (getHTTP2PrioritiesEnabled() && msg) {
auto res = msg->getHTTP2Priority();
if (res) {
h2Pri.streamDependency = std::get<0>(*res);
h2Pri.exclusive = std::get<1>(*res);
h2Pri.weight = std::get<2>(*res);
} else {
// HTTPMessage with setPriority called explicitly
h2Pri.streamDependency =
codec_->mapPriorityToDependency(msg->getPriority());
}
}
return h2Pri;
}
void
HTTPSession::onMessageBegin(HTTPCodec::StreamID streamID, HTTPMessage* msg) {
VLOG(4) << "processing new msg streamID=" << streamID << " " << *this;
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
HTTPTransaction* txn = findTransaction(streamID);
if (txn) {
if (isDownstream() && txn->isPushed()) {
// Push streams are unidirectional (half-closed). If the downstream
// attempts to send ingress, abort with STREAM_CLOSED error.
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
"Downstream attempts to send ingress, abort.");
ex.setCodecStatusCode(ErrorCode::STREAM_CLOSED);
txn->onError(ex);
}
return; // If this transaction is already registered, no need to add it now
}
http2::PriorityUpdate messagePriority = getMessagePriority(msg);
txn = createTransaction(streamID, HTTPCodec::NoStream,
HTTPCodec::NoExAttributes, messagePriority);
if (!txn) {
return; // This could happen if the socket is bad.
}
if (!codec_->supportsParallelRequests() && getPipelineStreamCount() > 1) {
// The previous transaction hasn't completed yet. Pause reads until
// it completes; this requires pausing both transactions.
// HTTP/1.1 pipeline is detected, and which is incompactible with
// ByteEventTracker. Drain all the ByteEvents
CHECK(byteEventTracker_);
byteEventTracker_->drainByteEvents();
// drainByteEvents() may detach txn(s). Don't pause read if one txn left
if (getPipelineStreamCount() < 2) {
DCHECK(readsUnpaused());
return;
}
// There must be at least two transactions (we just checked). The previous
// txns haven't completed yet. Pause reads until they complete
DCHECK_GE(transactions_.size(), 2);
for (auto it = ++transactions_.rbegin(); it != transactions_.rend(); ++it) {
DCHECK(it->second.isIngressEOMSeen());
it->second.pauseIngress();
}
transactions_.rbegin()->second.pauseIngress();
DCHECK_EQ(liveTransactions_, 0);
DCHECK(readsPaused());
}
}
void
HTTPSession::onPushMessageBegin(HTTPCodec::StreamID streamID,
HTTPCodec::StreamID assocStreamID,
HTTPMessage* msg) {
VLOG(4) << "processing new push promise streamID=" << streamID
<< " on assocStreamID=" << assocStreamID << " " << *this;
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
if (assocStreamID == 0) {
VLOG(2) << "push promise " << streamID << " should be associated with "
<< "an active stream=" << assocStreamID << " " << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
if (isDownstream()) {
VLOG(2) << "push promise cannot be sent to upstream " << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
HTTPTransaction* assocTxn = findTransaction(assocStreamID);
if (!assocTxn || assocTxn->isIngressEOMSeen()) {
VLOG(2) << "cannot find the assocTxn=" << assocTxn
<< ", or assoc stream is already closed by upstream" << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
http2::PriorityUpdate messagePriority = getMessagePriority(msg);
auto txn = createTransaction(streamID, assocStreamID,
HTTPCodec::NoExAttributes, messagePriority);
if (!txn) {
return; // This could happen if the socket is bad.
}
if (!assocTxn->onPushedTransaction(txn)) {
VLOG(1) << "Failed to add pushed txn " << streamID
<< " to assoc txn " << assocStreamID << " on " << *this;
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("Failed to add pushed transaction ", streamID));
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
onError(streamID, ex, true);
}
}
void
HTTPSession::onExMessageBegin(HTTPCodec::StreamID streamID,
HTTPCodec::StreamID controlStream,
bool unidirectional,
HTTPMessage* msg) {
VLOG(4) << "processing new ExMessage=" << streamID
<< " on controlStream=" << controlStream << ", " << *this;
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
if (controlStream == 0) {
LOG(ERROR) << "ExMessage=" << streamID << " should have an active control "
<< "stream=" << controlStream << ", " << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
HTTPTransaction* controlTxn = findTransaction(controlStream);
if (!controlTxn) {
// control stream is broken, or remote sends a bogus stream id
LOG(ERROR) << "no control stream=" << controlStream << ", " << *this;
return;
}
http2::PriorityUpdate messagePriority = getMessagePriority(msg);
auto txn = createTransaction(streamID,
HTTPCodec::NoStream,
HTTPCodec::ExAttributes(controlStream,
unidirectional),
messagePriority);
if (!txn) {
return; // This could happen if the socket is bad.
}
// control stream may be paused if the upstream is not ready yet
if (controlTxn->isIngressPaused()) {
txn->pauseIngress();
}
}
void
HTTPSession::onHeadersComplete(HTTPCodec::StreamID streamID,
unique_ptr<HTTPMessage> msg) {
// The codec's parser detected the end of an ingress message's
// headers.
VLOG(4) << "processing ingress headers complete for " << *this <<
", streamID=" << streamID;
if (!codec_->isReusable()) {
setCloseReason(ConnectionCloseReason::REQ_NOTREUSABLE);
}
if (infoCallback_) {
infoCallback_->onIngressMessage(*this, *msg.get());
}
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
const char* sslCipher =
transportInfo_.sslCipher ? transportInfo_.sslCipher->c_str() : nullptr;
msg->setSecureInfo(transportInfo_.sslVersion, sslCipher);
msg->setSecure(transportInfo_.secure);
auto controlStreamID = txn->getControlStream();
if (controlStreamID) {
auto controlTxn = findTransaction(*controlStreamID);
if (!controlTxn) {
VLOG(2) << "txn=" << streamID << " with a broken controlTxn="
<< *controlStreamID << " " << *this;
HTTPException ex(
HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("broken controlTxn ", *controlStreamID));
onError(streamID, ex, true);
return;
}
// Call onExTransaction() only for requests.
if (txn->isRemoteInitiated() && !controlTxn->onExTransaction(txn)) {
VLOG(2) << "Failed to add exTxn=" << streamID
<< " to controlTxn=" << *controlStreamID << ", " << *this;
HTTPException ex(
HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("Fail to add exTxn ", streamID));
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
onError(streamID, ex, true);
return;
}
} else {
setupOnHeadersComplete(txn, msg.get());
}
// The txn may have already been aborted by the handler.
// Verify that the txn still exists before ingress callbacks.
txn = findTransaction(streamID);
if (!txn) {
return;
}
if (!txn->getHandler()) {
txn->sendAbort();
return;
}
// Tell the Transaction to start processing the message now
// that the full ingress headers have arrived.
txn->onIngressHeadersComplete(std::move(msg));
}
void
HTTPSession::onBody(HTTPCodec::StreamID streamID,
unique_ptr<IOBuf> chain, uint16_t padding) {
FOLLY_SCOPED_TRACE_SECTION("HTTPSession - onBody");
DestructorGuard dg(this);
// The codec's parser detected part of the ingress message's
// entity-body.
uint64_t length = chain->computeChainDataLength();
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
if (connFlowControl_ &&
connFlowControl_->ingressBytesProcessed(writeBuf_, length)) {
scheduleWrite();
}
invalidStream(streamID);
return;
}
if (HTTPSessionBase::onBodyImpl(std::move(chain), length, padding, txn)) {
VLOG(4) << *this << " pausing due to read limit exceeded.";
pauseReads();
}
}
void HTTPSession::onChunkHeader(HTTPCodec::StreamID streamID,
size_t length) {
// The codec's parser detected a chunk header (meaning that this
// connection probably is HTTP/1.1).
//
// After calling onChunkHeader(), the codec will call onBody() zero
// or more times and then call onChunkComplete().
//
// The reason for this callback on the chunk header is to support
// an optimization. In general, the job of the codec is to present
// the HTTPSession with an abstract view of a message,
// with all the details of wire formatting hidden. However, there's
// one important case where we want to know about chunking: reverse
// proxying where both the client and server streams are HTTP/1.1.
// In that scenario, we preserve the server's chunk boundaries when
// sending the response to the client, in order to avoid possibly
// making the egress packetization worse by rechunking.
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
txn->onIngressChunkHeader(length);
}
void HTTPSession::onChunkComplete(HTTPCodec::StreamID streamID) {
// The codec's parser detected the end of the message body chunk
// associated with the most recent call to onChunkHeader().
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
txn->onIngressChunkComplete();
}
void
HTTPSession::onTrailersComplete(HTTPCodec::StreamID streamID,
unique_ptr<HTTPHeaders> trailers) {
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
txn->onIngressTrailers(std::move(trailers));
}
void
HTTPSession::onMessageComplete(HTTPCodec::StreamID streamID,
bool upgrade) {
DestructorGuard dg(this);
// The codec's parser detected the end of the ingress message for
// this transaction.
VLOG(4) << "processing ingress message complete for " << *this <<
", streamID=" << streamID;
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
if (upgrade) {
/* Send the upgrade callback to the transaction and the handler.
* Currently we support upgrades for only HTTP sessions and not SPDY
* sessions.
*/
ingressUpgraded_ = true;
txn->onIngressUpgrade(UpgradeProtocol::TCP);
return;
}
// txnIngressFinished = !1xx response
const bool txnIngressFinished =
txn->isDownstream() || !txn->extraResponseExpected();
if (txnIngressFinished) {
decrementTransactionCount(txn, true, false);
}
txn->onIngressEOM();
// The codec knows, based on the semantics of whatever protocol it
// supports, whether it's valid for any more ingress messages to arrive
// after this one. For example, an HTTP/1.1 request containing
// "Connection: close" indicates the end of the ingress, whereas a
// SPDY session generally can handle more messages at any time.
//
// If the connection is not reusable, we close the read side of it
// but not the write side. There are two reasons why more writes
// may occur after this point:
// * If there are previous writes buffered up in the pendingWrites_
// queue, we need to attempt to complete them.
// * The Handler associated with the transaction may want to
// produce more egress data when the ingress message is fully
// complete. (As a common example, an application that handles
// form POSTs may not be able to even start generating a response
// until it has received the full request body.)
//
// There may be additional checks that need to be performed that are
// specific to requests or responses, so we call the subclass too.
if (!codec_->isReusable() &&
txnIngressFinished &&
!codec_->supportsParallelRequests()) {
VLOG(4) << *this << " cannot reuse ingress";
shutdownTransport(true, false);
}
}
void HTTPSession::onError(HTTPCodec::StreamID streamID,
const HTTPException& error, bool newTxn) {
DestructorGuard dg(this);
// The codec detected an error in the ingress stream, possibly bad
// syntax, a truncated message, or bad semantics in the frame. If reads
// are paused, queue up the event; otherwise, process it now.
VLOG(4) << "Error on " << *this << ", streamID=" << streamID
<< ", " << error;
if (ingressError_) {
return;
}
if (!codec_->supportsParallelRequests()) {
// this error should only prevent us from reading/handling more errors
// on serial streams
ingressError_ = true;
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
}
if ((streamID == 0) && infoCallback_) {
infoCallback_->onIngressError(*this, kErrorMessage);
}
if (!streamID) {
ingressError_ = true;
onSessionParseError(error);
return;
}
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
if (error.hasHttpStatusCode() && streamID != 0) {
// If the error has an HTTP code, then parsing was fine, it just was
// illegal in a higher level way
txn = createTransaction(streamID, HTTPCodec::NoStream,
HTTPCodec::NoExAttributes);
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
if (txn) {
handleErrorDirectly(txn, error);
}
} else if (newTxn) {
onNewTransactionParseError(streamID, error);
} else {
VLOG(4) << *this << " parse error with invalid transaction";
invalidStream(streamID);
}
return;
}
if (!txn->getHandler() &&
txn->getEgressState() == HTTPTransactionEgressSM::State::Start) {
handleErrorDirectly(txn, error);
return;
}
txn->onError(error);
if (!codec_->isReusable() && transactions_.empty()) {
VLOG(4) << *this << "shutdown from onError";
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
shutdownTransport(true, true);
}
}
void HTTPSession::onAbort(HTTPCodec::StreamID streamID,
ErrorCode code) {
VLOG(4) << "stream abort on " << *this << ", streamID=" << streamID
<< ", code=" << getErrorCodeString(code);
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
VLOG(4) << *this << " abort for unrecognized transaction, streamID= "
<< streamID;
return;
}
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("Stream aborted, streamID=",
streamID, ", code=", getErrorCodeString(code)));
ex.setProxygenError(kErrorStreamAbort);
ex.setCodecStatusCode(code);
DestructorGuard dg(this);
if (isDownstream() && !txn->getAssocTxnId() && code == ErrorCode::CANCEL) {
// Cancelling the assoc txn cancels all push txns
for (auto it = txn->getPushedTransactions().begin();
it != txn->getPushedTransactions().end(); ) {
auto pushTxn = findTransaction(*it);
++it;
DCHECK(pushTxn != nullptr);
pushTxn->onError(ex);
}
}
auto exTxns = txn->getExTransactions();
for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
auto exTxn = findTransaction(*it);
if (exTxn) {
exTxn->onError(ex);
}
}
txn->onError(ex);
}
void HTTPSession::onGoaway(uint64_t lastGoodStreamID,
ErrorCode code,
std::unique_ptr<folly::IOBuf> debugData) {
DestructorGuard g(this);
VLOG(4) << "GOAWAY on " << *this << ", code=" << getErrorCodeString(code);
setCloseReason(ConnectionCloseReason::GOAWAY);
// Drain active transactions and prevent new transactions
drain();
// We give the less-forceful onGoaway() first so that transactions have
// a chance to do stat tracking before potentially getting a forceful
// onError().
invokeOnAllTransactions(&HTTPTransaction::onGoaway, code);
// Abort transactions which have been initiated but not created
// successfully at the remote end. Upstream transactions are created
// with odd transaction IDs and downstream transactions with even IDs.
vector<HTTPCodec::StreamID> ids;
auto firstStream = HTTPCodec::NoStream;
for (const auto& txn: transactions_) {
auto streamID = txn.first;
if (((bool)(streamID & 0x01) == isUpstream()) &&
(streamID > lastGoodStreamID)) {
if (firstStream == HTTPCodec::NoStream) {
// transactions_ is a set so it should be sorted by stream id.
// We will defer adding the firstStream to the id list until
// we can determine whether we have a codec error code.
firstStream = streamID;
continue;
}
ids.push_back(streamID);
}
}
if (firstStream != HTTPCodec::NoStream && code != ErrorCode::NO_ERROR) {
// If we get a codec error, we will attempt to blame the first stream
// by delivering a specific error to it and let the rest of the streams
// get a normal unacknowledged stream error.
ProxygenError err = kErrorStreamUnacknowledged;
string debugInfo = (debugData) ?
folly::to<string>(" with debug info: ", (char*)debugData->data()) : "";
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>(getErrorString(err),
" on transaction id: ", *firstStream,
" with codec error: ", getErrorCodeString(code),
debugInfo));
ex.setProxygenError(err);
errorOnTransactionId(*firstStream, std::move(ex));
} else if (firstStream != HTTPCodec::NoStream) {
ids.push_back(*firstStream);
}
errorOnTransactionIds(ids, kErrorStreamUnacknowledged);
}
void HTTPSession::onPingRequest(uint64_t uniqueID) {
VLOG(4) << *this << " got ping request with id=" << uniqueID;
TimePoint timestamp = getCurrentTime();
// Insert the ping reply to the head of writeBuf_
folly::IOBufQueue pingBuf(folly::IOBufQueue::cacheChainLength());
codec_->generatePingReply(pingBuf, uniqueID);
size_t pingSize = pingBuf.chainLength();
pingBuf.append(writeBuf_.move());
writeBuf_.append(pingBuf.move());
if (byteEventTracker_) {
byteEventTracker_->addPingByteEvent(pingSize, timestamp, bytesScheduled_);
}
scheduleWrite();
}
void HTTPSession::onPingReply(uint64_t uniqueID) {
VLOG(4) << *this << " got ping reply with id=" << uniqueID;
if (infoCallback_) {
infoCallback_->onPingReplyReceived();
}
}
void HTTPSession::onWindowUpdate(HTTPCodec::StreamID streamID,
uint32_t amount) {
VLOG(4) << *this << " got window update on streamID=" << streamID << " for "
<< amount << " bytes.";
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
// We MUST be using SPDY/3+ if we got WINDOW_UPDATE. The spec says that -
//
// A sender should ignore all the WINDOW_UPDATE frames associated with the
// stream after it send the last frame for the stream.
//
// TODO: Only ignore if this is from some past transaction
return;
}
txn->onIngressWindowUpdate(amount);
}
void HTTPSession::onSettings(const SettingsList& settings) {
DestructorGuard g(this);
for (auto& setting : settings) {
if (setting.id == SettingsId::INITIAL_WINDOW_SIZE) {
onSetSendWindow(setting.value);
} else if (setting.id == SettingsId::MAX_CONCURRENT_STREAMS) {
onSetMaxInitiatedStreams(setting.value);
} else if (setting.id == SettingsId::SETTINGS_HTTP_CERT_AUTH) {
if (!(verifyCertAuthSetting(setting.value))) {
return;
}
}
}
if (codec_->generateSettingsAck(writeBuf_) > 0) {
scheduleWrite();
}
if (infoCallback_) {
infoCallback_->onSettings(*this, settings);
}
}
void HTTPSession::onSettingsAck() {
VLOG(4) << *this << " received settings ack";
if (infoCallback_) {
infoCallback_->onSettingsAck(*this);
}
}
void HTTPSession::onPriority(HTTPCodec::StreamID streamID,
const HTTPMessage::HTTPPriority& pri) {
if (!getHTTP2PrioritiesEnabled()) {
return;
}
http2::PriorityUpdate h2Pri{std::get<0>(pri), std::get<1>(pri),
std::get<2>(pri)};
HTTPTransaction* txn = findTransaction(streamID);
if (txn) {
// existing txn, change pri
txn->onPriorityUpdate(h2Pri);
} else {
// virtual node
txnEgressQueue_.addOrUpdatePriorityNode(streamID, h2Pri);
}
}
void HTTPSession::onCertificateRequest(uint16_t requestId,
std::unique_ptr<IOBuf> authRequest) {
DestructorGuard dg(this);
VLOG(4) << "CERTIFICATE_REQUEST on" << *this << ", requestId=" << requestId;
if (!secondAuthManager_) {
return;
}
std::pair<uint16_t, std::unique_ptr<folly::IOBuf>> authenticator;
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
if (isUpstream()) {
authenticator =
secondAuthManager_->getAuthenticator(*fizzBase,
TransportDirection::UPSTREAM,
requestId,
std::move(authRequest));
} else {
authenticator =
secondAuthManager_->getAuthenticator(*fizzBase,
TransportDirection::DOWNSTREAM,
requestId,
std::move(authRequest));
}
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return;
}
if (codec_->generateCertificate(writeBuf_,
authenticator.first,
std::move(authenticator.second)) > 0) {
scheduleWrite();
}
}
void HTTPSession::onCertificate(uint16_t certId,
std::unique_ptr<IOBuf> authenticator) {
DestructorGuard dg(this);
VLOG(4) << "CERTIFICATE on" << *this << ", certId=" << certId;
if (!secondAuthManager_) {
return;
}
bool isValid = false;
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
if (isUpstream()) {
isValid = secondAuthManager_->validateAuthenticator(
*fizzBase,
TransportDirection::UPSTREAM,
certId,
std::move(authenticator));
} else {
isValid = secondAuthManager_->validateAuthenticator(
*fizzBase,
TransportDirection::DOWNSTREAM,
certId,
std::move(authenticator));
}
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return;
}
if (isValid) {
VLOG(4) << "Successfully validated the authenticator provided by the peer.";
} else {
VLOG(4) << "Failed to validate the authenticator provided by the peer";
}
}
bool HTTPSession::onNativeProtocolUpgradeImpl(
HTTPCodec::StreamID streamID, std::unique_ptr<HTTPCodec> codec,
const std::string& protocolString) {
CHECK_EQ(streamID, 1);
HTTPTransaction* txn = findTransaction(streamID);
CHECK(txn);
// only HTTP1xCodec calls onNativeProtocolUpgrade
CHECK(!codec_->supportsParallelRequests());
// Reset to defaults
maxConcurrentIncomingStreams_ = 100;
maxConcurrentOutgoingStreamsRemote_ = 10000;
// overwrite destination, delay current codec deletion until the end
// of the event loop
auto oldCodec = codec_.setDestination(std::move(codec));
sock_->getEventBase()->runInLoop([oldCodec = std::move(oldCodec)] () {});
onCodecChanged();
setupCodec();
// txn will be streamID=1, have to make a placeholder
(void)codec_->createStream();
// This can happen if flow control was not explicitly set, and it got the
// HTTP1xCodec defaults. Reset to the new codec default
if (initialReceiveWindow_ == 0 || receiveStreamWindowSize_ == 0 ||
receiveSessionWindowSize_ == 0) {
initialReceiveWindow_ = receiveStreamWindowSize_ =
receiveSessionWindowSize_ = codec_->getDefaultWindowSize();
}
// trigger settings frame that would have gone out in startNow()
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
initialReceiveWindow_);
}
sendSettings();
if (connFlowControl_) {
connFlowControl_->setReceiveWindowSize(writeBuf_,
receiveSessionWindowSize_);
scheduleWrite();
}
// Convert the transaction that contained the Upgrade header
txn->reset(codec_->supportsStreamFlowControl(),
initialReceiveWindow_,
receiveStreamWindowSize_,
getCodecSendWindowSize());
if (!transportInfo_.secure &&
(!transportInfo_.appProtocol ||
transportInfo_.appProtocol->empty())) {
transportInfo_.appProtocol = std::make_shared<string>(
protocolString);
}
return true;
}
void HTTPSession::onSetSendWindow(uint32_t windowSize) {
VLOG(4) << *this << " got send window size adjustment. new=" << windowSize;
invokeOnAllTransactions(&HTTPTransaction::onIngressSetSendWindow,
windowSize);
}
void HTTPSession::onSetMaxInitiatedStreams(uint32_t maxTxns) {
VLOG(4) << *this << " got new maximum number of concurrent txns "
<< "we can initiate: " << maxTxns;
const bool didSupport = supportsMoreTransactions();
maxConcurrentOutgoingStreamsRemote_ = maxTxns;
if (infoCallback_ && didSupport != supportsMoreTransactions()) {
if (didSupport) {
infoCallback_->onSettingsOutgoingStreamsFull(*this);
} else {
infoCallback_->onSettingsOutgoingStreamsNotFull(*this);
}
}
}
size_t HTTPSession::sendSettings() {
size_t size = codec_->generateSettings(writeBuf_);
scheduleWrite();
return size;
}
void HTTPSession::pauseIngress(HTTPTransaction* txn) noexcept {
VLOG(4) << *this << " pausing streamID=" << txn->getID() <<
", liveTransactions_ was " << liveTransactions_;
CHECK_GT(liveTransactions_, 0);
--liveTransactions_;
auto exTxns = txn->getExTransactions();
for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
auto exTxn = findTransaction(*it);
if (exTxn) {
exTxn->pauseIngress();
}
}
if (liveTransactions_ == 0) {
pauseReads();
}
}
void HTTPSession::resumeIngress(HTTPTransaction* txn) noexcept {
VLOG(4) << *this << " resuming streamID=" << txn->getID() <<
", liveTransactions_ was " << liveTransactions_;
++liveTransactions_;
auto exTxns = txn->getExTransactions();
for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
auto exTxn = findTransaction(*it);
if (exTxn) {
exTxn->resumeIngress();
}
}
if (liveTransactions_ == 1) {
resumeReads();
}
}
void
HTTPSession::transactionTimeout(HTTPTransaction* txn) noexcept {
// A transaction has timed out. If the transaction does not have
// a Handler yet, because we haven't yet received the full request
// headers, we give it a DirectResponseHandler that generates an
// error page.
VLOG(3) << "Transaction timeout for streamID=" << txn->getID();
if (!codec_->supportsParallelRequests()) {
// this error should only prevent us from reading/handling more errors
// on serial streams
ingressError_ = true;
}
if (!txn->getHandler() &&
txn->getEgressState() == HTTPTransactionEgressSM::State::Start) {
VLOG(4) << *this << " Timed out receiving headers";
if (infoCallback_) {
infoCallback_->onIngressError(*this, kErrorTimeout);
}
if (codec_->supportsParallelRequests()) {
// This can only happen with HTTP/2 where the HEADERS frame is incomplete
// and we time out waiting for the CONTINUATION. Abort the request.
//
// It would maybe be a little nicer to use the timeout handler for these
// also.
txn->sendAbort();
return;
}
VLOG(4) << *this << " creating direct error handler";
auto handler = getTransactionTimeoutHandler(txn);
txn->setHandler(handler);
}
// Tell the transaction about the timeout. The transaction will
// communicate the timeout to the handler, and the handler will
// decide how to proceed.
txn->onIngressTimeout();
}
void HTTPSession::sendHeaders(HTTPTransaction* txn,
const HTTPMessage& headers,
HTTPHeaderSize* size,
bool includeEOM) noexcept {
CHECK(started_);
unique_ptr<IOBuf> goawayBuf;
if (shouldShutdown()) {
// For HTTP/1.1, add Connection: close
// For SPDY, save the goaway for AFTER the request
auto writeBuf = writeBuf_.move();
drainImpl();
goawayBuf = writeBuf_.move();
writeBuf_.append(std::move(writeBuf));
}
if (isUpstream() || (txn->isPushed() && headers.isRequest())) {
// upstream picks priority
if (getHTTP2PrioritiesEnabled()) {
auto pri = getMessagePriority(&headers);
txn->onPriorityUpdate(pri);
}
}
const bool wasReusable = codec_->isReusable();
const uint64_t oldOffset = sessionByteOffset();
auto exAttributes = txn->getExAttributes();
auto assocStream = txn->getAssocTxnId();
if (exAttributes) {
codec_->generateExHeader(writeBuf_,
txn->getID(),
headers,
*exAttributes,
includeEOM,
size);
} else if (headers.isRequest() && assocStream) {
// Only PUSH_PROMISE (not push response) has an associated stream
codec_->generatePushPromise(writeBuf_,
txn->getID(),
headers,
*assocStream,
includeEOM,
size);
} else {
codec_->generateHeader(writeBuf_,
txn->getID(),
headers,
includeEOM,
size);
}
const uint64_t newOffset = sessionByteOffset();
// for push response count towards the MAX_CONCURRENT_STREAMS limit
if (isDownstream() && headers.isResponse() && txn->isPushed()) {
incrementOutgoingStreams();
}
// For all upstream headers, addFirstHeaderByteEvent should be added
// For all downstream, only response headers need addFirstHeaderByteEvent
bool shouldAddFirstHeaderByteEvent = isUpstream() ||
(isDownstream() && headers.isResponse());
if (shouldAddFirstHeaderByteEvent && newOffset > oldOffset &&
!txn->testAndSetFirstHeaderByteSent() && byteEventTracker_) {
byteEventTracker_->addFirstHeaderByteEvent(newOffset, txn);
}
if (size) {
VLOG(4) << *this << " sending headers, size=" << size->compressed
<< ", uncompressedSize=" << size->uncompressed;
}
if (goawayBuf) {
VLOG(4) << *this << " moved GOAWAY to end of writeBuf";
writeBuf_.append(std::move(goawayBuf));
}
if (includeEOM) {
commonEom(txn, 0, true);
}
scheduleWrite();
onHeadersSent(headers, wasReusable);
}
void
HTTPSession::commonEom(
HTTPTransaction* txn,
size_t encodedSize,
bool piggybacked) noexcept {
HTTPSessionBase::handleLastByteEvents(
byteEventTracker_.get(), txn, encodedSize, sessionByteOffset(),
piggybacked);
onEgressMessageFinished(txn);
}
size_t
HTTPSession::sendBody(HTTPTransaction* txn,
std::unique_ptr<folly::IOBuf> body,
bool includeEOM,
bool trackLastByteFlushed) noexcept {
uint64_t offset = sessionByteOffset();
size_t bodyLen = body ? body->computeChainDataLength(): 0;
size_t encodedSize = codec_->generateBody(writeBuf_,
txn->getID(),
std::move(body),
HTTPCodec::NoPadding,
includeEOM);
CHECK(inLoopCallback_);
pendingWriteSizeDelta_ -= bodyLen;
bodyBytesPerWriteBuf_ += bodyLen;
if (encodedSize > 0 && !txn->testAndSetFirstByteSent() && byteEventTracker_) {
byteEventTracker_->addFirstBodyByteEvent(offset, txn);
}
if (trackLastByteFlushed && encodedSize > 0 && byteEventTracker_) {
byteEventTracker_->addTrackedByteEvent(txn, offset + encodedSize);
}
if (includeEOM) {
VLOG(5) << *this << " sending EOM in body for streamID=" << txn->getID();
commonEom(txn, encodedSize, true);
}
return encodedSize;
}
size_t HTTPSession::sendChunkHeader(HTTPTransaction* txn,
size_t length) noexcept {
size_t encodedSize = codec_->generateChunkHeader(writeBuf_,
txn->getID(),
length);
scheduleWrite();
return encodedSize;
}
size_t HTTPSession::sendChunkTerminator(
HTTPTransaction* txn) noexcept {
size_t encodedSize = codec_->generateChunkTerminator(writeBuf_,
txn->getID());
scheduleWrite();
return encodedSize;
}
void
HTTPSession::onEgressMessageFinished(HTTPTransaction* txn, bool withRST) {
// If the semantics of the protocol don't permit more messages
// to be read or sent on this connection, close the socket in one or
// more directions.
CHECK(!transactions_.empty());
if (infoCallback_) {
infoCallback_->onRequestEnd(*this, txn->getMaxDeferredSize());
}
auto oldStreamCount = getPipelineStreamCount();
decrementTransactionCount(txn, false, true);
if (withRST || ((!codec_->isReusable() || readsShutdown()) &&
transactions_.size() == 1)) {
// We should shutdown reads if we are closing with RST or we aren't
// interested in any further messages (ie if we are a downstream session).
// Upgraded sessions have independent ingress and egress, and the reads
// need not be shutdown on egress finish.
if (withRST) {
// Let any queued writes complete, but send a RST when done.
VLOG(4) << *this << " resetting egress after this message";
resetAfterDrainingWrites_ = true;
setCloseReason(ConnectionCloseReason::TRANSACTION_ABORT);
shutdownTransport(true, true);
} else {
// the reason is already set (either not reusable or readshutdown).
// Defer normal shutdowns until the end of the loop. This
// handles an edge case with direct responses with Connection:
// close served before ingress EOM. The remainder of the ingress
// message may be in the parse loop, so give it a chance to
// finish out and avoid a kErrorEOF
// we can get here during shutdown, in that case do not schedule a
// shutdown callback again
if (!shutdownTransportCb_) {
// Just for safety, the following bumps the refcount on this session
// to keep it live until the loopCb runs
shutdownTransportCb_.reset(new ShutdownTransportCallback(this));
sock_->getEventBase()->runInLoop(shutdownTransportCb_.get(), true);
}
}
} else {
maybeResumePausedPipelinedTransaction(oldStreamCount,
txn->getSequenceNumber());
}
}
size_t HTTPSession::sendEOM(HTTPTransaction* txn,
const HTTPHeaders* trailers) noexcept {
VLOG(4) << *this << " sending EOM for streamID=" << txn->getID()
<< " trailers=" << (trailers ? "yes" : "no");
size_t encodedSize = 0;
if (trailers) {
encodedSize = codec_->generateTrailers(writeBuf_, txn->getID(), *trailers);
}
// Don't send EOM for HTTP2, when trailers sent.
// sendTrailers already flagged end of stream.
bool http2Trailers = trailers && isHTTP2CodecProtocol(codec_->getProtocol());
if (!http2Trailers) {
encodedSize += codec_->generateEOM(writeBuf_, txn->getID());
}
commonEom(txn, encodedSize, false);
return encodedSize;
}
size_t HTTPSession::sendAbort(HTTPTransaction* txn,
ErrorCode statusCode) noexcept {
// Ask the codec to generate an abort indicator for the transaction.
// Depending on the protocol, this may be a no-op.
// Schedule a network write to send out whatever egress we might
// have queued up.
VLOG(4) << *this << " sending abort for streamID=" << txn->getID();
// drain this transaction's writeBuf instead of flushing it
// then enqueue the abort directly into the Session buffer,
// hence with max priority.
size_t encodedSize = codec_->generateRstStream(writeBuf_,
txn->getID(),
statusCode);
if (!codec_->isReusable()) {
// HTTP 1x codec does not support per stream abort so this will
// render the codec not reusable
setCloseReason(ConnectionCloseReason::TRANSACTION_ABORT);
}
scheduleWrite();
// If the codec wasn't able to write a L7 message for the abort, then
// fall back to closing the transport with a TCP level RST
onEgressMessageFinished(txn, !encodedSize);
return encodedSize;
}
size_t HTTPSession::sendPriority(HTTPTransaction* txn,
const http2::PriorityUpdate& pri) noexcept {
return sendPriorityImpl(txn->getID(), pri);
}
void HTTPSession::setSecondAuthManager(
std::unique_ptr<SecondaryAuthManager> secondAuthManager) {
secondAuthManager_ = std::move(secondAuthManager);
}
SecondaryAuthManager* HTTPSession::getSecondAuthManager() const {
return secondAuthManager_.get();
}
/**
* Send a CERTIFICATE_REQUEST frame. If the underlying protocol doesn't
* support secondary authentication, this is a no-op and 0 is returned.
*/
size_t HTTPSession::sendCertificateRequest(
std::unique_ptr<folly::IOBuf> certificateRequestContext,
std::vector<fizz::Extension> extensions) {
// Check if both sending and receiving peer have advertised valid
// SETTINGS_HTTP_CERT_AUTH setting. Otherwise, the frames for secondary
// authentication should not be sent.
auto ingressSettings = codec_->getIngressSettings();
auto egressSettings = codec_->getEgressSettings();
if (ingressSettings && egressSettings) {
if (ingressSettings->getSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH, 0) ==
0 ||
egressSettings->getSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH, 0) ==
0) {
VLOG(4) << "Secondary certificate authentication is not supported.";
return 0;
}
}
auto authRequest = secondAuthManager_->createAuthRequest(
std::move(certificateRequestContext), std::move(extensions));
auto encodedSize = codec_->generateCertificateRequest(
writeBuf_, authRequest.first, std::move(authRequest.second));
if (encodedSize > 0) {
scheduleWrite();
} else {
VLOG(4) << "Failed to generate CERTIFICATE_REQUEST frame.";
}
return encodedSize;
}
void HTTPSession::decrementTransactionCount(HTTPTransaction* txn,
bool ingressEOM,
bool egressEOM) {
if ((isUpstream() && !txn->isPushed()) ||
(isDownstream() && txn->isPushed())) {
if (ingressEOM && txn->testAndClearActive()) {
outgoingStreams_--;
}
} else {
if (egressEOM && txn->testAndClearActive()) {
incomingStreams_--;
}
}
}
// This is a kludgy function because it requires the caller to remember
// the old value of pipelineStreamCount from before it calls
// decrementTransactionCount. I'm trying to avoid yet more state in
// HTTPSession. If decrementTransactionCount actually closed a stream
// and there is still a pipelinable stream, then it was pipelining
bool
HTTPSession::maybeResumePausedPipelinedTransaction(
size_t oldStreamCount, uint32_t txnSeqn) {
if (!codec_->supportsParallelRequests() && !transactions_.empty() &&
getPipelineStreamCount() < oldStreamCount &&
getPipelineStreamCount() == 1) {
auto& nextTxn = transactions_.rbegin()->second;
DCHECK_EQ(nextTxn.getSequenceNumber(), txnSeqn + 1);
DCHECK(!nextTxn.isIngressComplete());
DCHECK(nextTxn.isIngressPaused());
VLOG(4) << "Resuming paused pipelined txn " << nextTxn;
nextTxn.resumeIngress();
return true;
}
return false;
}
void
HTTPSession::detach(HTTPTransaction* txn) noexcept {
DestructorGuard guard(this);
HTTPCodec::StreamID streamID = txn->getID();
auto txnSeqn = txn->getSequenceNumber();
auto it = transactions_.find(txn->getID());
DCHECK(it != transactions_.end());
if (txn->isIngressPaused()) {
// Someone detached a transaction that was paused. Make the resumeIngress
// call to keep liveTransactions_ in order
VLOG(4) << *this << " detached paused transaction=" << streamID;
resumeIngress(txn);
}
VLOG(4) << *this << " removing streamID=" << streamID <<
", liveTransactions was " << liveTransactions_;
CHECK_GT(liveTransactions_, 0);
liveTransactions_--;
if (txn->isPushed()) {
auto assocTxn = findTransaction(*txn->getAssocTxnId());
if (assocTxn) {
assocTxn->removePushedTransaction(streamID);
}
}
if (txn->getControlStream()) {
auto controlTxn = findTransaction(*txn->getControlStream());
if (controlTxn) {
controlTxn->removeExTransaction(streamID);
}
}
auto oldStreamCount = getPipelineStreamCount();
decrementTransactionCount(txn, true, true);
transactions_.erase(it);
if (transactions_.empty()) {
HTTPSessionBase::setLatestActive();
if (infoCallback_) {
infoCallback_->onDeactivateConnection(*this);
}
if (getConnectionManager()) {
getConnectionManager()->onDeactivated(*this);
}
} else {
if (infoCallback_) {
infoCallback_->onTransactionDetached(*this);
}
}
if (!readsShutdown()) {
if (maybeResumePausedPipelinedTransaction(oldStreamCount, txnSeqn)) {
return;
} else {
// this will resume reads if they were paused (eg: 0 HTTP transactions)
resumeReads();
}
}
if (liveTransactions_ == 0 && transactions_.empty() && !isScheduled()) {
resetTimeout();
}
// It's possible that this is the last transaction in the session,
// so check whether the conditions for shutdown are satisfied.
if (transactions_.empty()) {
if (shouldShutdown()) {
writesDraining_ = true;
}
// Handle the case where we are draining writes but all remaining
// transactions terminated with no egress.
if (writesDraining_ && !writesShutdown() && !hasMoreWrites()) {
shutdownTransport(false, true);
return;
}
}
checkForShutdown();
}
size_t
HTTPSession::sendWindowUpdate(HTTPTransaction* txn,
uint32_t bytes) noexcept {
size_t sent = codec_->generateWindowUpdate(writeBuf_, txn->getID(), bytes);
if (sent) {
scheduleWrite();
}
return sent;
}
void
HTTPSession::notifyIngressBodyProcessed(uint32_t bytes) noexcept {
if (HTTPSessionBase::notifyBodyProcessed(bytes)) {
resumeReads();
}
if (connFlowControl_ &&
connFlowControl_->ingressBytesProcessed(writeBuf_, bytes)) {
scheduleWrite();
}
}
void
HTTPSession::notifyEgressBodyBuffered(int64_t bytes) noexcept {
pendingWriteSizeDelta_ += bytes;
// any net change requires us to update pause/resume state in the
// loop callback
if (pendingWriteSizeDelta_ > 0) {
// pause inline, resume in loop
updateWriteBufSize(0);
} else if (!isLoopCallbackScheduled()) {
sock_->getEventBase()->runInLoop(this);
}
}
bool HTTPSession::getCurrentTransportInfoWithoutUpdate(
TransportInfo* tinfo) const {
auto sock = sock_->getUnderlyingTransport<AsyncSocket>();
if (sock) {
tinfo->initWithSocket(sock);
return true;
}
return false;
}
bool HTTPSession::getCurrentTransportInfo(TransportInfo* tinfo) {
if (getCurrentTransportInfoWithoutUpdate(tinfo)) {
// some fields are the same with the setup transport info
tinfo->setupTime = transportInfo_.setupTime;
tinfo->secure = transportInfo_.secure;
tinfo->sslSetupTime = transportInfo_.sslSetupTime;
tinfo->sslVersion = transportInfo_.sslVersion;
tinfo->sslCipher = transportInfo_.sslCipher;
tinfo->sslResume = transportInfo_.sslResume;
tinfo->appProtocol = transportInfo_.appProtocol;
tinfo->sslError = transportInfo_.sslError;
#if defined(__linux__) || defined(__FreeBSD__)
// update connection transport info with the latest RTT
if (tinfo->tcpinfo.tcpi_rtt > 0) {
transportInfo_.tcpinfo.tcpi_rtt = tinfo->tcpinfo.tcpi_rtt;
transportInfo_.rtt = std::chrono::microseconds(tinfo->tcpinfo.tcpi_rtt);
}
transportInfo_.rtx = tinfo->rtx;
#endif
return true;
}
return false;
}
unique_ptr<IOBuf> HTTPSession::getNextToSend(bool* cork, bool* eom) {
// limit ourselves to one outstanding write at a time (onWriteSuccess calls
// scheduleWrite)
if (numActiveWrites_ > 0 || writesShutdown()) {
VLOG(4) << "skipping write during this loop, numActiveWrites_=" <<
numActiveWrites_ << " writesShutdown()=" << writesShutdown();
return nullptr;
}
// We always tack on at least one body packet to the current write buf
// This ensures that a short HTTPS response will go out in a single SSL record
while (!txnEgressQueue_.empty()) {
uint32_t toSend = kWriteReadyMax;
if (connFlowControl_) {
if (connFlowControl_->getAvailableSend() == 0) {
VLOG(4) << "Session-level send window is full, skipping remaining "
<< "body writes this loop";
break;
}
toSend = std::min(toSend, connFlowControl_->getAvailableSend());
}
txnEgressQueue_.nextEgress(nextEgressResults_,
isSpdyCodecProtocol(codec_->getProtocol()));
CHECK(!nextEgressResults_.empty()); // Queue was non empty, so this must be
// The maximum we will send for any transaction in this loop
uint32_t txnMaxToSend = toSend * nextEgressResults_.front().second;
if (txnMaxToSend == 0) {
// toSend is smaller than the number of transactions. Give all egress
// to the first transaction
nextEgressResults_.erase(++nextEgressResults_.begin(),
nextEgressResults_.end());
txnMaxToSend = std::min(toSend, egressBodySizeLimit_);
nextEgressResults_.front().second = 1;
}
if (nextEgressResults_.size() > 1 && txnMaxToSend > egressBodySizeLimit_) {
// Cap the max to egressBodySizeLimit_, and recompute toSend accordingly
txnMaxToSend = egressBodySizeLimit_;
toSend = txnMaxToSend / nextEgressResults_.front().second;
}
// split allowed by relative weight, with some minimum
for (auto txnPair: nextEgressResults_) {
uint32_t txnAllowed = txnPair.second * toSend;
if (nextEgressResults_.size() > 1) {
CHECK_LE(txnAllowed, egressBodySizeLimit_);
}
if (connFlowControl_) {
CHECK_LE(txnAllowed, connFlowControl_->getAvailableSend());
}
if (txnAllowed == 0) {
// The ratio * toSend was so small this txn gets nothing.
VLOG(4) << *this << " breaking egress loop on 0 txnAllowed";
break;
}
VLOG(4) << *this << " egressing txnID=" << txnPair.first->getID() <<
" allowed=" << txnAllowed;
txnPair.first->onWriteReady(txnAllowed, txnPair.second);
}
nextEgressResults_.clear();
// it can be empty because of HTTPTransaction rate limiting. We should
// change rate limiting to clearPendingEgress while waiting.
if (!writeBuf_.empty()) {
break;
}
}
*eom = false;
if (byteEventTracker_) {
uint64_t needed = byteEventTracker_->preSend(cork, eom, bytesWritten_);
if (needed > 0) {
VLOG(5) << *this << " writeBuf_.chainLength(): "
<< writeBuf_.chainLength() << " txnEgressQueue_.empty(): "
<< txnEgressQueue_.empty();
if (needed < writeBuf_.chainLength()) {
// split the next EOM chunk
VLOG(5) << *this << " splitting " << needed << " bytes out of a "
<< writeBuf_.chainLength() << " bytes IOBuf";
*cork = true;
if (sessionStats_) {
sessionStats_->recordTTLBAIOBSplitByEom();
}
return writeBuf_.split(needed);
} else {
CHECK_EQ(needed, writeBuf_.chainLength());
}
}
}
// cork if there are txns with pending egress and room to send them
*cork = !txnEgressQueue_.empty() && !isConnWindowFull();
return writeBuf_.move();
}
void
HTTPSession::runLoopCallback() noexcept {
// We schedule this callback to run at the end of an event
// loop iteration if either of two conditions has happened:
// * The session has generated some egress data (see scheduleWrite())
// * Reads have become unpaused (see resumeReads())
DestructorGuard dg(this);
inLoopCallback_ = true;
auto scopeg = folly::makeGuard([this] {
inLoopCallback_ = false;
// This ScopeGuard needs to be under the above DestructorGuard
if (pendingWriteSizeDelta_) {
updateWriteBufSize(0);
}
checkForShutdown();
});
VLOG(5) << *this << " in loop callback";
for (uint32_t i = 0; i < kMaxWritesPerLoop; ++i) {
bodyBytesPerWriteBuf_ = 0;
if (isPrioritySampled()) {
invokeOnAllTransactions(
&HTTPTransaction::updateContentionsCount,
txnEgressQueue_.numPendingEgress());
}
bool cork = true;
bool eom = false;
unique_ptr<IOBuf> writeBuf = getNextToSend(&cork, &eom);
if (!writeBuf) {
break;
}
uint64_t len = writeBuf->computeChainDataLength();
VLOG(11) << *this
<< " bytes of egress to be written: " << len
<< " cork:" << cork << " eom:" << eom;
if (len == 0) {
checkForShutdown();
return;
}
if (isPrioritySampled()) {
invokeOnAllTransactions(
&HTTPTransaction::updateSessionBytesSheduled,
bodyBytesPerWriteBuf_);
}
WriteSegment* segment = new WriteSegment(this, len);
segment->setCork(cork);
segment->setEOR(eom);
pendingWrites_.push_back(*segment);
if (!writeTimeout_.isScheduled()) {
// Any performance concern here?
timeout_.scheduleTimeout(&writeTimeout_);
}
numActiveWrites_++;
VLOG(4) << *this << " writing " << len << ", activeWrites="
<< numActiveWrites_ << " cork=" << cork << " eom=" << eom;
bytesScheduled_ += len;
sock_->writeChain(segment, std::move(writeBuf), segment->getFlags());
if (numActiveWrites_ > 0) {
updateWriteCount();
pendingWriteSizeDelta_ += len;
// updateWriteBufSize called in scope guard
break;
}
// writeChain can result in a writeError and trigger the shutdown code path
}
if (numActiveWrites_ == 0 && !writesShutdown() && hasMoreWrites() &&
(!connFlowControl_ || connFlowControl_->getAvailableSend())) {
scheduleWrite();
}
if (readsUnpaused()) {
processReadData();
// Install the read callback if necessary
if (readsUnpaused() && !sock_->getReadCallback()) {
sock_->setReadCB(this);
}
}
// checkForShutdown is now in ScopeGuard
}
void
HTTPSession::scheduleWrite() {
// Do all the network writes for this connection in one batch at
// the end of the current event loop iteration. Writing in a
// batch helps us packetize the network traffic more efficiently,
// as well as saving a few system calls.
if (!isLoopCallbackScheduled() &&
(writeBuf_.front() || !txnEgressQueue_.empty())) {
VLOG(5) << *this << " scheduling write callback";
sock_->getEventBase()->runInLoop(this);
}
}
void
HTTPSession::updateWriteCount() {
if (numActiveWrites_ > 0 && writesUnpaused()) {
// Exceeded limit. Pause reading on the incoming stream.
VLOG(3) << "Pausing egress for " << *this;
writes_ = SocketState::PAUSED;
} else if (numActiveWrites_ == 0 && writesPaused()) {
// Dropped below limit. Resume reading on the incoming stream if needed.
VLOG(3) << "Resuming egress for " << *this;
writes_ = SocketState::UNPAUSED;
}
}
void
HTTPSession::updateWriteBufSize(int64_t delta) {
// This is the sum of body bytes buffered within transactions_ and in
// the sock_'s write buffer.
delta += pendingWriteSizeDelta_;
pendingWriteSizeDelta_ = 0;
bool wasExceeded = egressLimitExceeded();
updatePendingWriteSize(delta);
if (egressLimitExceeded() && !wasExceeded) {
// Exceeded limit. Pause reading on the incoming stream.
if (inResume_) {
VLOG(3) << "Pausing txn egress for " << *this << " deferred";
pendingPause_ = true;
} else {
VLOG(3) << "Pausing txn egress for " << *this;
invokeOnAllTransactions(&HTTPTransaction::pauseEgress);
}
} else if (!egressLimitExceeded() && wasExceeded) {
// Dropped below limit. Resume reading on the incoming stream if needed.
if (inResume_) {
if (pendingPause_) {
VLOG(3) << "Cancel deferred txn egress pause for " << *this;
pendingPause_ = false;
} else {
VLOG(3) << "Ignoring redundant resume for " << *this;
}
} else {
VLOG(3) << "Resuming txn egress for " << *this;
resumeTransactions();
}
}
}
void
HTTPSession::shutdownTransport(bool shutdownReads,
bool shutdownWrites,
const std::string& errorMsg) {
DestructorGuard guard(this);
// shutdowns not accounted for, shouldn't see any
setCloseReason(ConnectionCloseReason::UNKNOWN);
VLOG(4) << "shutdown request for " << *this << ": reads="
<< shutdownReads << " (currently " << readsShutdown()
<< "), writes=" << shutdownWrites << " (currently "
<< writesShutdown() << ")";
bool notifyEgressShutdown = false;
bool notifyIngressShutdown = false;
ProxygenError error;
if (!transportInfo_.sslError.empty()) {
error = kErrorSSL;
} else if (sock_->error()) {
VLOG(3) << "shutdown request for " << *this
<< " on bad socket. Shutting down writes too.";
if (getConnectionCloseReason() == ConnectionCloseReason::IO_WRITE_ERROR) {
error = kErrorWrite;
} else {
error = kErrorConnectionReset;
}
shutdownWrites = true;
} else if (getConnectionCloseReason() == ConnectionCloseReason::TIMEOUT) {
error = kErrorTimeout;
} else {
error = kErrorEOF;
}
if (shutdownReads && !shutdownWrites && flowControlTimeout_.isScheduled()) {
// reads are dead and writes are blocked on a window update that will never
// come. shutdown writes too.
VLOG(4) << *this << " Converting read shutdown to read/write due to"
" flow control";
shutdownWrites = true;
}
if (shutdownWrites && !writesShutdown()) {
if (codec_->generateGoaway(writeBuf_,
codec_->getLastIncomingStreamID(),
ErrorCode::NO_ERROR)) {
scheduleWrite();
}
if (!hasMoreWrites() &&
(transactions_.empty() || codec_->closeOnEgressComplete())) {
writes_ = SocketState::SHUTDOWN;
if (byteEventTracker_) {
byteEventTracker_->drainByteEvents();
}
if (resetAfterDrainingWrites_) {
VLOG(4) << *this << " writes drained, sending RST";
resetSocketOnShutdown_ = true;
shutdownReads = true;
} else {
VLOG(4) << *this << " writes drained, closing";
sock_->shutdownWriteNow();
}
notifyEgressShutdown = true;
} else if (!writesDraining_) {
writesDraining_ = true;
notifyEgressShutdown = true;
} // else writes are already draining; don't double notify
}
if (shutdownReads && !readsShutdown()) {
notifyIngressShutdown = true;
// TODO: send an RST if readBuf_ is non empty?
sock_->setReadCB(nullptr);
reads_ = SocketState::SHUTDOWN;
if (!transactions_.empty() && error == kErrorConnectionReset) {
if (infoCallback_ != nullptr) {
infoCallback_->onIngressError(*this, error);
}
} else if (error == kErrorEOF) {
// Report to the codec that the ingress stream has ended
codec_->onIngressEOF();
if (infoCallback_) {
infoCallback_->onIngressEOF();
}
}
// Once reads are shutdown the parser should stop processing
codec_->setParserPaused(true);
}
if (notifyIngressShutdown || notifyEgressShutdown) {
auto dir = (notifyIngressShutdown && notifyEgressShutdown)
? HTTPException::Direction::INGRESS_AND_EGRESS
: (notifyIngressShutdown ? HTTPException::Direction::INGRESS
: HTTPException::Direction::EGRESS);
HTTPException ex(
dir,
folly::to<std::string>("Shutdown transport: ", getErrorString(error),
errorMsg.empty() ? "" : " ", errorMsg, ", ",
getPeerAddress().describe()));
ex.setProxygenError(error);
invokeOnAllTransactions(&HTTPTransaction::onError, ex);
}
// Close the socket only after the onError() callback on the txns
// and handler has been detached.
checkForShutdown();
}
void HTTPSession::shutdownTransportWithReset(
ProxygenError errorCode,
const std::string& errorMsg) {
DestructorGuard guard(this);
VLOG(4) << "shutdownTransportWithReset";
if (!readsShutdown()) {
sock_->setReadCB(nullptr);
reads_ = SocketState::SHUTDOWN;
}
if (!writesShutdown()) {
writes_ = SocketState::SHUTDOWN;
IOBuf::destroy(writeBuf_.move());
while (!pendingWrites_.empty()) {
pendingWrites_.front().detach();
numActiveWrites_--;
}
VLOG(4) << *this << " cancel write timer";
writeTimeout_.cancelTimeout();
resetSocketOnShutdown_ = true;
}
errorOnAllTransactions(errorCode, errorMsg);
// drainByteEvents() can call detach(txn), which can in turn call
// shutdownTransport if we were already draining. To prevent double
// calling onError() to the transactions, we call drainByteEvents()
// after we've given the explicit error.
if (byteEventTracker_) {
byteEventTracker_->drainByteEvents();
}
// HTTPTransaction::onError could theoretically schedule more callbacks,
// so do this last.
if (isLoopCallbackScheduled()) {
cancelLoopCallback();
}
// onError() callbacks or drainByteEvents() could result in txns detaching
// due to CallbackGuards going out of scope. Close the socket only after
// the txns are detached.
checkForShutdown();
}
void
HTTPSession::checkForShutdown() {
VLOG(10) << *this << " checking for shutdown, readShutdown="
<< readsShutdown() << ", writesShutdown=" << writesShutdown()
<< ", transaction set empty=" << transactions_.empty();
// Two conditions are required to destroy the HTTPSession:
// * All writes have been finished.
// * There are no transactions remaining on the session.
if (writesShutdown() && transactions_.empty() &&
!isLoopCallbackScheduled()) {
VLOG(4) << "destroying " << *this;
sock_->setReadCB(nullptr);
auto asyncSocket = sock_->getUnderlyingTransport<folly::AsyncSocket>();
if (asyncSocket) {
asyncSocket->setBufferCallback(nullptr);
}
reads_ = SocketState::SHUTDOWN;
if (resetSocketOnShutdown_) {
sock_->closeWithReset();
} else {
sock_->closeNow();
}
destroy();
}
}
void
HTTPSession::drain() {
if (!draining_) {
VLOG(4) << *this << " draining";
draining_ = true;
setCloseReason(ConnectionCloseReason::SHUTDOWN);
if (allTransactionsStarted()) {
drainImpl();
}
if (transactions_.empty() && isUpstream()) {
// We don't do this for downstream since we need to wait for
// inflight requests to arrive
VLOG(4) << *this << " shutdown from drain";
shutdownTransport(true, true);
}
} else {
VLOG(4) << *this << " already draining";
}
}
void HTTPSession::drainImpl() {
if (codec_->isReusable() || codec_->isWaitingToDrain()) {
setCloseReason(ConnectionCloseReason::SHUTDOWN);
// For HTTP/2, if we haven't started yet then we cannot send a GOAWAY frame
// since we haven't sent the initial SETTINGS frame. Defer sending that
// GOAWAY until the initial SETTINGS is sent.
if (started_) {
codec_->generateGoaway(writeBuf_,
getGracefulGoawayAck(),
ErrorCode::NO_ERROR);
scheduleWrite();
}
}
}
bool HTTPSession::shouldShutdown() const {
return draining_ &&
allTransactionsStarted() &&
(!codec_->supportsParallelRequests() ||
isUpstream() ||
!codec_->isReusable());
}
size_t HTTPSession::sendPing() {
const size_t bytes = codec_->generatePingRequest(writeBuf_);
if (bytes) {
scheduleWrite();
}
return bytes;
}
HTTPCodec::StreamID HTTPSession::sendPriority(http2::PriorityUpdate pri) {
if (!codec_->supportsParallelRequests()) {
// For HTTP/1.1, don't call createStream()
return 0;
}
auto id = codec_->createStream();
sendPriority(id, pri);
return id;
}
size_t HTTPSession::sendPriority(HTTPCodec::StreamID id,
http2::PriorityUpdate pri) {
auto res = sendPriorityImpl(id, pri);
txnEgressQueue_.addOrUpdatePriorityNode(id, pri);
return res;
}
size_t HTTPSession::sendPriorityImpl(HTTPCodec::StreamID id,
http2::PriorityUpdate pri) {
CHECK_NE(id, 0);
const size_t bytes = codec_->generatePriority(
writeBuf_, id, std::make_tuple(pri.streamDependency,
pri.exclusive,
pri.weight));
if (bytes) {
scheduleWrite();
}
return bytes;
}
HTTPTransaction*
HTTPSession::findTransaction(HTTPCodec::StreamID streamID) {
auto it = transactions_.find(streamID);
if (it == transactions_.end()) {
return nullptr;
} else {
return &it->second;
}
}
HTTPTransaction*
HTTPSession::createTransaction(
HTTPCodec::StreamID streamID,
const folly::Optional<HTTPCodec::StreamID>& assocStreamID,
const folly::Optional<HTTPCodec::ExAttributes>& exAttributes,
const http2::PriorityUpdate& priority) {
if (!sock_->good() || transactions_.count(streamID)) {
// Refuse to add a transaction on a closing session or if a
// transaction of that ID already exists.
return nullptr;
}
if (transactions_.empty()) {
if (infoCallback_) {
infoCallback_->onActivateConnection(*this);
}
if (getConnectionManager()) {
getConnectionManager()->onActivated(*this);
}
HTTPSessionBase::onCreateTransaction();
}
auto matchPair = transactions_.emplace(
std::piecewise_construct,
std::forward_as_tuple(streamID),
std::forward_as_tuple(
codec_->getTransportDirection(), streamID, getNumTxnServed(), *this,
txnEgressQueue_, timeout_.getWheelTimer(), timeout_.getDefaultTimeout(),
sessionStats_,
codec_->supportsStreamFlowControl(),
initialReceiveWindow_,
getCodecSendWindowSize(),
priority,
assocStreamID,
exAttributes
));
CHECK(matchPair.second) << "Emplacement failed, despite earlier "
"existence check.";
HTTPTransaction* txn = &matchPair.first->second;
if (isPrioritySampled()) {
txn->setPrioritySampled(true /* sampled */);
}
if (getNumTxnServed() > 0) {
auto stats = txn->getSessionStats();
if (stats != nullptr) {
stats->recordSessionReused();
}
}
VLOG(5) << *this << " adding streamID=" << txn->getID()
<< ", liveTransactions_ was " << liveTransactions_;
++liveTransactions_;
incrementSeqNo();
txn->setReceiveWindow(receiveStreamWindowSize_);
if (isUpstream() && !txn->isPushed()) {
incrementOutgoingStreams();
// do not count towards MAX_CONCURRENT_STREAMS for PUSH_PROMISE
} else if (!(isDownstream() && txn->isPushed())) {
incomingStreams_++;
}
return txn;
}
void
HTTPSession::incrementOutgoingStreams() {
outgoingStreams_++;
HTTPSessionBase::onNewOutgoingStream(outgoingStreams_);
}
void
HTTPSession::onWriteSuccess(uint64_t bytesWritten) {
DestructorGuard dg(this);
bytesWritten_ += bytesWritten;
transportInfo_.totalBytes += bytesWritten;
CHECK(writeTimeout_.isScheduled());
if (pendingWrites_.empty()) {
VLOG(10) << "Cancel write timer on last successful write";
writeTimeout_.cancelTimeout();
} else {
VLOG(10) << "Refresh write timer on writeSuccess";
timeout_.scheduleTimeout(&writeTimeout_);
}
if (infoCallback_) {
infoCallback_->onWrite(*this, bytesWritten);
}
VLOG(5) << "total bytesWritten_: " << bytesWritten_;
// processByteEvents will return true if it has been replaced with another
// tracker in the middle and needs to be re-run. Should happen at most
// once. while with no body is intentional
while (byteEventTracker_ &&
byteEventTracker_->processByteEvents(
byteEventTracker_, bytesWritten_)) {} // pass
if ((!codec_->isReusable() || readsShutdown()) && (transactions_.empty())) {
if (!codec_->isReusable()) {
// Shouldn't happen unless there is a bug. This can only happen when
// someone calls shutdownTransport, but did not specify a reason before.
setCloseReason(ConnectionCloseReason::UNKNOWN);
}
VLOG(4) << *this << " shutdown from onWriteSuccess";
shutdownTransport(true, true);
}
numActiveWrites_--;
if (!inLoopCallback_) {
updateWriteCount();
// safe to resume here:
updateWriteBufSize(-folly::to<int64_t>(bytesWritten));
// PRIO_FIXME: this is done because of the corking business...
// in the future we may want to have a pull model
// whereby the socket asks us for a given amount of
// data to send...
if (numActiveWrites_ == 0 && hasMoreWrites()) {
runLoopCallback();
}
}
onWriteCompleted();
if (egressBytesLimit_ > 0 && bytesWritten_ >= egressBytesLimit_) {
VLOG(4) << "Egress limit reached, shutting down "
"session (egressed " << bytesWritten_ << ", limit set to "
<< egressBytesLimit_ << ")";
shutdownTransport(true, true);
}
}
void
HTTPSession::onWriteError(size_t bytesWritten,
const AsyncSocketException& ex) {
VLOG(4) << *this << " write error: " << ex.what();
if (infoCallback_) {
infoCallback_->onWrite(*this, bytesWritten);
}
auto sslEx = dynamic_cast<const folly::SSLException*>(&ex);
// Save the SSL error, if there was one. It will be recorded later
if (sslEx && sslEx->getSSLError() == folly::SSLError::SSL_ERROR) {
transportInfo_.sslError = ex.what();
}
setCloseReason(ConnectionCloseReason::IO_WRITE_ERROR);
shutdownTransportWithReset(kErrorWrite, ex.what());
}
void
HTTPSession::onWriteCompleted() {
if (!writesDraining_) {
return;
}
if (numActiveWrites_) {
return;
}
// Don't shutdown if there might be more writes
if (!pendingWrites_.empty()) {
return;
}
// All finished draining writes, so shut down the egress
shutdownTransport(false, true);
}
void HTTPSession::onSessionParseError(const HTTPException& error) {
VLOG(4) << *this << " session layer parse error. Terminate the session.";
if (error.hasCodecStatusCode()) {
std::unique_ptr<folly::IOBuf> errorMsg =
folly::IOBuf::copyBuffer(error.what());
codec_->generateGoaway(writeBuf_,
codec_->getLastIncomingStreamID(),
error.getCodecStatusCode(),
isHTTP2CodecProtocol(codec_->getProtocol()) ?
std::move(errorMsg) : nullptr);
scheduleWrite();
}
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
shutdownTransport(true, true);
}
void HTTPSession::onNewTransactionParseError(HTTPCodec::StreamID streamID,
const HTTPException& error) {
VLOG(4) << *this << " parse error with new transaction";
if (error.hasCodecStatusCode()) {
codec_->generateRstStream(writeBuf_, streamID, error.getCodecStatusCode());
scheduleWrite();
}
if (!codec_->isReusable()) {
// HTTP 1x codec does not support per stream abort so this will
// render the codec not reusable
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
}
}
void
HTTPSession::pauseReads() {
// Make sure the parser is paused. Note that if reads are shutdown
// before they are paused, we never make it past the if.
codec_->setParserPaused(true);
if (!readsUnpaused() ||
(codec_->supportsParallelRequests() &&
!ingressLimitExceeded())) {
return;
}
pauseReadsImpl();
}
void HTTPSession::pauseReadsImpl() {
VLOG(4) << *this << ": pausing reads";
if (infoCallback_) {
infoCallback_->onIngressPaused(*this);
}
cancelTimeout();
sock_->setReadCB(nullptr);
reads_ = SocketState::PAUSED;
}
void
HTTPSession::resumeReads() {
if (!readsPaused() ||
(codec_->supportsParallelRequests() &&
ingressLimitExceeded())) {
return;
}
resumeReadsImpl();
}
void HTTPSession::resumeReadsImpl() {
VLOG(4) << *this << ": resuming reads";
resetTimeout();
reads_ = SocketState::UNPAUSED;
codec_->setParserPaused(false);
if (!isLoopCallbackScheduled()) {
sock_->getEventBase()->runInLoop(this);
}
}
bool
HTTPSession::hasMoreWrites() const {
VLOG(10) << __PRETTY_FUNCTION__
<< " numActiveWrites_: " << numActiveWrites_
<< " pendingWrites_.empty(): " << pendingWrites_.empty()
<< " pendingWrites_.size(): " << pendingWrites_.size()
<< " txnEgressQueue_.empty(): " << txnEgressQueue_.empty();
return (numActiveWrites_ != 0) ||
!pendingWrites_.empty() || writeBuf_.front() ||
!txnEgressQueue_.empty();
}
void HTTPSession::errorOnAllTransactions(
ProxygenError err,
const std::string& errorMsg) {
std::vector<HTTPCodec::StreamID> ids;
for (const auto& txn: transactions_) {
ids.push_back(txn.first);
}
errorOnTransactionIds(ids, err, errorMsg);
}
void HTTPSession::errorOnTransactionIds(
const std::vector<HTTPCodec::StreamID>& ids,
ProxygenError err,
const std::string& errorMsg) {
std::string extraErrorMsg;
if (!errorMsg.empty()) {
extraErrorMsg = folly::to<std::string>(". ", errorMsg);
}
for (auto id: ids) {
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>(getErrorString(err),
" on transaction id: ", id,
extraErrorMsg));
ex.setProxygenError(err);
errorOnTransactionId(id, std::move(ex));
}
}
void HTTPSession::errorOnTransactionId(
HTTPCodec::StreamID id,
HTTPException ex) {
auto txn = findTransaction(id);
if (txn != nullptr) {
txn->onError(std::move(ex));
}
}
void HTTPSession::resumeTransactions() {
CHECK(!inResume_);
inResume_ = true;
DestructorGuard g(this);
auto resumeFn = [] (HTTP2PriorityQueue&, HTTPCodec::StreamID,
HTTPTransaction *txn, double) {
if (txn) {
txn->resumeEgress();
}
return false;
};
auto stopFn = [this] {
return (transactions_.empty() || egressLimitExceeded());
};
txnEgressQueue_.iterateBFS(resumeFn, stopFn, true /* all */);
inResume_ = false;
if (pendingPause_) {
VLOG(3) << "Pausing txn egress for " << *this;
pendingPause_ = false;
invokeOnAllTransactions(&HTTPTransaction::pauseEgress);
}
}
void HTTPSession::onConnectionSendWindowOpen() {
flowControlTimeout_.cancelTimeout();
// We can write more now. Schedule a write.
scheduleWrite();
}
void HTTPSession::onConnectionSendWindowClosed() {
if(!txnEgressQueue_.empty()) {
VLOG(4) << *this << " session stalled by flow control";
if (sessionStats_) {
sessionStats_->recordSessionStalled();
}
}
DCHECK(!flowControlTimeout_.isScheduled());
if (infoCallback_) {
infoCallback_->onFlowControlWindowClosed(*this);
}
auto timeout = flowControlTimeout_.getTimeoutDuration();
if (timeout != std::chrono::milliseconds(0)) {
timeout_.scheduleTimeout(&flowControlTimeout_, timeout);
} else {
timeout_.scheduleTimeout(&flowControlTimeout_);
}
}
HTTPCodec::StreamID HTTPSession::getGracefulGoawayAck() const {
if (!codec_->isReusable() || codec_->isWaitingToDrain()) {
// TODO: just track last stream ID inside HTTPSession since this logic
// is shared between HTTP/2 and SPDY
return codec_->getLastIncomingStreamID();
}
VLOG(4) << *this << " getGracefulGoawayAck is reusable and not draining";
// return the maximum possible stream id
return std::numeric_limits<int32_t>::max();
}
void HTTPSession::invalidStream(HTTPCodec::StreamID stream, ErrorCode code) {
if (!codec_->supportsParallelRequests()) {
LOG(ERROR) << "Invalid stream on non-parallel codec.";
return;
}
HTTPException err(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("invalid stream=", stream));
// TODO: Below line will change for HTTP/2 -- just call a const getter
// function for the status code.
err.setCodecStatusCode(code);
onError(stream, err, true);
}
void HTTPSession::onPingReplyLatency(int64_t latency) noexcept {
if (infoCallback_ && latency >= 0) {
infoCallback_->onPingReplySent(latency);
}
}
void HTTPSession::onDeleteAckEvent() noexcept {
if (readsShutdown()) {
shutdownTransport(true, transactions_.empty());
}
}
void HTTPSession::onEgressBuffered() {
if (infoCallback_) {
infoCallback_->onEgressBuffered(*this);
}
}
void HTTPSession::onEgressBufferCleared() {
if (infoCallback_) {
infoCallback_->onEgressBufferCleared(*this);
}
}
void HTTPSession::onReplaySafe() noexcept {
CHECK(sock_);
sock_->setReplaySafetyCallback(nullptr);
if (infoCallback_) {
infoCallback_->onFullHandshakeCompletion(*this);
}
for (auto callback : waitingForReplaySafety_) {
callback->onReplaySafe();
}
waitingForReplaySafety_.clear();
}
void HTTPSession::onLastByteEvent(
HTTPTransaction* txn, uint64_t eomOffset, bool eomTracked) noexcept {
if (!sock_->isEorTrackingEnabled() || !eomTracked) {
return;
}
if (eomOffset != sock_->getAppBytesWritten()) {
VLOG(2) << "tracking ack to last app byte " << eomOffset
<< " while " << sock_->getAppBytesWritten()
<< " app bytes have already been written";
return;
}
VLOG(5) << "tracking raw last byte " << sock_->getRawBytesWritten()
<< " while the app last byte is " << eomOffset;
byteEventTracker_->addAckByteEvent(sock_->getRawBytesWritten(), txn);
}
} // proxygen
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_597_0 |
crossvul-cpp_data_good_1749_1 | /*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2011-2015 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <Core/Controller.h>
// For calculating delta_monotonic (Ruby < 2.1 workaround, otherwise unused)
#include <uv.h>
/*************************************************************************
*
* Implements Core::Controller methods pertaining sending request data
* to a selected application process. This happens in parallel to forwarding
* application response data to the client.
*
*************************************************************************/
namespace Passenger {
namespace Core {
using namespace std;
using namespace boost;
/****************************
*
* Private methods
*
****************************/
struct Controller::SessionProtocolWorkingState {
StaticString path;
StaticString queryString;
StaticString methodStr;
StaticString serverName;
StaticString serverPort;
const LString *remoteAddr;
const LString *remotePort;
const LString *remoteUser;
const LString *contentType;
const LString *contentLength;
char *environmentVariablesData;
size_t environmentVariablesSize;
bool hasBaseURI;
SessionProtocolWorkingState()
: environmentVariablesData(NULL)
{ }
~SessionProtocolWorkingState() {
free(environmentVariablesData);
}
};
struct Controller::HttpHeaderConstructionCache {
StaticString methodStr;
const LString *remoteAddr;
const LString *setCookie;
bool cached;
};
void
Controller::sendHeaderToApp(Client *client, Request *req) {
TRACE_POINT();
SKC_TRACE(client, 2, "Sending headers to application with " <<
req->session->getProtocol() << " protocol");
req->state = Request::SENDING_HEADER_TO_APP;
/**
* HTTP does not formally support half-closing, and Node.js treats a
* half-close as a full close, so we only half-close session sockets, not
* HTTP sockets.
*/
if (req->session->getProtocol() == "session") {
UPDATE_TRACE_POINT();
req->halfCloseAppConnection = req->bodyType != Request::RBT_NO_BODY;
sendHeaderToAppWithSessionProtocol(client, req);
} else {
UPDATE_TRACE_POINT();
req->halfCloseAppConnection = false;
sendHeaderToAppWithHttpProtocol(client, req);
}
UPDATE_TRACE_POINT();
if (!req->ended()) {
if (req->appSink.acceptingInput()) {
UPDATE_TRACE_POINT();
sendBodyToApp(client, req);
if (!req->ended()) {
req->appSource.startReading();
}
} else if (req->appSink.mayAcceptInputLater()) {
UPDATE_TRACE_POINT();
SKC_TRACE(client, 3, "Waiting for appSink channel to become "
"idle before sending body to application");
req->appSink.setConsumedCallback(sendBodyToAppWhenAppSinkIdle);
req->appSource.startReading();
} else {
// Either we're done feeding to req->appSink, or req->appSink.feed()
// encountered an error while writing to the application socket.
// But we don't care about either scenarios; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
UPDATE_TRACE_POINT();
assert(req->appSink.ended() || req->appSink.hasError());
logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
req->appSource.startReading();
}
}
}
void
Controller::sendHeaderToAppWithSessionProtocol(Client *client, Request *req) {
TRACE_POINT();
SessionProtocolWorkingState state;
// Workaround for Ruby < 2.1 support.
std::string delta_monotonic = boost::to_string(SystemTime::getUsec() - (uv_hrtime() / 1000));
unsigned int bufferSize = determineHeaderSizeForSessionProtocol(req,
state, delta_monotonic);
MemoryKit::mbuf_pool &mbuf_pool = getContext()->mbuf_pool;
const unsigned int MBUF_MAX_SIZE = mbuf_pool_data_size(&mbuf_pool);
bool ok;
if (bufferSize <= MBUF_MAX_SIZE) {
MemoryKit::mbuf buffer(MemoryKit::mbuf_get(&mbuf_pool));
bufferSize = MBUF_MAX_SIZE;
ok = constructHeaderForSessionProtocol(req, buffer.start,
bufferSize, state, delta_monotonic);
assert(ok);
buffer = MemoryKit::mbuf(buffer, 0, bufferSize);
SKC_TRACE(client, 3, "Header data: \"" << cEscapeString(
StaticString(buffer.start, bufferSize)) << "\"");
req->appSink.feedWithoutRefGuard(boost::move(buffer));
} else {
char *buffer = (char *) psg_pnalloc(req->pool, bufferSize);
ok = constructHeaderForSessionProtocol(req, buffer,
bufferSize, state, delta_monotonic);
assert(ok);
SKC_TRACE(client, 3, "Header data: \"" << cEscapeString(
StaticString(buffer, bufferSize)) << "\"");
req->appSink.feedWithoutRefGuard(MemoryKit::mbuf(
buffer, bufferSize));
}
(void) ok; // Shut up compiler warning
}
void
Controller::sendBodyToAppWhenAppSinkIdle(Channel *_channel, unsigned int size) {
FdSinkChannel *channel = reinterpret_cast<FdSinkChannel *>(_channel);
Request *req = static_cast<Request *>(static_cast<
ServerKit::BaseHttpRequest *>(channel->getHooks()->userData));
Client *client = static_cast<Client *>(req->client);
Controller *self = static_cast<Controller *>(
getServerFromClient(client));
SKC_LOG_EVENT_FROM_STATIC(self, Controller, client, "sendBodyToAppWhenAppSinkIdle");
channel->setConsumedCallback(NULL);
if (channel->acceptingInput()) {
self->sendBodyToApp(client, req);
if (!req->ended()) {
req->appSource.startReading();
}
} else {
// req->appSink.feed() encountered an error while writing to the
// application socket. But we don't care about that; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
UPDATE_TRACE_POINT();
assert(!req->appSink.ended());
assert(req->appSink.hasError());
self->logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
req->appSource.startReading();
}
}
static bool
isAlphaNum(char ch) {
return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
/**
* For CGI, alphanum headers with optional dashes are mapped to UPP3R_CAS3. This
* function can be used to reject non-alphanum/dash headers that would end up with
* the same mapping (e.g. upp3r_cas3 and upp3r-cas3 would end up the same, and
* potentially collide each other in the receiving application). This is
* used to fix CVE-2015-7519.
*/
static bool
containsNonAlphaNumDash(const LString &s) {
const LString::Part *part = s.start;
while (part != NULL) {
for (unsigned int i = 0; i < part->size; i++) {
const char start = part->data[i];
if (start != '-' && !isAlphaNum(start)) {
return true;
}
}
part = part->next;
}
return false;
}
static void
httpHeaderToScgiUpperCase(unsigned char *data, unsigned int size) {
static const boost::uint8_t toUpperMap[256] = {
'\0', 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, '\t',
'\n', 0x0b, 0x0c, '\r', 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f, ' ', '!', '"', '#', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', '_', '.', '/', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
'<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', '[', '\\', ']', '^', '_', '`', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '{', '|', '}', '~', 0x7f, 0x80, 0x81,
0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b,
0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,
0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9,
0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd,
0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1,
0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb,
0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5,
0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9,
0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
const unsigned char *buf = data;
const size_t imax = size / 8;
const size_t leftover = size % 8;
size_t i;
for (i = 0; i < imax; i++, data += 8) {
data[0] = (unsigned char) toUpperMap[data[0]];
data[1] = (unsigned char) toUpperMap[data[1]];
data[2] = (unsigned char) toUpperMap[data[2]];
data[3] = (unsigned char) toUpperMap[data[3]];
data[4] = (unsigned char) toUpperMap[data[4]];
data[5] = (unsigned char) toUpperMap[data[5]];
data[6] = (unsigned char) toUpperMap[data[6]];
data[7] = (unsigned char) toUpperMap[data[7]];
}
i = imax * 8;
switch (leftover) {
case 7: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 6: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 5: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 4: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 3: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 2: *data++ = (unsigned char) toUpperMap[buf[i++]];
case 1: *data++ = (unsigned char) toUpperMap[buf[i]];
case 0: break;
}
}
unsigned int
Controller::determineHeaderSizeForSessionProtocol(Request *req,
SessionProtocolWorkingState &state, string delta_monotonic)
{
unsigned int dataSize = sizeof(boost::uint32_t);
state.path = req->getPathWithoutQueryString();
state.hasBaseURI = req->options.baseURI != P_STATIC_STRING("/")
&& startsWith(state.path, req->options.baseURI);
if (state.hasBaseURI) {
state.path = state.path.substr(req->options.baseURI.size());
if (state.path.empty()) {
state.path = P_STATIC_STRING("/");
}
}
state.queryString = req->getQueryString();
state.methodStr = StaticString(http_method_str(req->method));
state.remoteAddr = req->secureHeaders.lookup(REMOTE_ADDR);
state.remotePort = req->secureHeaders.lookup(REMOTE_PORT);
state.remoteUser = req->secureHeaders.lookup(REMOTE_USER);
state.contentType = req->headers.lookup(HTTP_CONTENT_TYPE);
if (req->hasBody()) {
state.contentLength = req->headers.lookup(HTTP_CONTENT_LENGTH);
} else {
state.contentLength = NULL;
}
if (req->envvars != NULL) {
size_t len = modp_b64_decode_len(req->envvars->size);
state.environmentVariablesData = (char *) malloc(len);
if (state.environmentVariablesData == NULL) {
throw RuntimeException("Unable to allocate memory for base64 "
"decoding of environment variables");
}
len = modp_b64_decode(state.environmentVariablesData,
req->envvars->start->data,
req->envvars->size);
if (len == (size_t) -1) {
throw RuntimeException("Unable to base64 decode environment variables");
}
state.environmentVariablesSize = len;
}
dataSize += sizeof("REQUEST_URI");
dataSize += req->path.size + 1;
dataSize += sizeof("PATH_INFO");
dataSize += state.path.size() + 1;
dataSize += sizeof("SCRIPT_NAME");
if (state.hasBaseURI) {
dataSize += req->options.baseURI.size();
} else {
dataSize += sizeof("");
}
dataSize += sizeof("QUERY_STRING");
dataSize += state.queryString.size() + 1;
dataSize += sizeof("REQUEST_METHOD");
dataSize += state.methodStr.size() + 1;
if (req->host != NULL && req->host->size > 0) {
const LString *host = psg_lstr_make_contiguous(req->host, req->pool);
const char *sep = (const char *) memchr(host->start->data, ':', host->size);
if (sep != NULL) {
state.serverName = StaticString(host->start->data, sep - host->start->data);
state.serverPort = StaticString(sep + 1,
host->start->data + host->size - sep - 1);
} else {
state.serverName = StaticString(host->start->data, host->size);
if (req->https) {
state.serverPort = P_STATIC_STRING("443");
} else {
state.serverPort = P_STATIC_STRING("80");
}
}
} else {
state.serverName = defaultServerName;
state.serverPort = defaultServerPort;
}
dataSize += sizeof("SERVER_NAME");
dataSize += state.serverName.size() + 1;
dataSize += sizeof("SERVER_PORT");
dataSize += state.serverPort.size() + 1;
dataSize += sizeof("SERVER_SOFTWARE");
dataSize += serverSoftware.size() + 1;
dataSize += sizeof("SERVER_PROTOCOL");
dataSize += sizeof("HTTP/1.1");
dataSize += sizeof("REMOTE_ADDR");
if (state.remoteAddr != NULL) {
dataSize += state.remoteAddr->size + 1;
} else {
dataSize += sizeof("127.0.0.1");
}
dataSize += sizeof("REMOTE_PORT");
if (state.remotePort != NULL) {
dataSize += state.remotePort->size + 1;
} else {
dataSize += sizeof("0");
}
if (state.remoteUser != NULL) {
dataSize += sizeof("REMOTE_USER");
dataSize += state.remoteUser->size + 1;
}
if (state.contentType != NULL) {
dataSize += sizeof("CONTENT_TYPE");
dataSize += state.contentType->size + 1;
}
if (state.contentLength != NULL) {
dataSize += sizeof("CONTENT_LENGTH");
dataSize += state.contentLength->size + 1;
}
dataSize += sizeof("PASSENGER_CONNECT_PASSWORD");
dataSize += ApplicationPool2::ApiKey::SIZE + 1;
if (req->https) {
dataSize += sizeof("HTTPS");
dataSize += sizeof("on");
}
if (req->options.analytics) {
dataSize += sizeof("PASSENGER_TXN_ID");
dataSize += req->options.transaction->getTxnId().size() + 1;
dataSize += sizeof("PASSENGER_DELTA_MONOTONIC");
dataSize += delta_monotonic.size() + 1;
}
if (req->upgraded()) {
dataSize += sizeof("HTTP_CONNECTION");
dataSize += sizeof("upgrade");
}
ServerKit::HeaderTable::Iterator it(req->headers);
while (*it != NULL) {
dataSize += sizeof("HTTP_") - 1 + it->header->key.size + 1;
dataSize += it->header->val.size + 1;
it.next();
}
if (state.environmentVariablesData != NULL) {
dataSize += state.environmentVariablesSize;
}
return dataSize + 1;
}
bool
Controller::constructHeaderForSessionProtocol(Request *req, char * restrict buffer,
unsigned int &size, const SessionProtocolWorkingState &state, string delta_monotonic)
{
char *pos = buffer;
const char *end = buffer + size;
pos += sizeof(boost::uint32_t);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REQUEST_URI"));
pos = appendData(pos, end, req->path.start->data, req->path.size);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PATH_INFO"));
pos = appendData(pos, end, state.path.data(), state.path.size());
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SCRIPT_NAME"));
if (state.hasBaseURI) {
pos = appendData(pos, end, req->options.baseURI);
pos = appendData(pos, end, "", 1);
} else {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL(""));
}
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("QUERY_STRING"));
pos = appendData(pos, end, state.queryString.data(), state.queryString.size());
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REQUEST_METHOD"));
pos = appendData(pos, end, state.methodStr);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_NAME"));
pos = appendData(pos, end, state.serverName);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_PORT"));
pos = appendData(pos, end, state.serverPort);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_SOFTWARE"));
pos = appendData(pos, end, serverSoftware);
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("SERVER_PROTOCOL"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("HTTP/1.1"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REMOTE_ADDR"));
if (state.remoteAddr != NULL) {
pos = appendData(pos, end, state.remoteAddr);
pos = appendData(pos, end, "", 1);
} else {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("127.0.0.1"));
}
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REMOTE_PORT"));
if (state.remotePort != NULL) {
pos = appendData(pos, end, state.remotePort);
pos = appendData(pos, end, "", 1);
} else {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("0"));
}
if (state.remoteUser != NULL) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("REMOTE_USER"));
pos = appendData(pos, end, state.remoteUser);
pos = appendData(pos, end, "", 1);
}
if (state.contentType != NULL) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("CONTENT_TYPE"));
pos = appendData(pos, end, state.contentType);
pos = appendData(pos, end, "", 1);
}
if (state.contentLength != NULL) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("CONTENT_LENGTH"));
pos = appendData(pos, end, state.contentLength);
pos = appendData(pos, end, "", 1);
}
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PASSENGER_CONNECT_PASSWORD"));
pos = appendData(pos, end, req->session->getApiKey().toStaticString());
pos = appendData(pos, end, "", 1);
if (req->https) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("HTTPS"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("on"));
}
if (req->options.analytics) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PASSENGER_TXN_ID"));
pos = appendData(pos, end, req->options.transaction->getTxnId());
pos = appendData(pos, end, "", 1);
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("PASSENGER_DELTA_MONOTONIC"));
pos = appendData(pos, end, delta_monotonic);
pos = appendData(pos, end, "", 1);
}
if (req->upgraded()) {
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("HTTP_CONNECTION"));
pos = appendData(pos, end, P_STATIC_STRING_WITH_NULL("upgrade"));
}
ServerKit::HeaderTable::Iterator it(req->headers);
while (*it != NULL) {
// This header-skipping is not accounted for in determineHeaderSizeForSessionProtocol(), but
// since we are only reducing the size it just wastes some mem bytes.
if ((
(it->header->hash == HTTP_CONTENT_LENGTH.hash()
|| it->header->hash == HTTP_CONTENT_TYPE.hash()
|| it->header->hash == HTTP_CONNECTION.hash()
) && (psg_lstr_cmp(&it->header->key, P_STATIC_STRING("content-type"))
|| psg_lstr_cmp(&it->header->key, P_STATIC_STRING("content-length"))
|| psg_lstr_cmp(&it->header->key, P_STATIC_STRING("connection"))
)
) || containsNonAlphaNumDash(it->header->key)
)
{
it.next();
continue;
}
pos = appendData(pos, end, P_STATIC_STRING("HTTP_"));
const LString::Part *part = it->header->key.start;
while (part != NULL) {
char *start = pos;
pos = appendData(pos, end, part->data, part->size);
httpHeaderToScgiUpperCase((unsigned char *) start, pos - start);
part = part->next;
}
pos = appendData(pos, end, "", 1);
part = it->header->val.start;
while (part != NULL) {
pos = appendData(pos, end, part->data, part->size);
part = part->next;
}
pos = appendData(pos, end, "", 1);
it.next();
}
if (state.environmentVariablesData != NULL) {
pos = appendData(pos, end, state.environmentVariablesData, state.environmentVariablesSize);
}
Uint32Message::generate(buffer, pos - buffer - sizeof(boost::uint32_t));
size = pos - buffer;
return pos < end;
}
void
Controller::sendHeaderToAppWithHttpProtocol(Client *client, Request *req) {
ssize_t bytesWritten;
HttpHeaderConstructionCache cache;
cache.cached = false;
if (OXT_UNLIKELY(getLogLevel() >= LVL_DEBUG3)) {
struct iovec *buffers;
unsigned int nbuffers, dataSize;
bool ok;
ok = constructHeaderBuffersForHttpProtocol(req, NULL, 0,
nbuffers, dataSize, cache);
assert(ok);
buffers = (struct iovec *) psg_palloc(req->pool,
sizeof(struct iovec) * nbuffers);
ok = constructHeaderBuffersForHttpProtocol(req, buffers, nbuffers,
nbuffers, dataSize, cache);
assert(ok);
(void) ok; // Shut up compiler warning
char *buffer = (char *) psg_pnalloc(req->pool, dataSize);
gatherBuffers(buffer, dataSize, buffers, nbuffers);
SKC_TRACE(client, 3, "Header data: \"" <<
cEscapeString(StaticString(buffer, dataSize)) << "\"");
}
if (!sendHeaderToAppWithHttpProtocolAndWritev(req, bytesWritten, cache)) {
if (bytesWritten >= 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
sendHeaderToAppWithHttpProtocolWithBuffering(req, bytesWritten, cache);
} else {
int e = errno;
P_ASSERT_EQ(bytesWritten, -1);
disconnectWithAppSocketWriteError(&client, e);
}
}
}
/**
* Construct an array of buffers, which together contain the 'http' protocol header
* data that should be sent to the application. This method does not copy any data:
* it just constructs buffers that point to the data stored inside `req->pool`,
* `req->headers`, etc.
*
* The buffers will be stored in the array pointed to by `buffer`. This array must
* have space for at least `maxbuffers` items. The actual number of buffers constructed
* is stored in `nbuffers`, and the total data size of the buffers is stored in `dataSize`.
* Upon success, returns true. If the actual number of buffers necessary exceeds
* `maxbuffers`, then false is returned.
*
* You can also set `buffers` to NULL, in which case this method will not construct any
* buffers, but only count the number of buffers necessary, as well as the total data size.
* In this case, this method always returns true.
*/
bool
Controller::constructHeaderBuffersForHttpProtocol(Request *req, struct iovec *buffers,
unsigned int maxbuffers, unsigned int & restrict_ref nbuffers,
unsigned int & restrict_ref dataSize, HttpHeaderConstructionCache &cache)
{
#define BEGIN_PUSH_NEXT_BUFFER() \
do { \
if (buffers != NULL && i >= maxbuffers) { \
return false; \
} \
} while (false)
#define INC_BUFFER_ITER(i) \
do { \
i++; \
} while (false)
#define PUSH_STATIC_BUFFER(buf) \
do { \
BEGIN_PUSH_NEXT_BUFFER(); \
if (buffers != NULL) { \
buffers[i].iov_base = (void *) buf; \
buffers[i].iov_len = sizeof(buf) - 1; \
} \
INC_BUFFER_ITER(i); \
dataSize += sizeof(buf) - 1; \
} while (false)
ServerKit::HeaderTable::Iterator it(req->headers);
const LString::Part *part;
unsigned int i = 0;
nbuffers = 0;
dataSize = 0;
if (!cache.cached) {
cache.methodStr = http_method_str(req->method);
cache.remoteAddr = req->secureHeaders.lookup(REMOTE_ADDR);
cache.setCookie = req->headers.lookup(ServerKit::HTTP_SET_COOKIE);
cache.cached = true;
}
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) cache.methodStr.data();
buffers[i].iov_len = cache.methodStr.size();
}
INC_BUFFER_ITER(i);
dataSize += cache.methodStr.size();
PUSH_STATIC_BUFFER(" ");
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) req->path.start->data;
buffers[i].iov_len = req->path.size;
}
INC_BUFFER_ITER(i);
dataSize += req->path.size;
if (req->upgraded()) {
PUSH_STATIC_BUFFER(" HTTP/1.1\r\nConnection: upgrade\r\n");
} else {
PUSH_STATIC_BUFFER(" HTTP/1.1\r\nConnection: close\r\n");
}
if (cache.setCookie != NULL) {
LString::Part *part;
PUSH_STATIC_BUFFER("Set-Cookie: ");
part = cache.setCookie->start;
while (part != NULL) {
if (part->size == 1 && part->data[0] == '\n') {
// HeaderTable joins multiple Set-Cookie headers together using \n.
PUSH_STATIC_BUFFER("\r\nSet-Cookie: ");
} else {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
dataSize += part->size;
}
part = part->next;
}
PUSH_STATIC_BUFFER("\r\n");
}
while (*it != NULL) {
if ((it->header->hash == HTTP_CONNECTION.hash()
|| it->header->hash == ServerKit::HTTP_SET_COOKIE.hash())
&& (psg_lstr_cmp(&it->header->key, P_STATIC_STRING("connection"))
|| psg_lstr_cmp(&it->header->key, ServerKit::HTTP_SET_COOKIE)))
{
it.next();
continue;
}
part = it->header->key.start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += it->header->key.size;
PUSH_STATIC_BUFFER(": ");
part = it->header->val.start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += it->header->val.size;
PUSH_STATIC_BUFFER("\r\n");
it.next();
}
if (req->https) {
PUSH_STATIC_BUFFER("X-Forwarded-Proto: https\r\n");
PUSH_STATIC_BUFFER("!~Passenger-Proto: https\r\n");
}
if (cache.remoteAddr != NULL && cache.remoteAddr->size > 0) {
PUSH_STATIC_BUFFER("X-Forwarded-For: ");
part = cache.remoteAddr->start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += cache.remoteAddr->size;
PUSH_STATIC_BUFFER("\r\n");
PUSH_STATIC_BUFFER("!~Passenger-Client-Address: ");
part = cache.remoteAddr->start;
while (part != NULL) {
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) part->data;
buffers[i].iov_len = part->size;
}
INC_BUFFER_ITER(i);
part = part->next;
}
dataSize += cache.remoteAddr->size;
PUSH_STATIC_BUFFER("\r\n");
}
if (req->envvars != NULL) {
PUSH_STATIC_BUFFER("!~Passenger-Envvars: ");
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) req->envvars->start->data;
buffers[i].iov_len = req->envvars->size;
}
INC_BUFFER_ITER(i);
dataSize += req->envvars->size;
PUSH_STATIC_BUFFER("\r\n");
}
if (req->options.analytics) {
PUSH_STATIC_BUFFER("!~Passenger-Txn-Id: ");
if (buffers != NULL) {
BEGIN_PUSH_NEXT_BUFFER();
buffers[i].iov_base = (void *) req->options.transaction->getTxnId().data();
buffers[i].iov_len = req->options.transaction->getTxnId().size();
}
INC_BUFFER_ITER(i);
dataSize += req->options.transaction->getTxnId().size();
PUSH_STATIC_BUFFER("\r\n");
}
PUSH_STATIC_BUFFER("\r\n");
nbuffers = i;
return true;
#undef BEGIN_PUSH_NEXT_BUFFER
#undef INC_BUFFER_ITER
#undef PUSH_STATIC_BUFFER
}
bool
Controller::sendHeaderToAppWithHttpProtocolAndWritev(Request *req, ssize_t &bytesWritten,
HttpHeaderConstructionCache &cache)
{
unsigned int maxbuffers = std::min<unsigned int>(
5 + req->headers.size() * 4 + 4, IOV_MAX);
struct iovec *buffers = (struct iovec *) psg_palloc(req->pool,
sizeof(struct iovec) * maxbuffers);
unsigned int nbuffers, dataSize;
if (constructHeaderBuffersForHttpProtocol(req, buffers,
maxbuffers, nbuffers, dataSize, cache))
{
ssize_t ret;
do {
ret = writev(req->session->fd(), buffers, nbuffers);
} while (ret == -1 && errno == EINTR);
bytesWritten = ret;
return ret == (ssize_t) dataSize;
} else {
bytesWritten = 0;
return false;
}
}
void
Controller::sendHeaderToAppWithHttpProtocolWithBuffering(Request *req,
unsigned int offset, HttpHeaderConstructionCache &cache)
{
struct iovec *buffers;
unsigned int nbuffers, dataSize;
bool ok;
ok = constructHeaderBuffersForHttpProtocol(req, NULL, 0, nbuffers,
dataSize, cache);
assert(ok);
buffers = (struct iovec *) psg_palloc(req->pool,
sizeof(struct iovec) * nbuffers);
ok = constructHeaderBuffersForHttpProtocol(req, buffers, nbuffers,
nbuffers, dataSize, cache);
assert(ok);
(void) ok; // Shut up compiler warning
MemoryKit::mbuf_pool &mbuf_pool = getContext()->mbuf_pool;
const unsigned int MBUF_MAX_SIZE = mbuf_pool_data_size(&mbuf_pool);
if (dataSize <= MBUF_MAX_SIZE) {
MemoryKit::mbuf buffer(MemoryKit::mbuf_get(&mbuf_pool));
gatherBuffers(buffer.start, MBUF_MAX_SIZE, buffers, nbuffers);
buffer = MemoryKit::mbuf(buffer, offset, dataSize - offset);
req->appSink.feedWithoutRefGuard(boost::move(buffer));
} else {
char *buffer = (char *) psg_pnalloc(req->pool, dataSize);
gatherBuffers(buffer, dataSize, buffers, nbuffers);
req->appSink.feedWithoutRefGuard(MemoryKit::mbuf(
buffer + offset, dataSize - offset));
}
}
void
Controller::sendBodyToApp(Client *client, Request *req) {
TRACE_POINT();
assert(req->appSink.acceptingInput());
#ifdef DEBUG_CC_EVENT_LOOP_BLOCKING
req->timeOnRequestHeaderSent = ev_now(getLoop());
reportLargeTimeDiff(client,
"ApplicationPool get until headers sent",
req->timeBeforeAccessingApplicationPool,
req->timeOnRequestHeaderSent);
#endif
if (req->hasBody() || req->upgraded()) {
// onRequestBody() will take care of forwarding
// the request body to the app.
SKC_TRACE(client, 2, "Sending body to application");
req->state = Request::FORWARDING_BODY_TO_APP;
startBodyChannel(client, req);
} else {
// Our task is done. ForwardResponse.cpp will take
// care of ending the request, once all response
// data is forwarded.
SKC_TRACE(client, 2, "No body to send to application");
req->state = Request::WAITING_FOR_APP_OUTPUT;
halfCloseAppSink(client, req);
}
}
void
Controller::halfCloseAppSink(Client *client, Request *req) {
P_ASSERT_EQ(req->state, Request::WAITING_FOR_APP_OUTPUT);
if (req->halfCloseAppConnection) {
SKC_TRACE(client, 3, "Half-closing application socket with SHUT_WR");
::shutdown(req->session->fd(), SHUT_WR);
}
}
ServerKit::Channel::Result
Controller::whenSendingRequest_onRequestBody(Client *client, Request *req,
const MemoryKit::mbuf &buffer, int errcode)
{
TRACE_POINT();
if (buffer.size() > 0) {
// Data
if (req->bodyType == Request::RBT_CONTENT_LENGTH) {
SKC_TRACE(client, 3, "Forwarding " << buffer.size() <<
" bytes of client request body (" << req->bodyAlreadyRead <<
" of " << req->aux.bodyInfo.contentLength << " bytes forwarded in total): \"" <<
cEscapeString(StaticString(buffer.start, buffer.size())) <<
"\"");
} else {
SKC_TRACE(client, 3, "Forwarding " << buffer.size() <<
" bytes of client request body (" << req->bodyAlreadyRead <<
" bytes forwarded in total): \"" <<
cEscapeString(StaticString(buffer.start, buffer.size())) <<
"\"");
}
req->appSink.feed(buffer);
if (!req->appSink.acceptingInput()) {
if (req->appSink.mayAcceptInputLater()) {
SKC_TRACE(client, 3, "Waiting for appSink channel to become "
"idle before continuing sending body to application");
req->appSink.setConsumedCallback(resumeRequestBodyChannelWhenAppSinkIdle);
stopBodyChannel(client, req);
return Channel::Result(buffer.size(), false);
} else {
// Either we're done feeding to req->appSink, or req->appSink.feed()
// encountered an error while writing to the application socket.
// But we don't care about either scenarios; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
assert(!req->ended());
assert(req->appSink.hasError());
logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
stopBodyChannel(client, req);
}
}
return Channel::Result(buffer.size(), false);
} else if (errcode == 0 || errcode == ECONNRESET) {
// EOF
SKC_TRACE(client, 2, "End of request body encountered");
// Our task is done. ForwardResponse.cpp will take
// care of ending the request, once all response
// data is forwarded.
req->state = Request::WAITING_FOR_APP_OUTPUT;
halfCloseAppSink(client, req);
return Channel::Result(0, true);
} else {
const unsigned int BUFSIZE = 1024;
char *message = (char *) psg_pnalloc(req->pool, BUFSIZE);
int size = snprintf(message, BUFSIZE,
"error reading request body: %s (errno=%d)",
ServerKit::getErrorDesc(errcode), errcode);
disconnectWithError(&client, StaticString(message, size));
return Channel::Result(0, true);
}
}
void
Controller::resumeRequestBodyChannelWhenAppSinkIdle(Channel *_channel,
unsigned int size)
{
FdSinkChannel *channel = reinterpret_cast<FdSinkChannel *>(_channel);
Request *req = static_cast<Request *>(static_cast<
ServerKit::BaseHttpRequest *>(channel->getHooks()->userData));
Client *client = static_cast<Client *>(req->client);
Controller *self = static_cast<Controller *>(getServerFromClient(client));
SKC_LOG_EVENT_FROM_STATIC(self, Controller, client, "resumeRequestBodyChannelWhenAppSinkIdle");
P_ASSERT_EQ(req->state, Request::FORWARDING_BODY_TO_APP);
req->appSink.setConsumedCallback(NULL);
if (req->appSink.acceptingInput()) {
self->startBodyChannel(client, req);
} else {
// Either we're done feeding to req->appSink, or req->appSink.feed()
// encountered an error while writing to the application socket.
// But we don't care about either scenarios; we just care that
// ForwardResponse.cpp will now forward the response data and end the
// request when it's done.
assert(!req->ended());
assert(req->appSink.hasError());
self->logAppSocketWriteError(client, req->appSink.getErrcode());
req->state = Request::WAITING_FOR_APP_OUTPUT;
}
}
void
Controller::startBodyChannel(Client *client, Request *req) {
if (req->requestBodyBuffering) {
req->bodyBuffer.start();
} else {
req->bodyChannel.start();
}
}
void
Controller::stopBodyChannel(Client *client, Request *req) {
if (req->requestBodyBuffering) {
req->bodyBuffer.stop();
} else {
req->bodyChannel.stop();
}
}
void
Controller::logAppSocketWriteError(Client *client, int errcode) {
if (errcode == EPIPE) {
SKC_INFO(client,
"App socket write error: the application closed the socket prematurely"
" (Broken pipe; errno=" << errcode << ")");
} else {
SKC_INFO(client, "App socket write error: " << ServerKit::getErrorDesc(errcode) <<
" (errno=" << errcode << ")");
}
}
} // namespace Core
} // namespace Passenger
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1749_1 |
crossvul-cpp_data_bad_239_1 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/IRCSock.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Server.h>
#include <znc/Query.h>
#include <znc/ZNCDebug.h>
#include <time.h>
using std::set;
using std::vector;
using std::map;
#define IRCSOCKMODULECALL(macFUNC, macEXITER) \
NETWORKMODULECALL(macFUNC, m_pNetwork->GetUser(), m_pNetwork, nullptr, \
macEXITER)
// These are used in OnGeneralCTCP()
const time_t CIRCSock::m_uCTCPFloodTime = 5;
const unsigned int CIRCSock::m_uCTCPFloodCount = 5;
// It will be bad if user sets it to 0.00000000000001
// If you want no flood protection, set network's flood rate to -1
// TODO move this constant to CIRCNetwork?
static const double FLOOD_MINIMAL_RATE = 0.3;
class CIRCFloodTimer : public CCron {
CIRCSock* m_pSock;
public:
CIRCFloodTimer(CIRCSock* pSock) : m_pSock(pSock) {
StartMaxCycles(m_pSock->m_fFloodRate, 0);
}
CIRCFloodTimer(const CIRCFloodTimer&) = delete;
CIRCFloodTimer& operator=(const CIRCFloodTimer&) = delete;
void RunJob() override {
if (m_pSock->m_iSendsAllowed < m_pSock->m_uFloodBurst) {
m_pSock->m_iSendsAllowed++;
}
m_pSock->TrySend();
}
};
bool CIRCSock::IsFloodProtected(double fRate) {
return fRate > FLOOD_MINIMAL_RATE;
}
CIRCSock::CIRCSock(CIRCNetwork* pNetwork)
: CIRCSocket(),
m_bAuthed(false),
m_bNamesx(false),
m_bUHNames(false),
m_bAwayNotify(false),
m_bAccountNotify(false),
m_bExtendedJoin(false),
m_bServerTime(false),
m_sPerms("*!@%+"),
m_sPermModes("qaohv"),
m_scUserModes(),
m_mceChanModes(),
m_pNetwork(pNetwork),
m_Nick(),
m_sPass(""),
m_msChans(),
m_uMaxNickLen(9),
m_uCapPaused(0),
m_ssAcceptedCaps(),
m_ssPendingCaps(),
m_lastCTCP(0),
m_uNumCTCP(0),
m_mISupport(),
m_vSendQueue(),
m_iSendsAllowed(pNetwork->GetFloodBurst()),
m_uFloodBurst(pNetwork->GetFloodBurst()),
m_fFloodRate(pNetwork->GetFloodRate()),
m_bFloodProtection(IsFloodProtected(pNetwork->GetFloodRate())) {
EnableReadLine();
m_Nick.SetIdent(m_pNetwork->GetIdent());
m_Nick.SetHost(m_pNetwork->GetBindHost());
SetEncoding(m_pNetwork->GetEncoding());
m_mceChanModes['b'] = ListArg;
m_mceChanModes['e'] = ListArg;
m_mceChanModes['I'] = ListArg;
m_mceChanModes['k'] = HasArg;
m_mceChanModes['l'] = ArgWhenSet;
m_mceChanModes['p'] = NoArg;
m_mceChanModes['s'] = NoArg;
m_mceChanModes['t'] = NoArg;
m_mceChanModes['i'] = NoArg;
m_mceChanModes['n'] = NoArg;
pNetwork->SetIRCSocket(this);
// RFC says a line can have 512 chars max + 512 chars for message tags, but
// we don't care ;)
SetMaxBufferThreshold(2048);
if (m_bFloodProtection) {
AddCron(new CIRCFloodTimer(this));
}
}
CIRCSock::~CIRCSock() {
if (!m_bAuthed) {
IRCSOCKMODULECALL(OnIRCConnectionError(this), NOTHING);
}
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
pChan->Reset();
}
m_pNetwork->IRCDisconnected();
for (const auto& it : m_msChans) {
delete it.second;
}
Quit();
m_msChans.clear();
m_pNetwork->AddBytesRead(GetBytesRead());
m_pNetwork->AddBytesWritten(GetBytesWritten());
}
void CIRCSock::Quit(const CString& sQuitMsg) {
if (IsClosed()) {
return;
}
if (!m_bAuthed) {
Close(CLT_NOW);
return;
}
if (!sQuitMsg.empty()) {
PutIRC("QUIT :" + sQuitMsg);
} else {
PutIRC("QUIT :" + m_pNetwork->ExpandString(m_pNetwork->GetQuitMsg()));
}
Close(CLT_AFTERWRITE);
}
void CIRCSock::ReadLine(const CString& sData) {
CString sLine = sData;
sLine.TrimRight("\n\r");
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") IRC -> ZNC [" << sLine << "]");
bool bReturn = false;
IRCSOCKMODULECALL(OnRaw(sLine), &bReturn);
if (bReturn) return;
CMessage Message(sLine);
Message.SetNetwork(m_pNetwork);
IRCSOCKMODULECALL(OnRawMessage(Message), &bReturn);
if (bReturn) return;
switch (Message.GetType()) {
case CMessage::Type::Account:
bReturn = OnAccountMessage(Message);
break;
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::Away:
bReturn = OnAwayMessage(Message);
break;
case CMessage::Type::Capability:
bReturn = OnCapabilityMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Error:
bReturn = OnErrorMessage(Message);
break;
case CMessage::Type::Invite:
bReturn = OnInviteMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Kick:
bReturn = OnKickMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Nick:
bReturn = OnNickMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Numeric:
bReturn = OnNumericMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
case CMessage::Type::Wallops:
bReturn = OnWallopsMessage(Message);
break;
default:
break;
}
if (bReturn) return;
m_pNetwork->PutUser(Message);
}
void CIRCSock::SendNextCap() {
if (!m_uCapPaused) {
if (m_ssPendingCaps.empty()) {
// We already got all needed ACK/NAK replies.
PutIRC("CAP END");
} else {
CString sCap = *m_ssPendingCaps.begin();
m_ssPendingCaps.erase(m_ssPendingCaps.begin());
PutIRC("CAP REQ :" + sCap);
}
}
}
void CIRCSock::PauseCap() { ++m_uCapPaused; }
void CIRCSock::ResumeCap() {
--m_uCapPaused;
SendNextCap();
}
bool CIRCSock::OnServerCapAvailable(const CString& sCap) {
bool bResult = false;
IRCSOCKMODULECALL(OnServerCapAvailable(sCap), &bResult);
return bResult;
}
// #124: OnChanMsg(): nick doesn't have perms
static void FixupChanNick(CNick& Nick, CChan* pChan) {
// A channel nick has up-to-date channel perms, but might be
// lacking (usernames-in-host) the associated ident & host.
// An incoming message, on the other hand, has normally a full
// nick!ident@host prefix. Sync the two so that channel nicks
// get the potentially missing piece of info and module hooks
// get the perms.
CNick* pChanNick = pChan->FindNick(Nick.GetNick());
if (pChanNick) {
if (!Nick.GetIdent().empty()) {
pChanNick->SetIdent(Nick.GetIdent());
}
if (!Nick.GetHost().empty()) {
pChanNick->SetHost(Nick.GetHost());
}
Nick.Clone(*pChanNick);
}
}
bool CIRCSock::OnAccountMessage(CMessage& Message) {
// TODO: IRCSOCKMODULECALL(OnAccountMessage(Message)) ?
return false;
}
bool CIRCSock::OnActionMessage(CActionMessage& Message) {
bool bResult = false;
CChan* pChan = nullptr;
CString sTarget = Message.GetTarget();
if (sTarget.Equals(GetNick())) {
IRCSOCKMODULECALL(OnPrivCTCPMessage(Message), &bResult);
if (bResult) return true;
IRCSOCKMODULECALL(OnPrivActionMessage(Message), &bResult);
if (bResult) return true;
if (!m_pNetwork->IsUserOnline() ||
!m_pNetwork->GetUser()->AutoClearQueryBuffer()) {
const CNick& Nick = Message.GetNick();
CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick());
if (pQuery) {
CActionMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Nick.GetNickMask()));
Format.SetTarget("{target}");
Format.SetText("{text}");
pQuery->AddBuffer(Format, Message.GetText());
}
}
} else {
pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanCTCPMessage(Message), &bResult);
if (bResult) return true;
IRCSOCKMODULECALL(OnChanActionMessage(Message), &bResult);
if (bResult) return true;
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() ||
pChan->IsDetached()) {
CActionMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask()));
Format.SetTarget(_NAMEDFMT(Message.GetTarget()));
Format.SetText("{text}");
pChan->AddBuffer(Format, Message.GetText());
}
}
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnAwayMessage(CMessage& Message) {
// TODO: IRCSOCKMODULECALL(OnAwayMessage(Message)) ?
return false;
}
bool CIRCSock::OnCapabilityMessage(CMessage& Message) {
// CAPs are supported only before authorization.
if (!m_bAuthed) {
// The first parameter is most likely "*". No idea why, the
// CAP spec don't mention this, but all implementations
// I've seen add this extra asterisk
CString sSubCmd = Message.GetParam(1);
// If the caplist of a reply is too long, it's split
// into multiple replies. A "*" is prepended to show
// that the list was split into multiple replies.
// This is useful mainly for LS. For ACK and NAK
// replies, there's no real need for this, because
// we request only 1 capability per line.
// If we will need to support broken servers or will
// send several requests per line, need to delay ACK
// actions until all ACK lines are received and
// to recognize past request of NAK by 100 chars
// of this reply.
CString sArgs;
if (Message.GetParam(2) == "*") {
sArgs = Message.GetParam(3);
} else {
sArgs = Message.GetParam(2);
}
std::map<CString, std::function<void(bool bVal)>> mSupportedCaps = {
{"multi-prefix", [this](bool bVal) { m_bNamesx = bVal; }},
{"userhost-in-names", [this](bool bVal) { m_bUHNames = bVal; }},
{"away-notify", [this](bool bVal) { m_bAwayNotify = bVal; }},
{"account-notify", [this](bool bVal) { m_bAccountNotify = bVal; }},
{"extended-join", [this](bool bVal) { m_bExtendedJoin = bVal; }},
{"server-time", [this](bool bVal) { m_bServerTime = bVal; }},
{"znc.in/server-time-iso",
[this](bool bVal) { m_bServerTime = bVal; }},
};
if (sSubCmd == "LS") {
VCString vsTokens;
sArgs.Split(" ", vsTokens, false);
for (const CString& sCap : vsTokens) {
if (OnServerCapAvailable(sCap) || mSupportedCaps.count(sCap)) {
m_ssPendingCaps.insert(sCap);
}
}
} else if (sSubCmd == "ACK") {
sArgs.Trim();
IRCSOCKMODULECALL(OnServerCapResult(sArgs, true), NOTHING);
const auto& it = mSupportedCaps.find(sArgs);
if (it != mSupportedCaps.end()) {
it->second(true);
}
m_ssAcceptedCaps.insert(sArgs);
} else if (sSubCmd == "NAK") {
// This should work because there's no [known]
// capability with length of name more than 100 characters.
sArgs.Trim();
IRCSOCKMODULECALL(OnServerCapResult(sArgs, false), NOTHING);
}
SendNextCap();
}
// Don't forward any CAP stuff to the client
return true;
}
bool CIRCSock::OnCTCPMessage(CCTCPMessage& Message) {
bool bResult = false;
CChan* pChan = nullptr;
CString sTarget = Message.GetTarget();
if (sTarget.Equals(GetNick())) {
if (Message.IsReply()) {
IRCSOCKMODULECALL(OnCTCPReplyMessage(Message), &bResult);
return bResult;
} else {
IRCSOCKMODULECALL(OnPrivCTCPMessage(Message), &bResult);
if (bResult) return true;
}
} else {
pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanCTCPMessage(Message), &bResult);
if (bResult) return true;
}
}
const CNick& Nick = Message.GetNick();
const CString& sMessage = Message.GetText();
const MCString& mssCTCPReplies = m_pNetwork->GetUser()->GetCTCPReplies();
CString sQuery = sMessage.Token(0).AsUpper();
MCString::const_iterator it = mssCTCPReplies.find(sQuery);
bool bHaveReply = false;
CString sReply;
if (it != mssCTCPReplies.end()) {
sReply = m_pNetwork->ExpandString(it->second);
bHaveReply = true;
if (sReply.empty()) {
return true;
}
}
if (!bHaveReply && !m_pNetwork->IsUserAttached()) {
if (sQuery == "VERSION") {
sReply = CZNC::GetTag(false);
} else if (sQuery == "PING") {
sReply = sMessage.Token(1, true);
}
}
if (!sReply.empty()) {
time_t now = time(nullptr);
// If the last CTCP is older than m_uCTCPFloodTime, reset the counter
if (m_lastCTCP + m_uCTCPFloodTime < now) m_uNumCTCP = 0;
m_lastCTCP = now;
// If we are over the limit, don't reply to this CTCP
if (m_uNumCTCP >= m_uCTCPFloodCount) {
DEBUG("CTCP flood detected - not replying to query");
return true;
}
m_uNumCTCP++;
PutIRC("NOTICE " + Nick.GetNick() + " :\001" + sQuery + " " + sReply +
"\001");
return true;
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnErrorMessage(CMessage& Message) {
// ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
CString sError = Message.GetParam(0);
m_pNetwork->PutStatus(t_f("Error from server: {1}")(sError));
return true;
}
bool CIRCSock::OnInviteMessage(CMessage& Message) {
bool bResult = false;
IRCSOCKMODULECALL(OnInvite(Message.GetNick(), Message.GetParam(1)),
&bResult);
return bResult;
}
bool CIRCSock::OnJoinMessage(CJoinMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sChan = Message.GetParam(0);
CChan* pChan = nullptr;
if (Nick.NickEquals(GetNick())) {
m_pNetwork->AddChan(sChan, false);
pChan = m_pNetwork->FindChan(sChan);
if (pChan) {
pChan->Enable();
pChan->SetIsOn(true);
PutIRC("MODE " + sChan);
}
} else {
pChan = m_pNetwork->FindChan(sChan);
}
if (pChan) {
pChan->AddNick(Nick.GetNickMask());
Message.SetChan(pChan);
IRCSOCKMODULECALL(OnJoinMessage(Message), NOTHING);
if (pChan->IsDetached()) {
return true;
}
}
return false;
}
bool CIRCSock::OnKickMessage(CKickMessage& Message) {
CString sChan = Message.GetParam(0);
CString sKickedNick = Message.GetKickedNick();
CChan* pChan = m_pNetwork->FindChan(sChan);
if (pChan) {
Message.SetChan(pChan);
IRCSOCKMODULECALL(OnKickMessage(Message), NOTHING);
// do not remove the nick till after the OnKick call, so modules
// can do Chan.FindNick or something to get more info.
pChan->RemNick(sKickedNick);
}
if (GetNick().Equals(sKickedNick) && pChan) {
pChan->SetIsOn(false);
// Don't try to rejoin!
pChan->Disable();
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnModeMessage(CModeMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sTarget = Message.GetTarget();
CString sModes = Message.GetModes();
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
pChan->ModeChange(sModes, &Nick);
if (pChan->IsDetached()) {
return true;
}
} else if (sTarget == m_Nick.GetNick()) {
CString sModeArg = sModes.Token(0);
bool bAdd = true;
/* no module call defined (yet?)
MODULECALL(OnRawUserMode(*pOpNick, *this, sModeArg, sArgs),
m_pNetwork->GetUser(), nullptr, );
*/
for (unsigned int a = 0; a < sModeArg.size(); a++) {
const char& cMode = sModeArg[a];
if (cMode == '+') {
bAdd = true;
} else if (cMode == '-') {
bAdd = false;
} else {
if (bAdd) {
m_scUserModes.insert(cMode);
} else {
m_scUserModes.erase(cMode);
}
}
}
}
return false;
}
bool CIRCSock::OnNickMessage(CNickMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sNewNick = Message.GetNewNick();
bool bIsVisible = false;
vector<CChan*> vFoundChans;
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
if (pChan->ChangeNick(Nick.GetNick(), sNewNick)) {
vFoundChans.push_back(pChan);
if (!pChan->IsDetached()) {
bIsVisible = true;
}
}
}
if (Nick.NickEquals(GetNick())) {
// We are changing our own nick, the clients always must see this!
bIsVisible = false;
SetNick(sNewNick);
m_pNetwork->PutUser(Message);
}
IRCSOCKMODULECALL(OnNickMessage(Message, vFoundChans), NOTHING);
return !bIsVisible;
}
bool CIRCSock::OnNoticeMessage(CNoticeMessage& Message) {
CString sTarget = Message.GetTarget();
bool bResult = false;
if (sTarget.Equals(GetNick())) {
IRCSOCKMODULECALL(OnPrivNoticeMessage(Message), &bResult);
if (bResult) return true;
if (!m_pNetwork->IsUserOnline()) {
// If the user is detached, add to the buffer
CNoticeMessage Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(Message.GetNick().GetNickMask())));
Format.SetTarget("{target}");
Format.SetText("{text}");
m_pNetwork->AddNoticeBuffer(Format, Message.GetText());
}
return false;
} else {
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanNoticeMessage(Message), &bResult);
if (bResult) return true;
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() ||
pChan->IsDetached()) {
CNoticeMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask()));
Format.SetTarget(_NAMEDFMT(Message.GetTarget()));
Format.SetText("{text}");
pChan->AddBuffer(Format, Message.GetText());
}
}
return (pChan && pChan->IsDetached());
}
}
static CMessage BufferMessage(const CNumericMessage& Message) {
CMessage Format(Message);
Format.SetNick(CNick(_NAMEDFMT(Message.GetNick().GetHostMask())));
Format.SetParam(0, "{target}");
unsigned uParams = Format.GetParams().size();
for (unsigned int i = 1; i < uParams; ++i) {
Format.SetParam(i, _NAMEDFMT(Format.GetParam(i)));
}
return Format;
}
bool CIRCSock::OnNumericMessage(CNumericMessage& Message) {
const CString& sCmd = Message.GetCommand();
CString sServer = Message.GetNick().GetHostMask();
unsigned int uRaw = Message.GetCode();
CString sNick = Message.GetParam(0);
bool bResult = false;
IRCSOCKMODULECALL(OnNumericMessage(Message), &bResult);
if (bResult) return true;
switch (uRaw) {
case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay
if (m_bAuthed && sServer == "irc.znc.in") {
// m_bAuthed == true => we already received another 001 => we
// might be in a traffic loop
m_pNetwork->PutStatus(t_s(
"ZNC seems to be connected to itself, disconnecting..."));
Quit();
return true;
}
m_pNetwork->SetIRCServer(sServer);
// Now that we are connected, let nature take its course
SetTimeout(m_pNetwork->GetUser()->GetNoTrafficTimeout(), TMO_READ);
PutIRC("WHO " + sNick);
m_bAuthed = true;
m_pNetwork->PutStatus("Connected!");
const vector<CClient*>& vClients = m_pNetwork->GetClients();
for (CClient* pClient : vClients) {
CString sClientNick = pClient->GetNick(false);
if (!sClientNick.Equals(sNick)) {
// If they connected with a nick that doesn't match the one
// we got on irc, then we need to update them
pClient->PutClient(":" + sClientNick + "!" +
m_Nick.GetIdent() + "@" +
m_Nick.GetHost() + " NICK :" + sNick);
}
}
SetNick(sNick);
IRCSOCKMODULECALL(OnIRCConnected(), NOTHING);
m_pNetwork->ClearRawBuffer();
m_pNetwork->AddRawBuffer(BufferMessage(Message));
m_pNetwork->IRCConnected();
break;
}
case 5:
ParseISupport(Message);
m_pNetwork->UpdateExactRawBuffer(BufferMessage(Message));
break;
case 10: { // :irc.server.com 010 nick <hostname> <port> :<info>
CString sHost = Message.GetParam(1);
CString sPort = Message.GetParam(2);
CString sInfo = Message.GetParam(3);
m_pNetwork->PutStatus(
t_f("Server {1} redirects us to {2}:{3} with reason: {4}")(
m_pNetwork->GetCurrentServer()->GetString(false), sHost,
sPort, sInfo));
m_pNetwork->PutStatus(
t_s("Perhaps you want to add it as a new server."));
// Don't send server redirects to the client
return true;
}
case 2:
case 3:
case 4:
case 250: // highest connection count
case 251: // user count
case 252: // oper count
case 254: // channel count
case 255: // client count
case 265: // local users
case 266: // global users
m_pNetwork->UpdateRawBuffer(sCmd, BufferMessage(Message));
break;
case 305:
m_pNetwork->SetIRCAway(false);
break;
case 306:
m_pNetwork->SetIRCAway(true);
break;
case 324: { // MODE
// :irc.server.com 324 nick #chan +nstk key
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
pChan->SetModes(Message.GetParamsColon(2));
// We don't SetModeKnown(true) here,
// because a 329 will follow
if (!pChan->IsModeKnown()) {
// When we JOIN, we send a MODE
// request. This makes sure the
// reply isn't forwarded.
return true;
}
if (pChan->IsDetached()) {
return true;
}
}
} break;
case 329: {
// :irc.server.com 329 nick #chan 1234567890
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
unsigned long ulDate = Message.GetParam(2).ToULong();
pChan->SetCreationDate(ulDate);
if (!pChan->IsModeKnown()) {
pChan->SetModeKnown(true);
// When we JOIN, we send a MODE
// request. This makes sure the
// reply isn't forwarded.
return true;
}
if (pChan->IsDetached()) {
return true;
}
}
} break;
case 331: {
// :irc.server.com 331 yournick #chan :No topic is set.
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
pChan->SetTopic("");
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 332: {
// :irc.server.com 332 yournick #chan :This is a topic
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
CString sTopic = Message.GetParam(2);
pChan->SetTopic(sTopic);
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 333: {
// :irc.server.com 333 yournick #chan setternick 1112320796
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
sNick = Message.GetParam(2);
unsigned long ulDate = Message.GetParam(3).ToULong();
pChan->SetTopicOwner(sNick);
pChan->SetTopicDate(ulDate);
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 352: { // WHO
// :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name
sNick = Message.GetParam(5);
CString sChan = Message.GetParam(1);
CString sIdent = Message.GetParam(2);
CString sHost = Message.GetParam(3);
if (sNick.Equals(GetNick())) {
m_Nick.SetIdent(sIdent);
m_Nick.SetHost(sHost);
}
m_pNetwork->SetIRCNick(m_Nick);
m_pNetwork->SetIRCServer(sServer);
// A nick can only have one ident and hostname. Yes, you can query
// this information per-channel, but it is still global. For
// example, if the client supports UHNAMES, but the IRC server does
// not, then AFAIR "passive snooping of WHO replies" is the only way
// that ZNC can figure out the ident and host for the UHNAMES
// replies.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
pChan->OnWho(sNick, sIdent, sHost);
}
CChan* pChan = m_pNetwork->FindChan(sChan);
if (pChan && pChan->IsDetached()) {
return true;
}
break;
}
case 353: { // NAMES
// :irc.server.com 353 nick @ #chan :nick1 nick2
// Todo: allow for non @+= server msgs
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(2));
// If we don't know that channel, some client might have
// requested a /names for it and we really should forward this.
if (pChan) {
CString sNicks = Message.GetParam(3);
pChan->AddNicks(sNicks);
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 366: { // end of names list
// :irc.server.com 366 nick #chan :End of /NAMES list.
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
if (pChan->IsOn()) {
// If we are the only one in the chan, set our default modes
if (pChan->GetNickCount() == 1) {
CString sModes = pChan->GetDefaultModes();
if (sModes.empty()) {
sModes =
m_pNetwork->GetUser()->GetDefaultChanModes();
}
if (!sModes.empty()) {
PutIRC("MODE " + pChan->GetName() + " " + sModes);
}
}
}
if (pChan->IsDetached()) {
// don't put it to clients
return true;
}
}
break;
}
case 375: // begin motd
case 422: // MOTD File is missing
if (m_pNetwork->GetIRCServer().Equals(sServer)) {
m_pNetwork->ClearMotdBuffer();
}
case 372: // motd
case 376: // end motd
if (m_pNetwork->GetIRCServer().Equals(sServer)) {
m_pNetwork->AddMotdBuffer(BufferMessage(Message));
}
break;
case 437:
// :irc.server.net 437 * badnick :Nick/channel is temporarily unavailable
// :irc.server.net 437 mynick badnick :Nick/channel is temporarily unavailable
// :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel
if (m_pNetwork->IsChan(Message.GetParam(1)) || sNick != "*") break;
case 432:
// :irc.server.com 432 * nick :Erroneous Nickname: Illegal chars
case 433: {
CString sBadNick = Message.GetParam(1);
if (!m_bAuthed) {
SendAltNick(sBadNick);
return true;
}
break;
}
case 451:
// :irc.server.com 451 CAP :You have not registered
// Servers that don't support CAP will give us this error, don't send
// it to the client
if (sNick.Equals("CAP")) return true;
case 470: {
// :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to the linked channel #chan2
// :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel
// freenode style numeric
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (!pChan) {
// unreal style numeric
pChan = m_pNetwork->FindChan(Message.GetParam(2));
}
if (pChan) {
pChan->Disable();
m_pNetwork->PutStatus(
t_f("Channel {1} is linked to another channel and was thus "
"disabled.")(pChan->GetName()));
}
break;
}
case 670:
// :hydra.sector5d.org 670 kylef :STARTTLS successful, go ahead with TLS handshake
//
// 670 is a response to `STARTTLS` telling the client to switch to
// TLS
if (!GetSSL()) {
StartTLS();
m_pNetwork->PutStatus(t_s("Switched to SSL (STARTTLS)"));
}
return true;
}
return false;
}
bool CIRCSock::OnPartMessage(CPartMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sChan = Message.GetTarget();
CChan* pChan = m_pNetwork->FindChan(sChan);
bool bDetached = false;
if (pChan) {
pChan->RemNick(Nick.GetNick());
Message.SetChan(pChan);
IRCSOCKMODULECALL(OnPartMessage(Message), NOTHING);
if (pChan->IsDetached()) bDetached = true;
}
if (Nick.NickEquals(GetNick())) {
m_pNetwork->DelChan(sChan);
}
/*
* We use this boolean because
* m_pNetwork->DelChan() will delete this channel
* and thus we would dereference an
* already-freed pointer!
*/
return bDetached;
}
bool CIRCSock::OnPingMessage(CMessage& Message) {
// Generate a reply and don't forward this to any user,
// we don't want any PING forwarded
PutIRCQuick("PONG " + Message.GetParam(0));
return true;
}
bool CIRCSock::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CIRCSock::OnQuitMessage(CQuitMessage& Message) {
const CNick& Nick = Message.GetNick();
bool bIsVisible = false;
if (Nick.NickEquals(GetNick())) {
m_pNetwork->PutStatus(t_f("You quit: {1}")(Message.GetReason()));
// We don't call module hooks and we don't
// forward this quit to clients (Some clients
// disconnect if they receive such a QUIT)
return true;
}
vector<CChan*> vFoundChans;
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
if (pChan->RemNick(Nick.GetNick())) {
vFoundChans.push_back(pChan);
if (!pChan->IsDetached()) {
bIsVisible = true;
}
}
}
IRCSOCKMODULECALL(OnQuitMessage(Message, vFoundChans), NOTHING);
return !bIsVisible;
}
bool CIRCSock::OnTextMessage(CTextMessage& Message) {
bool bResult = false;
CChan* pChan = nullptr;
CString sTarget = Message.GetTarget();
if (sTarget.Equals(GetNick())) {
IRCSOCKMODULECALL(OnPrivTextMessage(Message), &bResult);
if (bResult) return true;
if (!m_pNetwork->IsUserOnline() ||
!m_pNetwork->GetUser()->AutoClearQueryBuffer()) {
const CNick& Nick = Message.GetNick();
CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick());
if (pQuery) {
CTextMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Nick.GetNickMask()));
Format.SetTarget("{target}");
Format.SetText("{text}");
pQuery->AddBuffer(Format, Message.GetText());
}
}
} else {
pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanTextMessage(Message), &bResult);
if (bResult) return true;
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() ||
pChan->IsDetached()) {
CTextMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask()));
Format.SetTarget(_NAMEDFMT(Message.GetTarget()));
Format.SetText("{text}");
pChan->AddBuffer(Format, Message.GetText());
}
}
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnTopicMessage(CTopicMessage& Message) {
const CNick& Nick = Message.GetNick();
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(0));
if (pChan) {
Message.SetChan(pChan);
bool bReturn = false;
IRCSOCKMODULECALL(OnTopicMessage(Message), &bReturn);
if (bReturn) return true;
pChan->SetTopicOwner(Nick.GetNick());
pChan->SetTopicDate((unsigned long)time(nullptr));
pChan->SetTopic(Message.GetTopic());
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnWallopsMessage(CMessage& Message) {
// :blub!dummy@rox-8DBEFE92 WALLOPS :this is a test
CString sMsg = Message.GetParam(0);
if (!m_pNetwork->IsUserOnline()) {
CMessage Format(Message);
Format.SetNick(CNick(_NAMEDFMT(Message.GetNick().GetHostMask())));
Format.SetParam(0, "{text}");
m_pNetwork->AddNoticeBuffer(Format, sMsg);
}
return false;
}
void CIRCSock::PutIRC(const CString& sLine) {
PutIRC(CMessage(sLine));
}
void CIRCSock::PutIRC(const CMessage& Message) {
// Only print if the line won't get sent immediately (same condition as in
// TrySend()!)
if (m_bFloodProtection && m_iSendsAllowed <= 0) {
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") ZNC -> IRC ["
<< CDebug::Filter(Message.ToString()) << "] (queued)");
}
m_vSendQueue.push_back(Message);
TrySend();
}
void CIRCSock::PutIRCQuick(const CString& sLine) {
// Only print if the line won't get sent immediately (same condition as in
// TrySend()!)
if (m_bFloodProtection && m_iSendsAllowed <= 0) {
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") ZNC -> IRC ["
<< CDebug::Filter(sLine) << "] (queued to front)");
}
m_vSendQueue.emplace_front(sLine);
TrySend();
}
void CIRCSock::TrySend() {
// This condition must be the same as in PutIRC() and PutIRCQuick()!
while (!m_vSendQueue.empty() &&
(!m_bFloodProtection || m_iSendsAllowed > 0)) {
m_iSendsAllowed--;
CMessage& Message = m_vSendQueue.front();
MCString mssTags;
for (const auto& it : Message.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
Message.SetTags(mssTags);
Message.SetNetwork(m_pNetwork);
bool bSkip = false;
IRCSOCKMODULECALL(OnSendToIRCMessage(Message), &bSkip);
if (!bSkip) {
PutIRCRaw(Message.ToString());
}
m_vSendQueue.pop_front();
}
}
void CIRCSock::PutIRCRaw(const CString& sLine) {
CString sCopy = sLine;
bool bSkip = false;
IRCSOCKMODULECALL(OnSendToIRC(sCopy), &bSkip);
if (!bSkip) {
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") ZNC -> IRC ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
}
}
void CIRCSock::SetNick(const CString& sNick) {
m_Nick.SetNick(sNick);
m_pNetwork->SetIRCNick(m_Nick);
}
void CIRCSock::Connected() {
DEBUG(GetSockName() << " == Connected()");
CString sPass = m_sPass;
CString sNick = m_pNetwork->GetNick();
CString sIdent = m_pNetwork->GetIdent();
CString sRealName = m_pNetwork->GetRealName();
bool bReturn = false;
IRCSOCKMODULECALL(OnIRCRegistration(sPass, sNick, sIdent, sRealName),
&bReturn);
if (bReturn) return;
PutIRC("CAP LS");
if (!sPass.empty()) {
PutIRC("PASS " + sPass);
}
PutIRC("NICK " + sNick);
PutIRC("USER " + sIdent + " \"" + sIdent + "\" \"" + sIdent + "\" :" +
sRealName);
// SendAltNick() needs this
m_Nick.SetNick(sNick);
}
void CIRCSock::Disconnected() {
IRCSOCKMODULECALL(OnIRCDisconnected(), NOTHING);
DEBUG(GetSockName() << " == Disconnected()");
if (!m_pNetwork->GetUser()->IsBeingDeleted() &&
m_pNetwork->GetIRCConnectEnabled() &&
m_pNetwork->GetServers().size() != 0) {
m_pNetwork->PutStatus(t_s("Disconnected from IRC. Reconnecting..."));
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
ResetChans();
// send a "reset user modes" cmd to the client.
// otherwise, on reconnect, it might think it still
// had user modes that it actually doesn't have.
CString sUserMode;
for (char cMode : m_scUserModes) {
sUserMode += cMode;
}
if (!sUserMode.empty()) {
m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" MODE " + m_pNetwork->GetIRCNick().GetNick() +
" :-" + sUserMode);
}
// also clear the user modes in our space:
m_scUserModes.clear();
}
void CIRCSock::SockError(int iErrno, const CString& sDescription) {
CString sError = sDescription;
DEBUG(GetSockName() << " == SockError(" << iErrno << " " << sError << ")");
if (!m_pNetwork->GetUser()->IsBeingDeleted()) {
if (GetConState() != CST_OK) {
m_pNetwork->PutStatus(
t_f("Cannot connect to IRC ({1}). Retrying...")(sError));
} else {
m_pNetwork->PutStatus(
t_f("Disconnected from IRC ({1}). Reconnecting...")(sError));
}
#ifdef HAVE_LIBSSL
if (iErrno == errnoBadSSLCert) {
// Stringify bad cert
X509* pCert = GetX509();
if (pCert) {
BIO* mem = BIO_new(BIO_s_mem());
X509_print(mem, pCert);
X509_free(pCert);
char* pCertStr = nullptr;
long iLen = BIO_get_mem_data(mem, &pCertStr);
CString sCert(pCertStr, iLen);
BIO_free(mem);
VCString vsCert;
sCert.Split("\n", vsCert);
for (const CString& s : vsCert) {
// It shouldn't contain any bad characters, but let's be
// safe...
m_pNetwork->PutStatus("|" + s.Escape_n(CString::EDEBUG));
}
CString sSHA1;
if (GetPeerFingerprint(sSHA1))
m_pNetwork->PutStatus(
"SHA1: " +
sSHA1.Escape_n(CString::EHEXCOLON, CString::EHEXCOLON));
CString sSHA256 = GetSSLPeerFingerprint();
m_pNetwork->PutStatus("SHA-256: " + sSHA256);
m_pNetwork->PutStatus(
t_f("If you trust this certificate, do /znc "
"AddTrustedServerFingerprint {1}")(sSHA256));
}
}
#endif
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
ResetChans();
m_scUserModes.clear();
}
void CIRCSock::Timeout() {
DEBUG(GetSockName() << " == Timeout()");
if (!m_pNetwork->GetUser()->IsBeingDeleted()) {
m_pNetwork->PutStatus(
t_s("IRC connection timed out. Reconnecting..."));
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
ResetChans();
m_scUserModes.clear();
}
void CIRCSock::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
if (!m_pNetwork->GetUser()->IsBeingDeleted()) {
m_pNetwork->PutStatus(t_s("Connection Refused. Reconnecting..."));
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
}
void CIRCSock::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
m_pNetwork->PutStatus(t_s("Received a too long line from the IRC server!"));
Quit();
}
void CIRCSock::ParseISupport(const CMessage& Message) {
const VCString vsParams = Message.GetParams();
for (size_t i = 1; i + 1 < vsParams.size(); ++i) {
const CString& sParam = vsParams[i];
CString sName = sParam.Token(0, false, "=");
CString sValue = sParam.Token(1, true, "=");
if (0 < sName.length() && ':' == sName[0]) {
break;
}
m_mISupport[sName] = sValue;
if (sName.Equals("PREFIX")) {
CString sPrefixes = sValue.Token(1, false, ")");
CString sPermModes = sValue.Token(0, false, ")");
sPermModes.TrimLeft("(");
if (!sPrefixes.empty() && sPermModes.size() == sPrefixes.size()) {
m_sPerms = sPrefixes;
m_sPermModes = sPermModes;
}
} else if (sName.Equals("CHANTYPES")) {
m_pNetwork->SetChanPrefixes(sValue);
} else if (sName.Equals("NICKLEN")) {
unsigned int uMax = sValue.ToUInt();
if (uMax) {
m_uMaxNickLen = uMax;
}
} else if (sName.Equals("CHANMODES")) {
if (!sValue.empty()) {
m_mceChanModes.clear();
for (unsigned int a = 0; a < 4; a++) {
CString sModes = sValue.Token(a, false, ",");
for (unsigned int b = 0; b < sModes.size(); b++) {
m_mceChanModes[sModes[b]] = (EChanModeArgs)a;
}
}
}
} else if (sName.Equals("NAMESX")) {
if (m_bNamesx) continue;
m_bNamesx = true;
PutIRC("PROTOCTL NAMESX");
} else if (sName.Equals("UHNAMES")) {
if (m_bUHNames) continue;
m_bUHNames = true;
PutIRC("PROTOCTL UHNAMES");
}
}
}
CString CIRCSock::GetISupport(const CString& sKey,
const CString& sDefault) const {
MCString::const_iterator i = m_mISupport.find(sKey.AsUpper());
if (i == m_mISupport.end()) {
return sDefault;
} else {
return i->second;
}
}
void CIRCSock::SendAltNick(const CString& sBadNick) {
const CString& sLastNick = m_Nick.GetNick();
// We don't know the maximum allowed nick length yet, but we know which
// nick we sent last. If sBadNick is shorter than that, we assume the
// server truncated our nick.
if (sBadNick.length() < sLastNick.length())
m_uMaxNickLen = (unsigned int)sBadNick.length();
unsigned int uMax = m_uMaxNickLen;
const CString& sConfNick = m_pNetwork->GetNick();
const CString& sAltNick = m_pNetwork->GetAltNick();
CString sNewNick = sConfNick.Left(uMax - 1);
if (sLastNick.Equals(sConfNick)) {
if ((!sAltNick.empty()) && (!sConfNick.Equals(sAltNick))) {
sNewNick = sAltNick;
} else {
sNewNick += "-";
}
} else if (sLastNick.Equals(sAltNick) && !sAltNick.Equals(sNewNick + "-")) {
sNewNick += "-";
} else if (sLastNick.Equals(sNewNick + "-") &&
!sAltNick.Equals(sNewNick + "|")) {
sNewNick += "|";
} else if (sLastNick.Equals(sNewNick + "|") &&
!sAltNick.Equals(sNewNick + "^")) {
sNewNick += "^";
} else if (sLastNick.Equals(sNewNick + "^") &&
!sAltNick.Equals(sNewNick + "a")) {
sNewNick += "a";
} else {
char cLetter = 0;
if (sBadNick.empty()) {
m_pNetwork->PutUser(t_s("No free nick available"));
Quit();
return;
}
cLetter = sBadNick.back();
if (cLetter == 'z') {
m_pNetwork->PutUser(t_s("No free nick found"));
Quit();
return;
}
sNewNick = sConfNick.Left(uMax - 1) + ++cLetter;
if (sNewNick.Equals(sAltNick))
sNewNick = sConfNick.Left(uMax - 1) + ++cLetter;
}
PutIRC("NICK " + sNewNick);
m_Nick.SetNick(sNewNick);
}
char CIRCSock::GetPermFromMode(char cMode) const {
if (m_sPermModes.size() == m_sPerms.size()) {
for (unsigned int a = 0; a < m_sPermModes.size(); a++) {
if (m_sPermModes[a] == cMode) {
return m_sPerms[a];
}
}
}
return 0;
}
CIRCSock::EChanModeArgs CIRCSock::GetModeType(char cMode) const {
map<char, EChanModeArgs>::const_iterator it =
m_mceChanModes.find(cMode);
if (it == m_mceChanModes.end()) {
return NoArg;
}
return it->second;
}
void CIRCSock::ResetChans() {
for (const auto& it : m_msChans) {
it.second->Reset();
}
}
void CIRCSock::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_239_1 |
crossvul-cpp_data_good_1581_0 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: ParaNdis-Common.c
*
* This file contains NDIS driver procedures, common for NDIS5 and NDIS6
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
static VOID ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext);
static __inline pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue);
// TODO: remove when the problem solved
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue);
//#define ROUNDSIZE(sz) ((sz + 15) & ~15)
#define MAX_VLAN_ID 4095
#define ABSTRACT_PATHES_TAG 'APVR'
/**********************************************************
Validates MAC address
Valid MAC address is not broadcast, not multicast, not empty
if bLocal is set, it must be LOCAL
if not, is must be non-local or local
Parameters:
PUCHAR pcMacAddress - MAC address to validate
BOOLEAN bLocal - TRUE, if we validate locally administered address
Return value:
TRUE if valid
***********************************************************/
BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal)
{
BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE;
bBroadcast = ETH_IS_BROADCAST(pcMacAddress);
bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress);
bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress);
bEmpty = ETH_IS_EMPTY(pcMacAddress);
return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA);
}
typedef struct _tagConfigurationEntry
{
const char *Name;
ULONG ulValue;
ULONG ulMinimal;
ULONG ulMaximal;
}tConfigurationEntry;
typedef struct _tagConfigurationEntries
{
tConfigurationEntry PrioritySupport;
tConfigurationEntry ConnectRate;
tConfigurationEntry isLogEnabled;
tConfigurationEntry debugLevel;
tConfigurationEntry TxCapacity;
tConfigurationEntry RxCapacity;
tConfigurationEntry LogStatistics;
tConfigurationEntry OffloadTxChecksum;
tConfigurationEntry OffloadTxLSO;
tConfigurationEntry OffloadRxCS;
tConfigurationEntry stdIpcsV4;
tConfigurationEntry stdTcpcsV4;
tConfigurationEntry stdTcpcsV6;
tConfigurationEntry stdUdpcsV4;
tConfigurationEntry stdUdpcsV6;
tConfigurationEntry stdLsoV1;
tConfigurationEntry stdLsoV2ip4;
tConfigurationEntry stdLsoV2ip6;
tConfigurationEntry PriorityVlanTagging;
tConfigurationEntry VlanId;
tConfigurationEntry PublishIndices;
tConfigurationEntry MTU;
tConfigurationEntry NumberOfHandledRXPackersInDPC;
#if PARANDIS_SUPPORT_RSS
tConfigurationEntry RSSOffloadSupported;
tConfigurationEntry NumRSSQueues;
#endif
#if PARANDIS_SUPPORT_RSC
tConfigurationEntry RSCIPv4Supported;
tConfigurationEntry RSCIPv6Supported;
#endif
}tConfigurationEntries;
static const tConfigurationEntries defaultConfiguration =
{
{ "Priority", 0, 0, 1 },
{ "ConnectRate", 100,10,10000 },
{ "DoLog", 1, 0, 1 },
{ "DebugLevel", 2, 0, 8 },
{ "TxCapacity", 1024, 16, 1024 },
{ "RxCapacity", 256, 32, 1024 },
{ "LogStatistics", 0, 0, 10000},
{ "Offload.TxChecksum", 0, 0, 31},
{ "Offload.TxLSO", 0, 0, 2},
{ "Offload.RxCS", 0, 0, 31},
{ "*IPChecksumOffloadIPv4", 3, 0, 3 },
{ "*TCPChecksumOffloadIPv4",3, 0, 3 },
{ "*TCPChecksumOffloadIPv6",3, 0, 3 },
{ "*UDPChecksumOffloadIPv4",3, 0, 3 },
{ "*UDPChecksumOffloadIPv6",3, 0, 3 },
{ "*LsoV1IPv4", 1, 0, 1 },
{ "*LsoV2IPv4", 1, 0, 1 },
{ "*LsoV2IPv6", 1, 0, 1 },
{ "*PriorityVLANTag", 3, 0, 3},
{ "VlanId", 0, 0, MAX_VLAN_ID},
{ "PublishIndices", 1, 0, 1},
{ "MTU", 1500, 576, 65500},
{ "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000},
#if PARANDIS_SUPPORT_RSS
{ "*RSS", 1, 0, 1},
{ "*NumRssQueues", 8, 1, PARANDIS_RSS_MAX_RECEIVE_QUEUES},
#endif
#if PARANDIS_SUPPORT_RSC
{ "*RscIPv4", 1, 0, 1},
{ "*RscIPv6", 1, 0, 1},
#endif
};
static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext)
{
VirtIODeviceReset(pContext->IODevice);
DPrintf(0, ("[%s] Done\n", __FUNCTION__));
/* reset all the features in the device */
pContext->ulCurrentVlansFilterSet = 0;
}
/**********************************************************
Gets integer value for specifies in pEntry->Name name
Parameters:
NDIS_HANDLE cfg previously open configuration
tConfigurationEntry *pEntry - Entry to fill value in
***********************************************************/
static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry)
{
NDIS_STATUS status;
const char *statusName;
NDIS_STRING name = {0};
PNDIS_CONFIGURATION_PARAMETER pParam = NULL;
NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger;
NdisInitializeString(&name, (PUCHAR)pEntry->Name);
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadConfiguration(
&status,
&pParam,
cfg,
&name,
ParameterType);
if (status == NDIS_STATUS_SUCCESS)
{
ULONG ulValue = pParam->ParameterData.IntegerData;
if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal)
{
pEntry->ulValue = ulValue;
statusName = "value";
}
else
{
statusName = "out of range";
}
}
else
{
statusName = "nothing";
}
#pragma warning(pop)
DPrintf(2, ("[%s] %s read for %s - 0x%x\n",
__FUNCTION__,
statusName,
pEntry->Name,
pEntry->ulValue));
if (name.Buffer) NdisFreeString(name);
}
static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT4Lso)
{
DPrintf(0, ("[%s] Warning: %s", procname, reason));
pContext->Offload.flagsValue &= ~osbT4Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT6Lso)
{
DPrintf(0, ("[%s] Warning: %s\n", procname, reason));
pContext->Offload.flagsValue &= ~osbT6Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
/**********************************************************
Loads NIC parameters from adapter registry key
Parameters:
context
PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host
***********************************************************/
static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR pNewMACAddress)
{
NDIS_HANDLE cfg;
tConfigurationEntries *pConfiguration = (tConfigurationEntries *) ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries));
if (pConfiguration)
{
*pConfiguration = defaultConfiguration;
cfg = ParaNdis_OpenNICConfiguration(pContext);
if (cfg)
{
GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled);
GetConfigurationEntry(cfg, &pConfiguration->debugLevel);
GetConfigurationEntry(cfg, &pConfiguration->ConnectRate);
GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport);
GetConfigurationEntry(cfg, &pConfiguration->TxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->RxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->LogStatistics);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO);
GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS);
GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6);
GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging);
GetConfigurationEntry(cfg, &pConfiguration->VlanId);
GetConfigurationEntry(cfg, &pConfiguration->PublishIndices);
GetConfigurationEntry(cfg, &pConfiguration->MTU);
GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC);
#if PARANDIS_SUPPORT_RSS
GetConfigurationEntry(cfg, &pConfiguration->RSSOffloadSupported);
GetConfigurationEntry(cfg, &pConfiguration->NumRSSQueues);
#endif
#if PARANDIS_SUPPORT_RSC
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv4Supported);
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv6Supported);
#endif
bDebugPrint = pConfiguration->isLogEnabled.ulValue;
virtioDebugLevel = pConfiguration->debugLevel.ulValue;
pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue;
pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue;
pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue;
pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue;
pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0;
pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue;
pContext->ulFormalLinkSpeed *= 1000000;
pContext->Offload.flagsValue = 0;
// TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum;
if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp;
if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions;
// RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum;
/* full packet size that can be configured as GSO for VIRTIO is short */
/* NDIS test fails sometimes fails on segments 50-60K */
pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE;
pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue;
pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue;
pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue;
pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue;
pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue;
pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff;
pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue;
#if PARANDIS_SUPPORT_RSS
pContext->bRSSOffloadSupported = pConfiguration->RSSOffloadSupported.ulValue ? TRUE : FALSE;
pContext->RSSMaxQueuesNumber = (CCHAR) pConfiguration->NumRSSQueues.ulValue;
#endif
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4SupportedSW = (UCHAR)pConfiguration->RSCIPv4Supported.ulValue;
pContext->RSC.bIPv6SupportedSW = (UCHAR)pConfiguration->RSCIPv6Supported.ulValue;
#endif
if (!pContext->bDoSupportPriority)
pContext->ulPriorityVlanSetting = 0;
// if Vlan not supported
if (!IsVlanSupported(pContext)) {
pContext->VlanId = 0;
}
{
NDIS_STATUS status;
PVOID p;
UINT len = 0;
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadNetworkAddress(&status, &p, &len, cfg);
if (status == NDIS_STATUS_SUCCESS && len == ETH_LENGTH_OF_ADDRESS)
{
NdisMoveMemory(pNewMACAddress, p, len);
}
else if (len && len != ETH_LENGTH_OF_ADDRESS)
{
DPrintf(0, ("[%s] MAC address has wrong length of %d\n", __FUNCTION__, len));
}
else
{
DPrintf(4, ("[%s] Nothing read for MAC, error %X\n", __FUNCTION__, status));
}
#pragma warning(pop)
}
NdisCloseConfiguration(cfg);
}
NdisFreeMemory(pConfiguration, 0, 0);
}
}
void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from)
{
if (!pDest) pDest = &pContext->Offload.flags;
if (!from) from = &pContext->Offload.flagsValue;
pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum);
pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum);
pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum);
pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum);
pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum);
pDest->fTxLso = !!(*from & osbT4Lso);
pDest->fTxLsoIP = !!(*from & osbT4LsoIp);
pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp);
pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum);
pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum);
pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum);
pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum);
pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum);
pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum);
pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum);
pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum);
pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum);
pDest->fTxLsov6 = !!(*from & osbT6Lso);
pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt);
pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions);
pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum);
pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum);
pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum);
pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum);
}
/**********************************************************
Enumerates adapter resources and fills the structure holding them
Verifies that IO assigned and has correct size
Verifies that interrupt assigned
Parameters:
PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS
tAdapterResources *pResources - structure to fill
Return value:
TRUE if everything is OK
***********************************************************/
static BOOLEAN GetAdapterResources(PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources)
{
UINT i;
NdisZeroMemory(pResources, sizeof(*pResources));
for (i = 0; i < RList->Count; ++i)
{
ULONG type = RList->PartialDescriptors[i].Type;
if (type == CmResourceTypePort)
{
PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start;
ULONG len = RList->PartialDescriptors[i].u.Port.Length;
DPrintf(0, ("Found IO ports at %08lX(%d)\n", Start.LowPart, len));
pResources->ulIOAddress = Start.LowPart;
pResources->IOLength = len;
}
else if (type == CmResourceTypeInterrupt)
{
pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector;
pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level;
pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity;
pResources->InterruptFlags = RList->PartialDescriptors[i].Flags;
DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X\n",
pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags));
}
}
return pResources->ulIOAddress && pResources->Vector;
}
static void DumpVirtIOFeatures(PPARANDIS_ADAPTER pContext)
{
static const struct { ULONG bitmask; PCHAR Name; } Features[] =
{
{VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" },
{VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" },
{VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" },
{VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" },
{VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"},
{VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"},
{VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"},
{VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"},
{VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"},
{VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"},
{VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"},
{VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"},
{VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"},
{VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"},
{VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"},
{VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"},
{VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"},
{VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"},
{VIRTIO_NET_F_CTRL_MAC_ADDR, "VIRTIO_NET_F_CTRL_MAC_ADDR"},
{VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"},
{VIRTIO_F_ANY_LAYOUT, "VIRTIO_F_ANY_LAYOUT"},
{ VIRTIO_RING_F_EVENT_IDX, "VIRTIO_RING_F_EVENT_IDX" },
};
UINT i;
for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Features[i].bitmask))
{
DPrintf(0, ("VirtIO Host Feature %s\n", Features[i].Name));
}
}
}
static BOOLEAN
AckFeature(PPARANDIS_ADAPTER pContext, UINT32 Feature)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Feature))
{
VirtIOFeatureEnable(pContext->u32GuestFeatures, Feature);
return TRUE;
}
return FALSE;
}
/**********************************************************
Prints out statistics
***********************************************************/
static void PrintStatistics(PARANDIS_ADAPTER *pContext)
{
ULONG64 totalTxFrames =
pContext->Statistics.ifHCOutBroadcastPkts +
pContext->Statistics.ifHCOutMulticastPkts +
pContext->Statistics.ifHCOutUcastPkts;
ULONG64 totalRxFrames =
pContext->Statistics.ifHCInBroadcastPkts +
pContext->Statistics.ifHCInMulticastPkts +
pContext->Statistics.ifHCInUcastPkts;
#if 0 /* TODO - setup accessor functions*/
DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d\n",
pContext->CurrentMacAddress[5],
pContext->RXPath.m_NetNofReceiveBuffers,
pContext->NetMaxReceiveBuffers));
DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d\n",
pContext->TXPath.GetFreeTXDescriptors(),
pContext->maxFreeTxDescriptors,
pContext->TXPath.GetFreeHWBuffers()));
#endif
DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u\n",
pContext->Statistics.ifHCOutOctets,
pContext->Statistics.ifHCInOctets));
DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d\n",
totalTxFrames,
pContext->extraStatistics.framesCSOffload,
pContext->extraStatistics.framesLSO,
pContext->extraStatistics.framesIndirect));
DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d\n",
totalRxFrames, pContext->extraStatistics.framesRxPriority,
pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut));
if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood)
{
DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d\n",
pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood));
}
}
static
VOID InitializeRSCState(PPARANDIS_ADAPTER pContext)
{
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4Enabled = FALSE;
pContext->RSC.bIPv6Enabled = FALSE;
if(!pContext->bGuestChecksumSupported)
{
DPrintf(0, ("[%s] Guest TSO cannot be enabled without guest checksum\n", __FUNCTION__) );
return;
}
if(pContext->RSC.bIPv4SupportedSW)
{
pContext->RSC.bIPv4Enabled =
pContext->RSC.bIPv4SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO4);
}
else
{
pContext->RSC.bIPv4SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO4);
}
if(pContext->RSC.bIPv6SupportedSW)
{
pContext->RSC.bIPv6Enabled =
pContext->RSC.bIPv6SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO6);
}
else
{
pContext->RSC.bIPv6SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO6);
}
pContext->RSC.bHasDynamicConfig = (pContext->RSC.bIPv4Enabled || pContext->RSC.bIPv6Enabled) &&
AckFeature(pContext, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
DPrintf(0, ("[%s] Guest TSO state: IP4=%d, IP6=%d, Dynamic=%d\n", __FUNCTION__,
pContext->RSC.bIPv4Enabled, pContext->RSC.bIPv6Enabled, pContext->RSC.bHasDynamicConfig) );
#else
UNREFERENCED_PARAMETER(pContext);
#endif
}
static __inline void
DumpMac(int dbg_level, const char* header_str, UCHAR* mac)
{
DPrintf(dbg_level,("%s: %02x-%02x-%02x-%02x-%02x-%02x\n",
header_str, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]));
}
static __inline void
SetDeviceMAC(PPARANDIS_ADAPTER pContext, PUCHAR pDeviceMAC)
{
if(pContext->bCfgMACAddrSupported && !pContext->bCtrlMACAddrSupported)
{
VirtIODeviceSet(pContext->IODevice, 0, pDeviceMAC, ETH_LENGTH_OF_ADDRESS);
}
}
static void
InitializeMAC(PPARANDIS_ADAPTER pContext, PUCHAR pCurrentMAC)
{
//Acknowledge related features
pContext->bCfgMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_MAC);
pContext->bCtrlMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_CTRL_MAC_ADDR);
//Read and validate permanent MAC address
if (pContext->bCfgMACAddrSupported)
{
VirtIODeviceGet(pContext->IODevice, 0, &pContext->PermanentMacAddress, ETH_LENGTH_OF_ADDRESS);
if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE))
{
DumpMac(0, "Invalid device MAC ignored", pContext->PermanentMacAddress);
NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress));
}
}
if (ETH_IS_EMPTY(pContext->PermanentMacAddress))
{
pContext->PermanentMacAddress[0] = 0x02;
pContext->PermanentMacAddress[1] = 0x50;
pContext->PermanentMacAddress[2] = 0xF2;
pContext->PermanentMacAddress[3] = 0x00;
pContext->PermanentMacAddress[4] = 0x01;
pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF);
DumpMac(0, "No device MAC present, use default", pContext->PermanentMacAddress);
}
DumpMac(0, "Permanent device MAC", pContext->PermanentMacAddress);
//Read and validate configured MAC address
if (ParaNdis_ValidateMacAddress(pCurrentMAC, TRUE))
{
DPrintf(0, ("[%s] MAC address from configuration used\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pCurrentMAC);
}
else
{
DPrintf(0, ("No valid MAC configured\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pContext->PermanentMacAddress);
}
//If control channel message for MAC address configuration is not supported
// Configure device with actual MAC address via configurations space
//Else actual MAC address will be configured later via control queue
SetDeviceMAC(pContext, pContext->CurrentMacAddress);
DumpMac(0, "Actual MAC", pContext->CurrentMacAddress);
}
static __inline void
RestoreMAC(PPARANDIS_ADAPTER pContext)
{
SetDeviceMAC(pContext, pContext->PermanentMacAddress);
}
/**********************************************************
Initializes the context structure
Major variables, received from NDIS on initialization, must be be set before this call
(for ex. pContext->MiniportHandle)
If this procedure fails, no need to call
ParaNdis_CleanupContext
Parameters:
Return value:
SUCCESS, if resources are OK
NDIS_STATUS_RESOURCE_CONFLICT if not
***********************************************************/
NDIS_STATUS ParaNdis_InitializeContext(
PARANDIS_ADAPTER *pContext,
PNDIS_RESOURCE_LIST pResourceList)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
USHORT linkStatus = 0;
UCHAR CurrentMAC[ETH_LENGTH_OF_ADDRESS] = {0};
ULONG dependentOptions;
DEBUG_ENTRY(0);
ReadNicConfiguration(pContext, CurrentMAC);
pContext->fCurrentLinkState = MediaConnectStateUnknown;
pContext->powerState = NdisDeviceStateUnspecified;
pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS;
#if PARANDIS_SUPPORT_RSC
pContext->MaxPacketSize.nMaxDataSizeHwRx = MAX_HW_RX_PACKET_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = MAX_OS_RX_PACKET_SIZE;
#else
pContext->MaxPacketSize.nMaxDataSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = pContext->MaxPacketSize.nMaxFullSizeOS;
#endif
if (pContext->ulPriorityVlanSetting)
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
if (GetAdapterResources(pResourceList, &pContext->AdapterResources) &&
NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange(
&pContext->pIoPortOffset,
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength)
)
{
if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE)
{
DPrintf(0, ("[%s] Message interrupt assigned\n", __FUNCTION__));
pContext->bUsingMSIX = TRUE;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(*pContext->IODevice));
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER);
pContext->u32HostFeatures = VirtIODeviceReadHostFeatures(pContext->IODevice);
DumpVirtIOFeatures(pContext);
pContext->bLinkDetectSupported = AckFeature(pContext, VIRTIO_NET_F_STATUS);
if(pContext->bLinkDetectSupported) {
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0;
DPrintf(0, ("[%s] Link status on driver startup: %d\n", __FUNCTION__, pContext->bConnected));
}
InitializeMAC(pContext, CurrentMAC);
pContext->bUseMergedBuffers = AckFeature(pContext, VIRTIO_NET_F_MRG_RXBUF);
pContext->nVirtioHeaderSize = (pContext->bUseMergedBuffers) ? sizeof(virtio_net_hdr_ext) : sizeof(virtio_net_hdr_basic);
pContext->bDoPublishIndices = AckFeature(pContext, VIRTIO_RING_F_EVENT_IDX);
}
else
{
DPrintf(0, ("[%s] Error: Incomplete resources\n", __FUNCTION__));
/* avoid deregistering if failed */
pContext->AdapterResources.ulIOAddress = 0;
status = NDIS_STATUS_RESOURCE_CONFLICT;
}
pContext->bMultiQueue = AckFeature(pContext, VIRTIO_NET_F_CTRL_MQ);
if (pContext->bMultiQueue)
{
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS + sizeof(USHORT), &pContext->nHardwareQueues,
sizeof(pContext->nHardwareQueues));
}
else
{
pContext->nHardwareQueues = 1;
}
dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum;
if((pContext->Offload.flagsValue & dependentOptions) && !AckFeature(pContext, VIRTIO_NET_F_CSUM))
{
DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload\n", __FUNCTION__) );
pContext->Offload.flagsValue &= ~dependentOptions;
}
pContext->bGuestChecksumSupported = AckFeature(pContext, VIRTIO_NET_F_GUEST_CSUM);
AckFeature(pContext, VIRTIO_NET_F_CTRL_VQ);
InitializeRSCState(pContext);
// now, after we checked the capabilities, we can initialize current
// configuration of offload tasks
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
if (pContext->Offload.flags.fTxLso && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO4))
{
DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4\n");
}
if (pContext->Offload.flags.fTxLsov6 && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO6))
{
DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6");
}
pContext->bUseIndirect = AckFeature(pContext, VIRTIO_F_INDIRECT);
pContext->bAnyLaypout = AckFeature(pContext, VIRTIO_F_ANY_LAYOUT);
pContext->bHasHardwareFilters = AckFeature(pContext, VIRTIO_NET_F_CTRL_RX_EXTRA);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
NdisInitializeEvent(&pContext->ResetEvent);
DEBUG_EXIT_STATUS(0, status);
return status;
}
void ParaNdis_FreeRxBufferDescriptor(PARANDIS_ADAPTER *pContext, pRxNetDescriptor p)
{
ULONG i;
for(i = 0; i < p->PagesAllocated; i++)
{
ParaNdis_FreePhysicalMemory(pContext, &p->PhysicalPages[i]);
}
if(p->BufferSGArray) NdisFreeMemory(p->BufferSGArray, 0, 0);
if(p->PhysicalPages) NdisFreeMemory(p->PhysicalPages, 0, 0);
NdisFreeMemory(p, 0, 0);
}
/**********************************************************
Allocates maximum RX buffers for incoming packets
Buffers are chained in NetReceiveBuffers
Parameters:
context
***********************************************************/
void ParaNdis_DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa)
{
if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL);
*ppq = NULL;
if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa);
RtlZeroMemory(ppa, sizeof(*ppa));
}
#if PARANDIS_SUPPORT_RSS
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *pContext)
{
if (!pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] No MSIX, using 1 queue\n", __FUNCTION__));
return 1;
}
if (pContext->bMultiQueue)
{
DPrintf(0, ("[%s] Number of hardware queues = %d\n", __FUNCTION__, pContext->nHardwareQueues));
}
else
{
DPrintf(0, ("[%s] - CTRL_MQ not acked, # bindles set to 1\n", __FUNCTION__));
return 1;
}
ULONG lnProcessors;
#if NDIS_SUPPORT_NDIS620
lnProcessors = NdisGroupActiveProcessorCount(ALL_PROCESSOR_GROUPS);
#elif NDIS_SUPPORT_NDIS6
lnProcessors = NdisSystemProcessorCount();
#else
lnProcessors = 1;
#endif
ULONG lnMSIs = (pContext->pMSIXInfoTable->MessageCount - 1) / 2; /* RX/TX pairs + control queue*/
DPrintf(0, ("[%s] %lu CPUs reported\n", __FUNCTION__, lnProcessors));
DPrintf(0, ("[%s] %lu MSIs, %lu queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, lnMSIs));
USHORT nMSIs = USHORT(lnMSIs & 0xFFFF);
USHORT nProcessors = USHORT(lnProcessors & 0xFFFF);
DPrintf(0, ("[%s] %u CPUs reported\n", __FUNCTION__, nProcessors));
DPrintf(0, ("[%s] %lu MSIs, %u queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, nMSIs));
USHORT nBundles = (pContext->nHardwareQueues < nProcessors) ? pContext->nHardwareQueues : nProcessors;
nBundles = (nMSIs < nBundles) ? nMSIs : nBundles;
DPrintf(0, ("[%s] # of path bundles = %u\n", __FUNCTION__, nBundles));
return nBundles;
}
#else
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *)
{
return 1;
}
#endif
static NDIS_STATUS SetupDPCTarget(PARANDIS_ADAPTER *pContext)
{
ULONG i;
#if NDIS_SUPPORT_NDIS620
NDIS_STATUS status;
PROCESSOR_NUMBER procNumber;
#endif
for (i = 0; i < pContext->nPathBundles; i++)
{
#if NDIS_SUPPORT_NDIS620
status = KeGetProcessorNumberFromIndex(i, &procNumber);
if (status != NDIS_STATUS_SUCCESS)
{
DPrintf(0, ("[%s] - KeGetProcessorNumberFromIndex failed for index %lu - %d\n", __FUNCTION__, i, status));
return status;
}
ParaNdis_ProcessorNumberToGroupAffinity(&pContext->pPathBundles[i].rxPath.DPCAffinity, &procNumber);
pContext->pPathBundles[i].txPath.DPCAffinity = pContext->pPathBundles[i].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->pPathBundles[i].rxPath.DPCTargetProcessor = 1i64 << i;
pContext->pPathBundles[i].txPath.DPCTargetProcessor = pContext->pPathBundles[i].rxPath.DPCTargetProcessor;
#else
#error not supported
#endif
}
#if NDIS_SUPPORT_NDIS620
pContext->CXPath.DPCAffinity = pContext->pPathBundles[0].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->CXPath.DPCTargetProcessor = pContext->pPathBundles[0].rxPath.DPCTargetProcessor;
#else
#error not yet defined
#endif
return NDIS_STATUS_SUCCESS;
}
#if PARANDIS_SUPPORT_RSS
NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext)
{
USHORT rssIndex, bundleIndex;
ULONG cpuIndex;
ULONG rssTableSize = pContext->RSSParameters.RSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
rssIndex = 0;
bundleIndex = 0;
USHORT *cpuIndexTable;
ULONG cpuNumbers;
cpuNumbers = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
cpuIndexTable = (USHORT *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, cpuNumbers * sizeof(*cpuIndexTable),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (cpuIndexTable == nullptr)
{
DPrintf(0, ("[%s] cpu index table allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(cpuIndexTable, sizeof(*cpuIndexTable) * cpuNumbers);
for (bundleIndex = 0; bundleIndex < pContext->nPathBundles; ++bundleIndex)
{
cpuIndex = pContext->pPathBundles[bundleIndex].rxPath.getCPUIndex();
if (cpuIndex == INVALID_PROCESSOR_INDEX)
{
DPrintf(0, ("[%s] Invalid CPU index for path %u\n", __FUNCTION__, bundleIndex));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else if (cpuIndex >= cpuNumbers)
{
DPrintf(0, ("[%s] CPU index %lu exceeds CPU range %lu\n", __FUNCTION__, cpuIndex, cpuNumbers));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else
{
cpuIndexTable[cpuIndex] = bundleIndex;
}
}
DPrintf(0, ("[%s] Entering, RSS table size = %lu, # of path bundles = %u. RSS2QueueLength = %u, RSS2QueueMap =0x%p\n",
__FUNCTION__, rssTableSize, pContext->nPathBundles,
pContext->RSS2QueueLength, pContext->RSS2QueueMap));
if (pContext->RSS2QueueLength && pContext->RSS2QueueLength < rssTableSize)
{
DPrintf(0, ("[%s] Freeing RSS2Queue Map\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueLength = 0;
}
if (!pContext->RSS2QueueLength)
{
pContext->RSS2QueueLength = USHORT(rssTableSize);
pContext->RSS2QueueMap = (CPUPathesBundle **)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, rssTableSize * sizeof(*pContext->RSS2QueueMap),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->RSS2QueueMap == nullptr)
{
DPrintf(0, ("[%s] - Allocating RSS to queue mapping failed\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(pContext->RSS2QueueMap, sizeof(*pContext->RSS2QueueMap) * pContext->RSS2QueueLength);
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles;
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
cpuIndex = NdisProcessorNumberToIndex(pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex]);
bundleIndex = cpuIndexTable[cpuIndex];
DPrintf(3, ("[%s] filling the relationship, rssIndex = %u, bundleIndex = %u\n", __FUNCTION__, rssIndex, bundleIndex));
DPrintf(3, ("[%s] RSS proc number %u/%u, bundle affinity %u/%u\n", __FUNCTION__,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Group,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Number,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Group,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Mask));
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles + bundleIndex;
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SUCCESS;
}
#endif
/**********************************************************
Initializes VirtIO buffering and related stuff:
Allocates RX and TX queues and buffers
Parameters:
context
Return value:
TRUE if both queues are allocated
***********************************************************/
static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_RESOURCES;
DEBUG_ENTRY(0);
UINT i;
USHORT nVirtIOQueues = pContext->nHardwareQueues * 2 + 2;
pContext->nPathBundles = DetermineQueueNumber(pContext);
if (pContext->nPathBundles == 0)
{
DPrintf(0, ("[%s] - no I/O pathes\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
if (nVirtIOQueues > pContext->IODevice->maxQueues)
{
ULONG IODeviceSize = VirtIODeviceSizeRequired(nVirtIOQueues);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = (VirtIODevice *)NdisAllocateMemoryWithTagPriority(
pContext->MiniportHandle,
IODeviceSize,
PARANDIS_MEMORY_TAG,
NormalPoolPriority);
if (pContext->IODevice == nullptr)
{
DPrintf(0, ("[%s] - IODevice allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, IODeviceSize);
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
DPrintf(0, ("[%s] %u queues' slots reallocated for size %lu\n", __FUNCTION__, pContext->IODevice->maxQueues, IODeviceSize));
}
new (&pContext->CXPath, PLACEMENT_NEW) CParaNdisCX();
pContext->bCXPathAllocated = TRUE;
if (!pContext->CXPath.Create(pContext, 2 * pContext->nHardwareQueues))
{
DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__));
pContext->bHasHardwareFilters = FALSE;
pContext->bCtrlMACAddrSupported = FALSE;
}
else
{
pContext->bCXPathCreated = TRUE;
}
pContext->pPathBundles = (CPUPathesBundle *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, pContext->nPathBundles * sizeof(*pContext->pPathBundles),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->pPathBundles == nullptr)
{
DPrintf(0, ("[%s] Path bundles allocation failed\n", __FUNCTION__));
return status;
}
for (i = 0; i < pContext->nPathBundles; i++)
{
new (pContext->pPathBundles + i, PLACEMENT_NEW) CPUPathesBundle();
if (!pContext->pPathBundles[i].rxPath.Create(pContext, i * 2))
{
DPrintf(0, ("%s: CParaNdisRX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].rxCreated = true;
if (!pContext->pPathBundles[i].txPath.Create(pContext, i * 2 + 1))
{
DPrintf(0, ("%s: CParaNdisTX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].txCreated = true;
}
if (pContext->bCXPathCreated)
{
pContext->pPathBundles[0].cxPath = &pContext->CXPath;
}
status = NDIS_STATUS_SUCCESS;
return status;
}
static void ReadLinkState(PARANDIS_ADAPTER *pContext)
{
if (pContext->bLinkDetectSupported)
{
USHORT linkStatus = 0;
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = !!(linkStatus & VIRTIO_NET_S_LINK_UP);
}
else
{
pContext->bConnected = TRUE;
}
}
static void ParaNdis_RemoveDriverOKStatus(PPARANDIS_ADAPTER pContext )
{
VirtIODeviceRemoveStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
KeMemoryBarrier();
pContext->bDeviceInitialized = FALSE;
}
static VOID ParaNdis_AddDriverOKStatus(PPARANDIS_ADAPTER pContext)
{
pContext->bDeviceInitialized = TRUE;
KeMemoryBarrier();
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
}
/**********************************************************
Finishes initialization of context structure, calling also version dependent part
If this procedure failed, ParaNdis_CleanupContext must be called
Parameters:
context
Return value:
SUCCESS or some kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
DEBUG_ENTRY(0);
status = ParaNdis_FinishSpecificInitialization(pContext);
DPrintf(0, ("[%s] ParaNdis_FinishSpecificInitialization passed, status = %d\n", __FUNCTION__, status));
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_VirtIONetInit(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_ConfigureMSIXVectors(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = SetupDPCTarget(pContext);
DPrintf(0, ("[%s] SetupDPCTarget passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS && pContext->nPathBundles > 1)
{
u16 nPathes = u16(pContext->nPathBundles);
BOOLEAN sendSuccess = pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, VIRTIO_NET_CTRL_MQ_VQ_PAIR_SET, &nPathes, sizeof(nPathes), NULL, 0, 2);
if (!sendSuccess)
{
DPrintf(0, ("[%s] - Send MQ control message failed\n", __FUNCTION__));
status = NDIS_STATUS_DEVICE_FAILED;
}
}
pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1;
if (status == NDIS_STATUS_SUCCESS)
{
ReadLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
ParaNdis_AddDriverOKStatus(pContext);
ParaNdis_UpdateMAC(pContext);
}
DEBUG_EXIT_STATUS(0, status);
return status;
}
/**********************************************************
Releases VirtIO related resources - queues and buffers
Parameters:
context
Return value:
***********************************************************/
static void VirtIONetRelease(PARANDIS_ADAPTER *pContext)
{
BOOLEAN b;
ULONG i;
DEBUG_ENTRY(0);
/* list NetReceiveBuffersWaiting must be free */
for (i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
pRxNetDescriptor pBufferDescriptor;
while (NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pContext->ReceiveQueues + i)))
{
pBufferDescriptor->Queue->ReuseReceiveBuffer(FALSE, pBufferDescriptor);
}
}
do
{
b = pContext->m_upstreamPacketPending != 0;
if (b)
{
DPrintf(0, ("[%s] There are waiting buffers\n", __FUNCTION__));
PrintStatistics(pContext);
NdisMSleep(5000000);
}
} while (b);
RestoreMAC(pContext);
for (i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txCreated)
{
pContext->pPathBundles[i].txPath.Shutdown();
}
if (pContext->pPathBundles[i].rxCreated)
{
pContext->pPathBundles[i].rxPath.Shutdown();
/* this can be freed, queue shut down */
pContext->pPathBundles[i].rxPath.FreeRxDescriptorsFromList();
}
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
PrintStatistics(pContext);
}
static void PreventDPCServicing(PARANDIS_ADAPTER *pContext)
{
LONG inside;
pContext->bEnableInterruptHandlingDPC = FALSE;
KeMemoryBarrier();
do
{
inside = InterlockedIncrement(&pContext->counterDPCInside);
InterlockedDecrement(&pContext->counterDPCInside);
if (inside > 1)
{
DPrintf(0, ("[%s] waiting!\n", __FUNCTION__));
NdisMSleep(20000);
}
} while (inside > 1);
}
/**********************************************************
Frees all the resources allocated when the context initialized,
calling also version-dependent part
Parameters:
context
***********************************************************/
VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext)
{
/* disable any interrupt generation */
if (pContext->IODevice->addr)
{
if (pContext->bDeviceInitialized)
{
ParaNdis_RemoveDriverOKStatus(pContext);
}
}
PreventDPCServicing(pContext);
/****************************************
ensure all the incoming packets returned,
free all the buffers and their descriptors
*****************************************/
if (pContext->IODevice->addr)
{
ParaNdis_ResetVirtIONetDevice(pContext);
}
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
VirtIONetRelease(pContext);
ParaNdis_FinalizeCleanup(pContext);
if (pContext->ReceiveQueuesInitialized)
{
ULONG i;
for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
NdisFreeSpinLock(&pContext->ReceiveQueues[i].Lock);
}
}
pContext->m_PauseLock.~CNdisRWLock();
#if PARANDIS_SUPPORT_RSS
if (pContext->bRSSInitialized)
{
ParaNdis6_RSSCleanupConfiguration(&pContext->RSSParameters);
}
pContext->RSSParameters.rwLock.~CNdisRWLock();
#endif
if (pContext->bCXPathAllocated)
{
pContext->CXPath.~CParaNdisCX();
pContext->bCXPathAllocated = false;
}
if (pContext->pPathBundles != NULL)
{
USHORT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].~CPUPathesBundle();
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->pPathBundles, PARANDIS_MEMORY_TAG);
pContext->pPathBundles = nullptr;
}
if (pContext->RSS2QueueMap)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueMap = nullptr;
pContext->RSS2QueueLength = 0;
}
if (pContext->IODevice)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = nullptr;
}
if (pContext->AdapterResources.ulIOAddress)
{
NdisMDeregisterIoPortRange(
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength,
pContext->pIoPortOffset);
pContext->AdapterResources.ulIOAddress = 0;
}
}
/**********************************************************
System shutdown handler (shutdown, restart, bugcheck)
Parameters:
context
***********************************************************/
VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0); // this is only for kdbg :)
ParaNdis_ResetVirtIONetDevice(pContext);
}
static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo)
{
ULONG i;
if (pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
if ((pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx) && !pPacketInfo->hasVlanHeader)
return FALSE;
if (IsVlanSupported(pContext) && pPacketInfo->hasVlanHeader)
{
if (pContext->VlanId && pContext->VlanId != pPacketInfo->Vlan.VlanId)
{
return FALSE;
}
}
if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS)
return TRUE;
if(pPacketInfo->isUnicast)
{
ULONG Res;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED))
return FALSE;
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, pContext->CurrentMacAddress, &Res);
return !Res;
}
if(pPacketInfo->isBroadcast)
return (pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST);
// Multi-cast
if(pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST)
return TRUE;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST))
return FALSE;
for (i = 0; i < pContext->MulticastData.nofMulticastEntries; i++)
{
ULONG Res;
PUCHAR CurrMcastAddr = &pContext->MulticastData.MulticastList[i*ETH_LENGTH_OF_ADDRESS];
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, CurrMcastAddr, &Res);
if(!Res)
return TRUE;
}
return FALSE;
}
BOOLEAN ParaNdis_PerformPacketAnalyzis(
#if PARANDIS_SUPPORT_RSS
PPARANDIS_RSS_PARAMS RSSParameters,
#endif
PNET_PACKET_INFO PacketInfo,
PVOID HeadersBuffer,
ULONG DataLength)
{
if(!ParaNdis_AnalyzeReceivedPacket(HeadersBuffer, DataLength, PacketInfo))
return FALSE;
#if PARANDIS_SUPPORT_RSS
if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED)
{
ParaNdis6_RSSAnalyzeReceivedPacket(RSSParameters, HeadersBuffer, PacketInfo);
}
#endif
return TRUE;
}
VOID ParaNdis_ProcessorNumberToGroupAffinity(PGROUP_AFFINITY Affinity, const PPROCESSOR_NUMBER Processor)
{
Affinity->Group = Processor->Group;
Affinity->Mask = 1;
Affinity->Mask <<= Processor->Number;
}
CCHAR ParaNdis_GetScalingDataForPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo, PPROCESSOR_NUMBER pTargetProcessor)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetScalingDataForPacket(&pContext->RSSParameters, pPacketInfo, pTargetProcessor);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(pPacketInfo);
UNREFERENCED_PARAMETER(pTargetProcessor);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
static __inline
CCHAR GetReceiveQueueForCurrentCPU(PARANDIS_ADAPTER *pContext)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetCurrentCpuReceiveQueue(&pContext->RSSParameters);
#else
UNREFERENCED_PARAMETER(pContext);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
VOID ParaNdis_QueueRSSDpc(PARANDIS_ADAPTER *pContext, ULONG MessageIndex, PGROUP_AFFINITY pTargetAffinity)
{
#if PARANDIS_SUPPORT_RSS
NdisMQueueDpcEx(pContext->InterruptHandle, MessageIndex, pTargetAffinity, NULL);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(MessageIndex);
UNREFERENCED_PARAMETER(pTargetAffinity);
ASSERT(FALSE);
#endif
}
VOID ParaNdis_ReceiveQueueAddBuffer(PPARANDIS_RECEIVE_QUEUE pQueue, pRxNetDescriptor pBuffer)
{
NdisInterlockedInsertTailList( &pQueue->BuffersList,
&pBuffer->ReceiveQueueListEntry,
&pQueue->Lock);
}
VOID ParaMdis_TestPausing(PARANDIS_ADAPTER *pContext)
{
ONPAUSECOMPLETEPROC callback = nullptr;
if (pContext->m_upstreamPacketPending == 0)
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
if (pContext->m_upstreamPacketPending == 0 && (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc))
{
callback = pContext->ReceivePauseCompletionProc;
pContext->ReceiveState = srsDisabled;
pContext->ReceivePauseCompletionProc = NULL;
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
}
}
if (callback) callback(pContext);
}
static __inline
pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue)
{
PLIST_ENTRY pListEntry = NdisInterlockedRemoveHeadList(&pQueue->BuffersList, &pQueue->Lock);
return pListEntry ? CONTAINING_RECORD(pListEntry, RxNetDescriptor, ReceiveQueueListEntry) : NULL;
}
static __inline
BOOLEAN ReceiveQueueHasBuffers(PPARANDIS_RECEIVE_QUEUE pQueue)
{
BOOLEAN res;
NdisAcquireSpinLock(&pQueue->Lock);
res = !IsListEmpty(&pQueue->BuffersList);
NdisReleaseSpinLock(&pQueue->Lock);
return res;
}
static VOID
UpdateReceiveSuccessStatistics(PPARANDIS_ADAPTER pContext,
PNET_PACKET_INFO pPacketInfo,
UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifHCInOctets += pPacketInfo->dataLength;
if(pPacketInfo->isUnicast)
{
pContext->Statistics.ifHCInUcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInUcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isBroadcast)
{
pContext->Statistics.ifHCInBroadcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInBroadcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isMulticast)
{
pContext->Statistics.ifHCInMulticastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInMulticastOctets += pPacketInfo->dataLength;
}
else
{
ASSERT(FALSE);
}
}
static __inline VOID
UpdateReceiveFailStatistics(PPARANDIS_ADAPTER pContext, UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifInErrors++;
pContext->Statistics.ifInDiscards += nCoalescedSegmentsCount;
}
static BOOLEAN ProcessReceiveQueue(PARANDIS_ADAPTER *pContext,
PULONG pnPacketsToIndicateLeft,
CCHAR nQueueIndex,
PNET_BUFFER_LIST *indicate,
PNET_BUFFER_LIST *indicateTail,
ULONG *nIndicate)
{
pRxNetDescriptor pBufferDescriptor;
PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex];
if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1)
{
while( (*pnPacketsToIndicateLeft > 0) &&
(NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) )
{
PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo;
if( !pContext->bSurprizeRemoved &&
pContext->ReceiveState == srsEnabled &&
pContext->bConnected &&
ShallPassPacket(pContext, pPacketInfo))
{
UINT nCoalescedSegmentsCount;
PNET_BUFFER_LIST packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor, &nCoalescedSegmentsCount);
if(packet != NULL)
{
UpdateReceiveSuccessStatistics(pContext, pPacketInfo, nCoalescedSegmentsCount);
if (*indicate == nullptr)
{
*indicate = *indicateTail = packet;
}
else
{
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = packet;
*indicateTail = packet;
}
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = NULL;
(*pnPacketsToIndicateLeft)--;
(*nIndicate)++;
}
else
{
UpdateReceiveFailStatistics(pContext, nCoalescedSegmentsCount);
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
else
{
pContext->extraStatistics.framesFilteredOut++;
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
}
NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount);
return ReceiveQueueHasBuffers(pTargetReceiveQueue);
}
static
BOOLEAN RxDPCWorkBody(PARANDIS_ADAPTER *pContext, CPUPathesBundle *pathBundle, ULONG nPacketsToIndicate)
{
BOOLEAN res = FALSE;
BOOLEAN bMoreDataInRing;
PNET_BUFFER_LIST indicate, indicateTail;
ULONG nIndicate;
CCHAR CurrCpuReceiveQueue = GetReceiveQueueForCurrentCPU(pContext);
do
{
indicate = nullptr;
indicateTail = nullptr;
nIndicate = 0;
{
CNdisDispatchReadAutoLock tLock(pContext->m_PauseLock);
pathBundle->rxPath.ProcessRxRing(CurrCpuReceiveQueue);
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED,
&indicate, &indicateTail, &nIndicate);
if(CurrCpuReceiveQueue != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED)
{
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, CurrCpuReceiveQueue,
&indicate, &indicateTail, &nIndicate);
}
bMoreDataInRing = pathBundle->rxPath.RestartQueue();
}
if (nIndicate)
{
NdisMIndicateReceiveNetBufferLists(pContext->MiniportHandle,
indicate,
0,
nIndicate,
0);
}
ParaMdis_TestPausing(pContext);
} while (bMoreDataInRing);
return res;
}
bool ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate)
{
bool stillRequiresProcessing = false;
UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC);
DEBUG_ENTRY(5);
InterlockedIncrement(&pContext->counterDPCInside);
CPUPathesBundle *pathBundle = nullptr;
if (pContext->nPathBundles == 1)
{
pathBundle = pContext->pPathBundles;
}
else
{
ULONG procNumber = KeGetCurrentProcessorNumber();
if (procNumber < pContext->nPathBundles)
{
pathBundle = pContext->pPathBundles + procNumber;
}
}
if (pathBundle == nullptr)
{
return false;
}
if (pContext->bEnableInterruptHandlingDPC)
{
bool bDoKick = false;
InterlockedExchange(&pContext->bDPCInactive, 0);
if (RxDPCWorkBody(pContext, pathBundle, numOfPacketsToIndicate))
{
stillRequiresProcessing = true;
}
if (pContext->CXPath.WasInterruptReported() && pContext->bLinkDetectSupported)
{
ReadLinkState(pContext);
ParaNdis_SynchronizeLinkState(pContext);
pContext->CXPath.ClearInterruptReport();
}
if (!stillRequiresProcessing)
{
bDoKick = pathBundle->txPath.DoPendingTasks(true);
if (pathBundle->txPath.RestartQueue(bDoKick))
{
stillRequiresProcessing = true;
}
}
}
InterlockedDecrement(&pContext->counterDPCInside);
return stillRequiresProcessing;
}
VOID ParaNdis_ResetRxClassification(PARANDIS_ADAPTER *pContext)
{
ULONG i;
PPARANDIS_RECEIVE_QUEUE pUnclassified = &pContext->ReceiveQueues[PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED];
NdisAcquireSpinLock(&pUnclassified->Lock);
for(i = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED + 1; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
PPARANDIS_RECEIVE_QUEUE pCurrQueue = &pContext->ReceiveQueues[i];
NdisAcquireSpinLock(&pCurrQueue->Lock);
while(!IsListEmpty(&pCurrQueue->BuffersList))
{
PLIST_ENTRY pListEntry = RemoveHeadList(&pCurrQueue->BuffersList);
InsertTailList(&pUnclassified->BuffersList, pListEntry);
}
NdisReleaseSpinLock(&pCurrQueue->Lock);
}
NdisReleaseSpinLock(&pUnclassified->Lock);
}
/**********************************************************
Periodically called procedure, checking dpc activity
If DPC are not running, it does exactly the same that the DPC
Parameters:
context
***********************************************************/
static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext)
{
BOOLEAN bStopped;
BOOLEAN bReportHang = FALSE;
bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE);
if (bStopped)
{
pContext->nDetectedInactivity++;
}
else
{
pContext->nDetectedInactivity = 0;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txPath.HasHWBuffersIsUse())
{
if (pContext->nDetectedStoppedTx++ > 1)
{
DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!\n", __FUNCTION__, pContext->pPathBundles[i].txPath.GetFreeHWBuffers()));
//bReportHang = TRUE;
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 0);
#endif
break;
}
}
}
if (pContext->Limits.nPrintDiagnostic &&
++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic)
{
pContext->Counters.nPrintDiagnostic = 0;
// todo - collect more and put out optionally
PrintStatistics(pContext);
}
if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn)
{
pContext->Counters.nRxInactivity++;
if (pContext->Counters.nRxInactivity >= 10)
{
#if defined(CRASH_ON_NO_RX)
ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1;
proc(pContext);
#endif
}
}
else
{
pContext->Counters.nRxInactivity = 0;
pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets;
}
return bReportHang;
}
/**********************************************************
Common implementation of periodic poll
Parameters:
context
Return:
TRUE, if reset required
***********************************************************/
BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext)
{
static int nHangOn = 0;
BOOLEAN b = nHangOn >= 3 && nHangOn < 6;
DEBUG_ENTRY(3);
b |= CheckRunningDpc(pContext);
//uncomment to cause 3 consecutive resets
//nHangOn++;
DEBUG_EXIT_STATUS(b ? 0 : 6, b);
return b;
}
/////////////////////////////////////////////////////////////////////////////////////
//
// ReadVirtIODeviceRegister\WriteVirtIODeviceRegister
// NDIS specific implementation of the IO space read\write
//
/////////////////////////////////////////////////////////////////////////////////////
u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister)
{
ULONG ulValue;
NdisRawReadPortUlong(ulRegister, &ulValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
return ulValue;
}
void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
NdisRawWritePortUlong(ulRegister, ulValue);
}
u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister)
{
u8 bValue;
NdisRawReadPortUchar(ulRegister, &bValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
return bValue;
}
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
NdisRawWritePortUchar(ulRegister, bValue);
}
u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister)
{
u16 wValue;
NdisRawReadPortUshort(ulRegister, &wValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
return wValue;
}
void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue)
{
#if 1
NdisRawWritePortUshort(ulRegister, wValue);
#else
// test only to cause long TX waiting queue of NDIS packets
// to recognize it and request for reset via Hang handler
static int nCounterToFail = 0;
static const int StartFail = 200, StopFail = 600;
BOOLEAN bFail = FALSE;
DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
if ((ulRegister & 0x1F) == 0x10)
{
nCounterToFail++;
bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail;
}
if (!bFail) NdisRawWritePortUshort(ulRegister, wValue);
else
{
DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
}
#endif
}
/**********************************************************
Common handler of multicast address configuration
Parameters:
PVOID Buffer array of addresses from NDIS
ULONG BufferSize size of incoming buffer
PUINT pBytesRead update on success
PUINT pBytesNeeded update on wrong buffer size
Return value:
SUCCESS or kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_SetMulticastList(
PARANDIS_ADAPTER *pContext,
PVOID Buffer,
ULONG BufferSize,
PUINT pBytesRead,
PUINT pBytesNeeded)
{
NDIS_STATUS status;
ULONG length = BufferSize;
if (length > sizeof(pContext->MulticastData.MulticastList))
{
status = NDIS_STATUS_MULTICAST_FULL;
*pBytesNeeded = sizeof(pContext->MulticastData.MulticastList);
}
else if (length % ETH_LENGTH_OF_ADDRESS)
{
status = NDIS_STATUS_INVALID_LENGTH;
*pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS;
}
else
{
NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList));
if (length)
NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length);
pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS;
DPrintf(1, ("[%s] New multicast list of %d bytes\n", __FUNCTION__, length));
*pBytesRead = length;
status = NDIS_STATUS_SUCCESS;
}
return status;
}
/**********************************************************
Common handler of PnP events
Parameters:
Return value:
***********************************************************/
VOID ParaNdis_OnPnPEvent(
PARANDIS_ADAPTER *pContext,
NDIS_DEVICE_PNP_EVENT pEvent,
PVOID pInfo,
ULONG ulSize)
{
const char *pName = "";
UNREFERENCED_PARAMETER(pInfo);
UNREFERENCED_PARAMETER(ulSize);
DEBUG_ENTRY(0);
#undef MAKECASE
#define MAKECASE(x) case (x): pName = #x; break;
switch (pEvent)
{
MAKECASE(NdisDevicePnPEventQueryRemoved)
MAKECASE(NdisDevicePnPEventRemoved)
MAKECASE(NdisDevicePnPEventSurpriseRemoved)
MAKECASE(NdisDevicePnPEventQueryStopped)
MAKECASE(NdisDevicePnPEventStopped)
MAKECASE(NdisDevicePnPEventPowerProfileChanged)
MAKECASE(NdisDevicePnPEventFilterListChanged)
default:
break;
}
ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0);
DPrintf(0, ("[%s] (%s)\n", __FUNCTION__, pName));
if (pEvent == NdisDevicePnPEventSurpriseRemoved)
{
// on simulated surprise removal (under PnpTest) we need to reset the device
// to prevent any access of device queues to memory buffers
pContext->bSurprizeRemoved = TRUE;
ParaNdis_ResetVirtIONetDevice(pContext);
{
UINT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Pause();
}
}
}
pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent;
if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0]))
pContext->nPnpEventIndex = 0;
}
static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext)
{
u8 val;
ULONG f = pContext->PacketFilter;
val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2);
//SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2);
}
static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext)
{
u32 u32UniCastEntries = 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET,
&u32UniCastEntries,
sizeof(u32UniCastEntries),
&pContext->MulticastData,
sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS,
2);
}
static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK)
{
u16 val = vlanId & 0xfff;
UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK);
}
static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn)
{
ULONG i;
for (i = 0; i <= MAX_VLAN_ID; ++i)
SetSingleVlanFilter(pContext, i, bOn, 7);
}
/*
possible values of filter set (pContext->ulCurrentVlansFilterSet):
0 - all disabled
1..4095 - one selected enabled
4096 - all enabled
Note that only 0th vlan can't be enabled
*/
VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ULONG newFilterSet;
if (IsVlanSupported(pContext))
newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1);
else
newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0;
if (newFilterSet != pContext->ulCurrentVlansFilterSet)
{
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, FALSE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2);
pContext->ulCurrentVlansFilterSet = newFilterSet;
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, TRUE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2);
}
}
}
VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ParaNdis_DeviceFiltersUpdateRxMode(pContext);
ParaNdis_DeviceFiltersUpdateAddresses(pContext);
ParaNdis_DeviceFiltersUpdateVlanId(pContext);
}
}
static VOID
ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext)
{
if (pContext->bCtrlMACAddrSupported)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_ADDR_SET,
pContext->CurrentMacAddress,
ETH_LENGTH_OF_ADDRESS,
NULL, 0, 4);
}
}
#if PARANDIS_SUPPORT_RSC
VOID
ParaNdis_UpdateGuestOffloads(PARANDIS_ADAPTER *pContext, UINT64 Offloads)
{
if (pContext->RSC.bHasDynamicConfig)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_GUEST_OFFLOADS, VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET,
&Offloads,
sizeof(Offloads),
NULL, 0, 2);
}
}
#endif
VOID ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext)
{
UINT i;
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER);
/* GetHostFeature must be called with any mask once upon device initialization:
otherwise the device will not work properly */
VirtIODeviceReadHostFeatures(pContext->IODevice);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Renew();
pContext->pPathBundles[i].rxPath.Renew();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Renew();
}
ParaNdis_RestoreDeviceConfigurationAfterReset(pContext);
ParaNdis_UpdateDeviceFilters(pContext);
ParaNdis_UpdateMAC(pContext);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].rxPath.PopulateQueue();
}
ReadLinkState(pContext);
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_AddDriverOKStatus(pContext);
// if bFastSuspendInProcess is set by Win8 power-off procedure,
// the ParaNdis_Resume enables Tx and RX
// otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart)
ParaNdis_Resume(pContext);
pContext->bFastSuspendInProcess = FALSE;
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0);
}
VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0);
pContext->bConnected = FALSE;
// if bFastSuspendInProcess is set by Win8 power-off procedure
// the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis)
pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled;
ParaNdis_Suspend(pContext);
ParaNdis_RemoveDriverOKStatus(pContext);
if (pContext->bFastSuspendInProcess)
{
InterlockedExchange(&pContext->ReuseBufferRegular, FALSE);
}
#if !NDIS_SUPPORT_NDIS620
// WLK tests for Windows 2008 require media disconnect indication
// on power off. HCK tests for newer versions require media state unknown
// indication only and fail on disconnect indication
ParaNdis_SetLinkState(pContext, MediaConnectStateDisconnected);
#endif
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
PreventDPCServicing(pContext);
/*******************************************************************
shutdown queues to have all the receive buffers under our control
all the transmit buffers move to list of free buffers
********************************************************************/
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Shutdown();
pContext->pPathBundles[i].rxPath.Shutdown();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
ParaNdis_ResetVirtIONetDevice(pContext);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0);
}
void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext)
{
if (pContext->AdapterResources.ulIOAddress)
{
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 1);
#endif
}
}
tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
//VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS
//VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)
{
res.flags.IpOK = FALSE;
res.flags.IpFailed = TRUE;
return res;
}
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1581_0 |
crossvul-cpp_data_bad_1798_0 | /*
* InspIRCd -- Internet Relay Chat Daemon
*
* Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
* Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
* Copyright (C) 2006, 2009 Robin Burchell <robin+git@viroteck.net>
* Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
* Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
* Copyright (C) 2005-2007 Craig Edwards <craigedwards@brainbox.cc>
*
* This file is part of InspIRCd. InspIRCd is free software: you can
* redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Core */
/*
dns.cpp - Nonblocking DNS functions.
Very very loosely based on the firedns library,
Copyright (C) 2002 Ian Gulliver. This file is no
longer anything like firedns, there are many major
differences between this code and the original.
Please do not assume that firedns works like this,
looks like this, walks like this or tastes like this.
*/
#ifndef _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#include "inspircd_win32wrapper.h"
#endif
#include "inspircd.h"
#include "socketengine.h"
#include "configreader.h"
#include "socket.h"
#define DN_COMP_BITMASK 0xC000 /* highest 6 bits in a DN label header */
/** Masks to mask off the responses we get from the DNSRequest methods
*/
enum QueryInfo
{
ERROR_MASK = 0x10000 /* Result is an error */
};
/** Flags which can be ORed into a request or reply for different meanings
*/
enum QueryFlags
{
FLAGS_MASK_RD = 0x01, /* Recursive */
FLAGS_MASK_TC = 0x02,
FLAGS_MASK_AA = 0x04, /* Authoritative */
FLAGS_MASK_OPCODE = 0x78,
FLAGS_MASK_QR = 0x80,
FLAGS_MASK_RCODE = 0x0F, /* Request */
FLAGS_MASK_Z = 0x70,
FLAGS_MASK_RA = 0x80
};
/** Represents a dns resource record (rr)
*/
struct ResourceRecord
{
QueryType type; /* Record type */
unsigned int rr_class; /* Record class */
unsigned long ttl; /* Time to live */
unsigned int rdlength; /* Record length */
};
/** Represents a dns request/reply header, and its payload as opaque data.
*/
class DNSHeader
{
public:
unsigned char id[2]; /* Request id */
unsigned int flags1; /* Flags */
unsigned int flags2; /* Flags */
unsigned int qdcount;
unsigned int ancount; /* Answer count */
unsigned int nscount; /* Nameserver count */
unsigned int arcount;
unsigned char payload[512]; /* Packet payload */
};
class DNSRequest
{
public:
unsigned char id[2]; /* Request id */
unsigned char* res; /* Result processing buffer */
unsigned int rr_class; /* Request class */
QueryType type; /* Request type */
DNS* dnsobj; /* DNS caller (where we get our FD from) */
unsigned long ttl; /* Time to live */
std::string orig; /* Original requested name/ip */
DNSRequest(DNS* dns, int id, const std::string &original);
~DNSRequest();
DNSInfo ResultIsReady(DNSHeader &h, unsigned length);
int SendRequests(const DNSHeader *header, const int length, QueryType qt);
};
class CacheTimer : public Timer
{
private:
DNS* dns;
public:
CacheTimer(DNS* thisdns)
: Timer(3600, ServerInstance->Time(), true), dns(thisdns) { }
virtual void Tick(time_t)
{
dns->PruneCache();
}
};
class RequestTimeout : public Timer
{
DNSRequest* watch;
int watchid;
public:
RequestTimeout(unsigned long n, DNSRequest* watching, int id) : Timer(n, ServerInstance->Time()), watch(watching), watchid(id)
{
}
~RequestTimeout()
{
if (ServerInstance->Res)
Tick(0);
}
void Tick(time_t)
{
if (ServerInstance->Res->requests[watchid] == watch)
{
/* Still exists, whack it */
if (ServerInstance->Res->Classes[watchid])
{
ServerInstance->Res->Classes[watchid]->OnError(RESOLVER_TIMEOUT, "Request timed out");
delete ServerInstance->Res->Classes[watchid];
ServerInstance->Res->Classes[watchid] = NULL;
}
ServerInstance->Res->requests[watchid] = NULL;
delete watch;
}
}
};
CachedQuery::CachedQuery(const std::string &res, QueryType qt, unsigned int ttl) : data(res), type(qt)
{
expires = ServerInstance->Time() + ttl;
}
int CachedQuery::CalcTTLRemaining()
{
int n = expires - ServerInstance->Time();
return (n < 0 ? 0 : n);
}
/* Allocate the processing buffer */
DNSRequest::DNSRequest(DNS* dns, int rid, const std::string &original) : dnsobj(dns)
{
/* hardening against overflow here: make our work buffer twice the theoretical
* maximum size so that hostile input doesn't screw us over.
*/
res = new unsigned char[sizeof(DNSHeader) * 2];
*res = 0;
orig = original;
RequestTimeout* RT = new RequestTimeout(ServerInstance->Config->dns_timeout ? ServerInstance->Config->dns_timeout : 5, this, rid);
ServerInstance->Timers->AddTimer(RT); /* The timer manager frees this */
}
/* Deallocate the processing buffer */
DNSRequest::~DNSRequest()
{
delete[] res;
}
/** Fill a ResourceRecord class based on raw data input */
inline void DNS::FillResourceRecord(ResourceRecord* rr, const unsigned char *input)
{
rr->type = (QueryType)((input[0] << 8) + input[1]);
rr->rr_class = (input[2] << 8) + input[3];
rr->ttl = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + input[7];
rr->rdlength = (input[8] << 8) + input[9];
}
/** Fill a DNSHeader class based on raw data input of a given length */
inline void DNS::FillHeader(DNSHeader *header, const unsigned char *input, const int length)
{
header->id[0] = input[0];
header->id[1] = input[1];
header->flags1 = input[2];
header->flags2 = input[3];
header->qdcount = (input[4] << 8) + input[5];
header->ancount = (input[6] << 8) + input[7];
header->nscount = (input[8] << 8) + input[9];
header->arcount = (input[10] << 8) + input[11];
memcpy(header->payload,&input[12],length);
}
/** Empty a DNSHeader class out into raw data, ready for transmission */
inline void DNS::EmptyHeader(unsigned char *output, const DNSHeader *header, const int length)
{
output[0] = header->id[0];
output[1] = header->id[1];
output[2] = header->flags1;
output[3] = header->flags2;
output[4] = header->qdcount >> 8;
output[5] = header->qdcount & 0xFF;
output[6] = header->ancount >> 8;
output[7] = header->ancount & 0xFF;
output[8] = header->nscount >> 8;
output[9] = header->nscount & 0xFF;
output[10] = header->arcount >> 8;
output[11] = header->arcount & 0xFF;
memcpy(&output[12],header->payload,length);
}
/** Send requests we have previously built down the UDP socket */
int DNSRequest::SendRequests(const DNSHeader *header, const int length, QueryType qt)
{
ServerInstance->Logs->Log("RESOLVER", DEBUG,"DNSRequest::SendRequests");
unsigned char payload[sizeof(DNSHeader)];
this->rr_class = 1;
this->type = qt;
DNS::EmptyHeader(payload,header,length);
if (ServerInstance->SE->SendTo(dnsobj, payload, length + 12, 0, &(dnsobj->myserver.sa), sa_size(dnsobj->myserver)) != length+12)
return -1;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Sent OK");
return 0;
}
/** Add a query with a predefined header, and allocate an ID for it. */
DNSRequest* DNS::AddQuery(DNSHeader *header, int &id, const char* original)
{
/* Is the DNS connection down? */
if (this->GetFd() == -1)
return NULL;
/* Create an id */
unsigned int tries = 0;
do {
id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
if (++tries == DNS::MAX_REQUEST_ID*5)
{
// If we couldn't find an empty slot this many times, do a sequential scan as a last
// resort. If an empty slot is found that way, go on, otherwise throw an exception
id = -1;
for (int i = 0; i < DNS::MAX_REQUEST_ID; i++)
{
if (!requests[i])
{
id = i;
break;
}
}
if (id == -1)
throw ModuleException("DNS: All ids are in use");
break;
}
} while (requests[id]);
DNSRequest* req = new DNSRequest(this, id, original);
header->id[0] = req->id[0] = id >> 8;
header->id[1] = req->id[1] = id & 0xFF;
header->flags1 = FLAGS_MASK_RD;
header->flags2 = 0;
header->qdcount = 1;
header->ancount = 0;
header->nscount = 0;
header->arcount = 0;
/* At this point we already know the id doesnt exist,
* so there needs to be no second check for the ::end()
*/
requests[id] = req;
/* According to the C++ spec, new never returns NULL. */
return req;
}
int DNS::ClearCache()
{
/* This ensures the buckets are reset to sane levels */
int rv = this->cache->size();
delete this->cache;
this->cache = new dnscache();
return rv;
}
int DNS::PruneCache()
{
int n = 0;
dnscache* newcache = new dnscache();
for (dnscache::iterator i = this->cache->begin(); i != this->cache->end(); i++)
/* Dont include expired items (theres no point) */
if (i->second.CalcTTLRemaining())
newcache->insert(*i);
else
n++;
delete this->cache;
this->cache = newcache;
return n;
}
void DNS::Rehash()
{
if (this->GetFd() > -1)
{
ServerInstance->SE->DelFd(this);
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
/* Rehash the cache */
this->PruneCache();
}
else
{
/* Create initial dns cache */
this->cache = new dnscache();
}
irc::sockets::aptosa(ServerInstance->Config->DNSServer, DNS::QUERY_PORT, myserver);
/* Initialize mastersocket */
int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
this->SetFd(s);
/* Have we got a socket and is it nonblocking? */
if (this->GetFd() != -1)
{
ServerInstance->SE->SetReuse(s);
ServerInstance->SE->NonBlocking(s);
irc::sockets::sockaddrs bindto;
memset(&bindto, 0, sizeof(bindto));
bindto.sa.sa_family = myserver.sa.sa_family;
if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0)
{
/* Failed to bind */
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error binding dns socket - hostnames will NOT resolve");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Internal error starting DNS - hostnames will NOT resolve.");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
}
else
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error creating DNS socket - hostnames will NOT resolve");
}
}
/** Initialise the DNS UDP socket so that we can send requests */
DNS::DNS()
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::DNS");
/* Clear the Resolver class table */
memset(Classes,0,sizeof(Classes));
/* Clear the requests class table */
memset(requests,0,sizeof(requests));
/* DNS::Rehash() sets this to a valid ptr
*/
this->cache = NULL;
/* Again, DNS::Rehash() sets this to a
* valid value
*/
this->SetFd(-1);
/* Actually read the settings
*/
this->Rehash();
this->PruneTimer = new CacheTimer(this);
ServerInstance->Timers->AddTimer(this->PruneTimer);
}
/** Build a payload to be placed after the header, based upon input data, a resource type, a class and a pointer to a buffer */
int DNS::MakePayload(const char * const name, const QueryType rr, const unsigned short rr_class, unsigned char * const payload)
{
short payloadpos = 0;
const char* tempchr, *tempchr2 = name;
unsigned short length;
/* split name up into labels, create query */
while ((tempchr = strchr(tempchr2,'.')) != NULL)
{
length = tempchr - tempchr2;
if (payloadpos + length + 1 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
tempchr2 = &tempchr[1];
}
length = strlen(tempchr2);
if (length)
{
if (payloadpos + length + 2 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
payload[payloadpos++] = 0;
}
if (payloadpos > 508)
return -1;
length = htons(rr);
memcpy(&payload[payloadpos],&length,2);
length = htons(rr_class);
memcpy(&payload[payloadpos + 2],&length,2);
return payloadpos + 4;
}
/** Start lookup of an hostname to an IP address */
int DNS::GetIP(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_A, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_A) == -1))
return -1;
return id;
}
/** Start lookup of an hostname to an IPv6 address */
int DNS::GetIP6(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_AAAA, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_AAAA) == -1))
return -1;
return id;
}
/** Start lookup of a cname to another name */
int DNS::GetCName(const char *alias)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(alias, DNS_QUERY_CNAME, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, alias);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_CNAME) == -1))
return -1;
return id;
}
/** Start lookup of an IP address to a hostname */
int DNS::GetNameForce(const char *ip, ForceProtocol fp)
{
char query[128];
DNSHeader h;
int id;
int length;
if (fp == PROTOCOL_IPV6)
{
in6_addr i;
if (inet_pton(AF_INET6, ip, &i) > 0)
{
DNS::MakeIP6Int(query, &i);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv6 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
else
{
in_addr i;
if (inet_aton(ip, &i))
{
unsigned char* c = (unsigned char*)&i.s_addr;
sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv4 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
length = this->MakePayload(query, DNS_QUERY_PTR, 1, (unsigned char*)&h.payload);
if (length == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't query '%s' using '%s' because it's too long", ip, query);
return -1;
}
DNSRequest* req = this->AddQuery(&h, id, ip);
if (!req)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't add query (resolver down?)");
return -1;
}
if (req->SendRequests(&h, length, DNS_QUERY_PTR) == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't send (firewall?)");
return -1;
}
return id;
}
/** Build an ipv6 reverse domain from an in6_addr
*/
void DNS::MakeIP6Int(char* query, const in6_addr *ip)
{
const char* hex = "0123456789abcdef";
for (int index = 31; index >= 0; index--) /* for() loop steps twice per byte */
{
if (index % 2)
/* low nibble */
*query++ = hex[ip->s6_addr[index / 2] & 0x0F];
else
/* high nibble */
*query++ = hex[(ip->s6_addr[index / 2] & 0xF0) >> 4];
*query++ = '.'; /* Seperator */
}
strcpy(query,"ip6.arpa"); /* Suffix the string */
}
/** Return the next id which is ready, and the result attached to it */
DNSResult DNS::GetResult()
{
/* Fetch dns query response and decide where it belongs */
DNSHeader header;
DNSRequest *req;
unsigned char buffer[sizeof(DNSHeader)];
irc::sockets::sockaddrs from;
memset(&from, 0, sizeof(from));
socklen_t x = sizeof(from);
int length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x);
/* Did we get the whole header? */
if (length < 12)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"GetResult didn't get a full packet (len=%d)", length);
/* Nope - something screwed up. */
return DNSResult(-1,"",0,"");
}
/* Check wether the reply came from a different DNS
* server to the one we sent it to, or the source-port
* is not 53.
* A user could in theory still spoof dns packets anyway
* but this is less trivial than just sending garbage
* to the server, which is possible without this check.
*
* -- Thanks jilles for pointing this one out.
*/
if (from != myserver)
{
std::string server1 = from.str();
std::string server2 = myserver.str();
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
server1.c_str(), server2.c_str());
return DNSResult(-1,"",0,"");
}
/* Put the read header info into a header class */
DNS::FillHeader(&header,buffer,length - 12);
/* Get the id of this request.
* Its a 16 bit value stored in two char's,
* so we use logic shifts to create the value.
*/
unsigned long this_id = header.id[1] + (header.id[0] << 8);
/* Do we have a pending request matching this id? */
if (!requests[this_id])
{
/* Somehow we got a DNS response for a request we never made... */
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.", this_id);
return DNSResult(-1,"",0,"");
}
else
{
/* Remove the query from the list of pending queries */
req = requests[this_id];
requests[this_id] = NULL;
}
/* Inform the DNSRequest class that it has a result to be read.
* When its finished it will return a DNSInfo which is a pair of
* unsigned char* resource record data, and an error message.
*/
DNSInfo data = req->ResultIsReady(header, length);
std::string resultstr;
/* Check if we got a result, if we didnt, its an error */
if (data.first == NULL)
{
/* An error.
* Mask the ID with the value of ERROR_MASK, so that
* the dns_deal_with_classes() function knows that its
* an error response and needs to be treated uniquely.
* Put the error message in the second field.
*/
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, data.second, 0, ro);
}
else
{
unsigned long ttl = req->ttl;
char formatted[128];
/* Forward lookups come back as binary data. We must format them into ascii */
switch (req->type)
{
case DNS_QUERY_A:
snprintf(formatted,16,"%u.%u.%u.%u",data.first[0],data.first[1],data.first[2],data.first[3]);
resultstr = formatted;
break;
case DNS_QUERY_AAAA:
{
if (!inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted)))
{
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, "inet_ntop() failed", 0, ro);
}
resultstr = formatted;
/* Special case. Sending ::1 around between servers
* and to clients is dangerous, because the : on the
* start makes the client or server interpret the IP
* as the last parameter on the line with a value ":1".
*/
if (*formatted == ':')
resultstr.insert(0, "0");
}
break;
case DNS_QUERY_CNAME:
/* Identical handling to PTR */
case DNS_QUERY_PTR:
/* Reverse lookups just come back as char* */
resultstr = std::string((const char*)data.first);
break;
default:
break;
}
/* Build the reply with the id and hostname/ip in it */
std::string ro = req->orig;
DNSResult result = DNSResult(this_id,resultstr,ttl,ro,req->type);
delete req;
return result;
}
}
/** A result is ready, process it */
DNSInfo DNSRequest::ResultIsReady(DNSHeader &header, unsigned length)
{
unsigned i = 0, o;
int q = 0;
int curanswer;
ResourceRecord rr;
unsigned short ptr;
/* This is just to keep _FORTIFY_SOURCE happy */
rr.type = DNS_QUERY_NONE;
rr.rdlength = 0;
rr.ttl = 1; /* GCC is a whiney bastard -- see the XXX below. */
rr.rr_class = 0; /* Same for VC++ */
if (!(header.flags1 & FLAGS_MASK_QR))
return std::make_pair((unsigned char*)NULL,"Not a query result");
if (header.flags1 & FLAGS_MASK_OPCODE)
return std::make_pair((unsigned char*)NULL,"Unexpected value in DNS reply packet");
if (header.flags2 & FLAGS_MASK_RCODE)
return std::make_pair((unsigned char*)NULL,"Domain name not found");
if (header.ancount < 1)
return std::make_pair((unsigned char*)NULL,"No resource records returned");
/* Subtract the length of the header from the length of the packet */
length -= 12;
while ((unsigned int)q < header.qdcount && i < length)
{
if (header.payload[i] > 63)
{
i += 6;
q++;
}
else
{
if (header.payload[i] == 0)
{
q++;
i += 5;
}
else i += header.payload[i] + 1;
}
}
curanswer = 0;
while ((unsigned)curanswer < header.ancount)
{
q = 0;
while (q == 0 && i < length)
{
if (header.payload[i] > 63)
{
i += 2;
q = 1;
}
else
{
if (header.payload[i] == 0)
{
i++;
q = 1;
}
else i += header.payload[i] + 1; /* skip length and label */
}
}
if (static_cast<int>(length - i) < 10)
return std::make_pair((unsigned char*)NULL,"Incorrectly sized DNS reply");
/* XXX: We actually initialise 'rr' here including its ttl field */
DNS::FillResourceRecord(&rr,&header.payload[i]);
i += 10;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver: rr.type is %d and this.type is %d rr.class %d this.class %d", rr.type, this->type, rr.rr_class, this->rr_class);
if (rr.type != this->type)
{
curanswer++;
i += rr.rdlength;
continue;
}
if (rr.rr_class != this->rr_class)
{
curanswer++;
i += rr.rdlength;
continue;
}
break;
}
if ((unsigned int)curanswer == header.ancount)
return std::make_pair((unsigned char*)NULL,"No A, AAAA or PTR type answers (" + ConvToStr(header.ancount) + " answers)");
if (i + rr.rdlength > (unsigned int)length)
return std::make_pair((unsigned char*)NULL,"Resource record larger than stated");
if (rr.rdlength > 1023)
return std::make_pair((unsigned char*)NULL,"Resource record too large");
this->ttl = rr.ttl;
switch (rr.type)
{
/*
* CNAME and PTR are compressed. We need to decompress them.
*/
case DNS_QUERY_CNAME:
case DNS_QUERY_PTR:
{
unsigned short lowest_pos = length;
o = 0;
q = 0;
while (q == 0 && i < length && o + 256 < 1023)
{
/* DN label found (byte over 63) */
if (header.payload[i] > 63)
{
memcpy(&ptr,&header.payload[i],2);
i = ntohs(ptr);
/* check that highest two bits are set. if not, we've been had */
if ((i & DN_COMP_BITMASK) != DN_COMP_BITMASK)
return std::make_pair((unsigned char *) NULL, "DN label decompression header is bogus");
/* mask away the two highest bits. */
i &= ~DN_COMP_BITMASK;
/* and decrease length by 12 bytes. */
i -= 12;
if (i >= lowest_pos)
return std::make_pair((unsigned char *) NULL, "Invalid decompression pointer");
lowest_pos = i;
}
else
{
if (header.payload[i] == 0)
{
q = 1;
}
else
{
res[o] = 0;
if (o != 0)
res[o++] = '.';
if (o + header.payload[i] > sizeof(DNSHeader))
return std::make_pair((unsigned char *) NULL, "DN label decompression is impossible -- malformed/hostile packet?");
memcpy(&res[o], &header.payload[i + 1], header.payload[i]);
o += header.payload[i];
i += header.payload[i] + 1;
}
}
}
res[o] = 0;
}
break;
case DNS_QUERY_AAAA:
if (rr.rdlength != sizeof(struct in6_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 16 bytes for an ipv6 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
case DNS_QUERY_A:
if (rr.rdlength != sizeof(struct in_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 4 bytes for an ipv4 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
default:
return std::make_pair((unsigned char *) NULL, "don't know how to handle undefined type (" + ConvToStr(rr.type) + ") -- rejecting");
break;
}
return std::make_pair(res,"No error");
}
/** Close the master socket */
DNS::~DNS()
{
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
ServerInstance->Timers->DelTimer(this->PruneTimer);
if (cache)
delete cache;
}
CachedQuery* DNS::GetCache(const std::string &source)
{
dnscache::iterator x = cache->find(source.c_str());
if (x != cache->end())
return &(x->second);
else
return NULL;
}
void DNS::DelCache(const std::string &source)
{
cache->erase(source.c_str());
}
void Resolver::TriggerCachedResult()
{
if (CQ)
OnLookupComplete(CQ->data, time_left, true);
}
/** High level abstraction of dns used by application at large */
Resolver::Resolver(const std::string &source, QueryType qt, bool &cached, Module* creator) : Creator(creator), input(source), querytype(qt)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver::Resolver");
cached = false;
CQ = ServerInstance->Res->GetCache(source);
if (CQ)
{
time_left = CQ->CalcTTLRemaining();
if (!time_left)
{
ServerInstance->Res->DelCache(source);
}
else if (CQ->type == qt)
{
cached = true;
return;
}
CQ = NULL;
}
switch (querytype)
{
case DNS_QUERY_A:
this->myid = ServerInstance->Res->GetIP(source.c_str());
break;
case DNS_QUERY_PTR4:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV4);
break;
case DNS_QUERY_PTR6:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV6);
break;
case DNS_QUERY_AAAA:
this->myid = ServerInstance->Res->GetIP6(source.c_str());
break;
case DNS_QUERY_CNAME:
this->myid = ServerInstance->Res->GetCName(source.c_str());
break;
default:
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request with unknown query type %d", querytype);
this->myid = -1;
break;
}
if (this->myid == -1)
{
throw ModuleException("Resolver: Couldn't get an id to make a request");
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request id %d", this->myid);
}
}
/** Called when an error occurs */
void Resolver::OnError(ResolverError, const std::string&)
{
/* Nothing in here */
}
/** Destroy a resolver */
Resolver::~Resolver()
{
/* Nothing here (yet) either */
}
/** Get the request id associated with this class */
int Resolver::GetId()
{
return this->myid;
}
Module* Resolver::GetCreator()
{
return this->Creator;
}
/** Process a socket read event */
void DNS::HandleEvent(EventType, int)
{
/* Fetch the id and result of the next available packet */
DNSResult res(0,"",0,"");
res.id = 0;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Handle DNS event");
res = this->GetResult();
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Result id %d", res.id);
/* Is there a usable request id? */
if (res.id != -1)
{
/* Its an error reply */
if (res.id & ERROR_MASK)
{
/* Mask off the error bit */
res.id -= ERROR_MASK;
/* Marshall the error to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsBad++;
Classes[res.id]->OnError(RESOLVER_NXDOMAIN, res.result);
delete Classes[res.id];
Classes[res.id] = NULL;
}
return;
}
else
{
/* It is a non-error result, marshall the result to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsGood++;
if (!this->GetCache(res.original.c_str()))
this->cache->insert(std::make_pair(res.original.c_str(), CachedQuery(res.result, res.type, res.ttl)));
Classes[res.id]->OnLookupComplete(res.result, res.ttl, false);
delete Classes[res.id];
Classes[res.id] = NULL;
}
}
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDns++;
}
}
/** Add a derived Resolver to the working set */
bool DNS::AddResolverClass(Resolver* r)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"AddResolverClass 0x%08lx", (unsigned long)r);
/* Check the pointers validity and the id's validity */
if ((r) && (r->GetId() > -1))
{
/* Check the slot isnt already occupied -
* This should NEVER happen unless we have
* a severely broken DNS server somewhere
*/
if (!Classes[r->GetId()])
{
/* Set up the pointer to the class */
Classes[r->GetId()] = r;
return true;
}
}
/* Pointer or id not valid, or duplicate id.
* Free the item and return
*/
delete r;
return false;
}
void DNS::CleanResolvers(Module* module)
{
for (int i = 0; i < MAX_REQUEST_ID; i++)
{
if (Classes[i])
{
if (Classes[i]->GetCreator() == module)
{
Classes[i]->OnError(RESOLVER_FORCEUNLOAD, "Parent module is unloading");
delete Classes[i];
Classes[i] = NULL;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1798_0 |
crossvul-cpp_data_bad_600_2 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <string>
#include <vector>
#include <folly/Conv.h>
#include <folly/Range.h>
#include <folly/futures/Promise.h>
#include <folly/io/Cursor.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventBaseManager.h>
#include <folly/io/async/TimeoutManager.h>
#include <folly/io/async/test/MockAsyncTransport.h>
#include <folly/portability/GTest.h>
#include <proxygen/lib/http/codec/HTTPCodecFactory.h>
#include <proxygen/lib/http/codec/test/TestUtils.h>
#include <proxygen/lib/http/session/HTTPDirectResponseHandler.h>
#include <proxygen/lib/http/session/HTTPDownstreamSession.h>
#include <proxygen/lib/http/session/HTTPSession.h>
#include <proxygen/lib/http/session/test/HTTPSessionMocks.h>
#include <proxygen/lib/http/session/test/HTTPSessionTest.h>
#include <proxygen/lib/http/session/test/MockByteEventTracker.h>
#include <proxygen/lib/http/session/test/TestUtils.h>
#include <proxygen/lib/test/TestAsyncTransport.h>
#include <wangle/acceptor/ConnectionManager.h>
using namespace folly::io;
using namespace wangle;
using namespace folly;
using namespace proxygen;
using namespace std;
using namespace testing;
using namespace std::chrono;
using folly::Promise;
template <typename C>
class HTTPDownstreamTest : public testing::Test {
public:
explicit HTTPDownstreamTest(
std::vector<int64_t> flowControl = { -1, -1, -1 },
bool startImmediately = true)
: eventBase_(),
transport_(new TestAsyncTransport(&eventBase_)),
transactionTimeouts_(makeTimeoutSet(&eventBase_)),
flowControl_(flowControl) {
EXPECT_CALL(mockController_, getGracefulShutdownTimeout())
.WillRepeatedly(Return(std::chrono::milliseconds(0)));
EXPECT_CALL(mockController_, attachSession(_))
.WillRepeatedly(Invoke([&] (HTTPSessionBase* session) {
session->setPrioritySampled(true);
}));
HTTPSession::setDefaultReadBufferLimit(65536);
auto codec = makeServerCodec<typename C::Codec>(C::version);
rawCodec_ = codec.get();
// If the codec is H2, getHeaderIndexingStrategy will be called when setting
// up the codec
if (rawCodec_->getProtocol() == CodecProtocol::HTTP_2) {
EXPECT_CALL(mockController_, getHeaderIndexingStrategy())
.WillOnce(
Return(&testH2IndexingStrat_)
);
}
httpSession_ = new HTTPDownstreamSession(
transactionTimeouts_.get(),
std::move(AsyncTransportWrapper::UniquePtr(transport_)),
localAddr, peerAddr,
&mockController_,
std::move(codec),
mockTransportInfo /* no stats for now */,
nullptr);
for (auto& param: flowControl) {
if (param < 0) {
param = rawCodec_->getDefaultWindowSize();
}
}
// Ensure the H2 header indexing strategy was setup correctly if applicable
if (rawCodec_->getProtocol() == CodecProtocol::HTTP_2) {
HTTP2Codec* recastedCodec = dynamic_cast<HTTP2Codec*>(rawCodec_);
EXPECT_EQ(
recastedCodec->getHeaderIndexingStrategy(), &testH2IndexingStrat_);
}
httpSession_->setFlowControl(flowControl[0], flowControl[1],
flowControl[2]);
httpSession_->setEgressSettings({{ SettingsId::MAX_CONCURRENT_STREAMS, 80 },
{ SettingsId::HEADER_TABLE_SIZE, 5555 },
{ SettingsId::ENABLE_PUSH, 1 },
{ SettingsId::ENABLE_EX_HEADERS, 1 }});
if (startImmediately) {
httpSession_->startNow();
}
clientCodec_ = makeClientCodec<typename C::Codec>(C::version);
if (clientCodec_->getProtocol() == CodecProtocol::HTTP_2) {
clientCodec_->getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
}
clientCodec_->generateConnectionPreface(requests_);
clientCodec_->setCallback(&callbacks_);
}
HTTPCodec::StreamID sendRequest(const std::string& url = "/",
int8_t priority = 0,
bool eom = true) {
auto req = getGetRequest();
req.setURL(url);
req.setPriority(priority);
return sendRequest(req, eom);
}
HTTPCodec::StreamID sendRequest(const HTTPMessage& req, bool eom = true) {
auto streamID = clientCodec_->createStream();
clientCodec_->generateHeader(requests_, streamID, req, eom);
return streamID;
}
HTTPCodec::StreamID sendHeader() {
return sendRequest("/", 0, false);
}
Promise<Unit> sendRequestLater(HTTPMessage req, bool eof=false) {
Promise<Unit> reqp;
reqp.getFuture().then(&eventBase_, [=] {
sendRequest(req);
transport_->addReadEvent(requests_, milliseconds(0));
if (eof) {
transport_->addReadEOF(milliseconds(0));
}
});
return reqp;
}
void SetUp() override {
folly::EventBaseManager::get()->clearEventBase();
HTTPSession::setDefaultWriteBufferLimit(65536);
HTTP2PriorityQueue::setNodeLifetime(std::chrono::milliseconds(2));
}
void cleanup() {
EXPECT_CALL(mockController_, detachSession(_));
httpSession_->dropConnection();
}
std::unique_ptr<testing::StrictMock<MockHTTPHandler>>
addSimpleStrictHandler() {
std::unique_ptr<testing::StrictMock<MockHTTPHandler>> handler =
std::make_unique<testing::StrictMock<MockHTTPHandler>>();
// The ownership model here is suspect, but assume the callers won't destroy
// handler before it's requested
auto rawHandler = handler.get();
EXPECT_CALL(mockController_, getRequestHandler(testing::_, testing::_))
.WillOnce(testing::Return(rawHandler))
.RetiresOnSaturation();
EXPECT_CALL(*handler, setTransaction(testing::_))
.WillOnce(testing::SaveArg<0>(&handler->txn_));
return handler;
}
std::unique_ptr<testing::NiceMock<MockHTTPHandler>>
addSimpleNiceHandler() {
std::unique_ptr<testing::NiceMock<MockHTTPHandler>> handler =
std::make_unique<testing::NiceMock<MockHTTPHandler>>();
// See comment above
auto rawHandler = handler.get();
EXPECT_CALL(mockController_, getRequestHandler(testing::_, testing::_))
.WillOnce(testing::Return(rawHandler))
.RetiresOnSaturation();
EXPECT_CALL(*handler, setTransaction(testing::_))
.WillOnce(testing::SaveArg<0>(&handler->txn_));
return handler;
}
void onEOMTerminateHandlerExpectShutdown(MockHTTPHandler& handler) {
handler.expectEOM([&] { handler.terminate(); });
handler.expectDetachTransaction();
expectDetachSession();
}
void expectDetachSession() {
EXPECT_CALL(mockController_, detachSession(testing::_));
}
void addSingleByteReads(const char* data, milliseconds delay={}) {
for (const char* p = data; *p != '\0'; ++p) {
transport_->addReadEvent(p, 1, delay);
}
}
void flushRequestsAndLoop(
bool eof=false, milliseconds eofDelay=milliseconds(0),
milliseconds initialDelay=milliseconds(0),
std::function<void()> extraEventsFn = std::function<void()>()) {
flushRequests(eof, eofDelay, initialDelay, extraEventsFn);
eventBase_.loop();
}
void flushRequestsAndLoopN(uint64_t n,
bool eof=false, milliseconds eofDelay=milliseconds(0),
milliseconds initialDelay=milliseconds(0),
std::function<void()> extraEventsFn = std::function<void()>()) {
flushRequests(eof, eofDelay, initialDelay, extraEventsFn);
for (uint64_t i = 0; i < n; i++) {
eventBase_.loopOnce();
}
}
void flushRequests(
bool eof=false, milliseconds eofDelay=milliseconds(0),
milliseconds initialDelay=milliseconds(0),
std::function<void()> extraEventsFn = std::function<void()>()) {
transport_->addReadEvent(requests_, initialDelay);
if (extraEventsFn) {
extraEventsFn();
}
if (eof) {
transport_->addReadEOF(eofDelay);
}
transport_->startReadEvents();
}
void testSimpleUpgrade(
const std::string& upgradeHeader,
CodecProtocol expectedProtocol,
const std::string& expectedUpgradeHeader);
void gracefulShutdown() {
folly::DelayedDestruction::DestructorGuard g(httpSession_);
clientCodec_->generateGoaway(this->requests_, 0, ErrorCode::NO_ERROR);
expectDetachSession();
flushRequestsAndLoop(true);
}
void testPriorities(uint32_t numPriorities);
void testChunks(bool trailers);
void expect101(CodecProtocol expectedProtocol,
const std::string& expectedUpgrade,
bool expect100 = false) {
NiceMock<MockHTTPCodecCallback> callbacks;
EXPECT_CALL(callbacks, onMessageBegin(_, _));
EXPECT_CALL(callbacks, onNativeProtocolUpgrade(_, _, _, _))
.WillOnce(
Invoke([this, expectedUpgrade] (HTTPCodec::StreamID,
CodecProtocol,
const std::string&,
HTTPMessage& msg) {
EXPECT_EQ(msg.getStatusCode(), 101);
EXPECT_EQ(msg.getStatusMessage(), "Switching Protocols");
EXPECT_EQ(msg.getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE),
expectedUpgrade);
// also connection and date
EXPECT_EQ(msg.getHeaders().size(), 3);
breakParseOutput_ = true;
return true;
}));
// this comes before 101, but due to gmock this is backwards
if (expect100) {
EXPECT_CALL(callbacks, onMessageBegin(_, _))
.RetiresOnSaturation();
EXPECT_CALL(callbacks, onHeadersComplete(_, _))
.WillOnce(Invoke([] (HTTPCodec::StreamID,
std::shared_ptr<HTTPMessage> msg) {
LOG(INFO) << "100 headers";
EXPECT_EQ(msg->getStatusCode(), 100);
}))
.RetiresOnSaturation();
EXPECT_CALL(callbacks, onMessageComplete(_, _))
.RetiresOnSaturation();
}
clientCodec_->setCallback(&callbacks);
parseOutput(*clientCodec_);
clientCodec_ = HTTPCodecFactory::getCodec(expectedProtocol,
TransportDirection::UPSTREAM);
}
void expectResponse(uint32_t code = 200,
ErrorCode errorCode = ErrorCode::NO_ERROR,
bool expect100 = false, bool expectGoaway = false) {
expectResponses(1, code, errorCode, expect100, expectGoaway);
}
void expectResponses(uint32_t n, uint32_t code = 200,
ErrorCode errorCode = ErrorCode::NO_ERROR,
bool expect100 = false, bool expectGoaway = false) {
clientCodec_->setCallback(&callbacks_);
if (isParallelCodecProtocol(clientCodec_->getProtocol())) {
EXPECT_CALL(callbacks_, onSettings(_))
.WillOnce(Invoke([this] (const SettingsList& settings) {
if (flowControl_[0] > 0) {
bool foundInitialWindow = false;
for (const auto& setting: settings) {
if (setting.id == SettingsId::INITIAL_WINDOW_SIZE) {
EXPECT_EQ(flowControl_[0], setting.value);
foundInitialWindow = true;
}
}
EXPECT_TRUE(foundInitialWindow);
}
}));
}
if (flowControl_[2] > 0) {
int64_t sessionDelta =
flowControl_[2] - clientCodec_->getDefaultWindowSize();
if (clientCodec_->supportsSessionFlowControl() && sessionDelta) {
EXPECT_CALL(callbacks_, onWindowUpdate(0, sessionDelta));
}
}
if (flowControl_[1] > 0) {
size_t initWindow = flowControl_[0] > 0 ?
flowControl_[0] : clientCodec_->getDefaultWindowSize();
int64_t streamDelta = flowControl_[1] - initWindow;
if (clientCodec_->supportsStreamFlowControl() && streamDelta) {
EXPECT_CALL(callbacks_, onWindowUpdate(1, streamDelta));
}
}
if (expectGoaway) {
EXPECT_CALL(callbacks_, onGoaway(HTTPCodec::StreamID(1),
ErrorCode::NO_ERROR, _));
}
for (uint32_t i = 0; i < n; i++) {
uint8_t times = (expect100) ? 2 : 1;
EXPECT_CALL(callbacks_, onMessageBegin(_, _))
.Times(times).RetiresOnSaturation();
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.WillOnce(Invoke([code] (HTTPCodec::StreamID,
std::shared_ptr<HTTPMessage> msg) {
EXPECT_EQ(msg->getStatusCode(), code);
}));
if (expect100) {
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.WillOnce(Invoke([] (HTTPCodec::StreamID,
std::shared_ptr<HTTPMessage> msg) {
EXPECT_EQ(msg->getStatusCode(), 100);
}))
.RetiresOnSaturation();
}
if (errorCode != ErrorCode::NO_ERROR) {
EXPECT_CALL(callbacks_, onAbort(_, _))
.WillOnce(Invoke([errorCode] (HTTPCodec::StreamID,
ErrorCode error) {
EXPECT_EQ(error, errorCode);
}));
}
EXPECT_CALL(callbacks_, onBody(_, _, _)).RetiresOnSaturation();
EXPECT_CALL(callbacks_, onMessageComplete(_, _)).RetiresOnSaturation();
}
parseOutput(*clientCodec_);
}
void parseOutput(HTTPCodec& clientCodec) {
auto writeEvents = transport_->getWriteEvents();
while (!breakParseOutput_ &&
(!writeEvents->empty() || !parseOutputStream_.empty())) {
if (!writeEvents->empty()) {
auto event = writeEvents->front();
auto vec = event->getIoVec();
for (size_t i = 0; i < event->getCount(); i++) {
parseOutputStream_.append(
IOBuf::copyBuffer(vec[i].iov_base, vec[i].iov_len));
}
writeEvents->pop_front();
}
uint32_t consumed = clientCodec.onIngress(*parseOutputStream_.front());
parseOutputStream_.split(consumed);
}
if (!breakParseOutput_) {
EXPECT_EQ(parseOutputStream_.chainLength(), 0);
}
breakParseOutput_ = false;
}
void resumeWritesInLoop() {
eventBase_.runInLoop([this] { transport_->resumeWrites(); });
}
void resumeWritesAfterDelay(milliseconds delay) {
eventBase_.runAfterDelay([this] { transport_->resumeWrites(); },
delay.count());
}
MockByteEventTracker* setMockByteEventTracker() {
auto byteEventTracker = new MockByteEventTracker(nullptr);
httpSession_->setByteEventTracker(
std::unique_ptr<ByteEventTracker>(byteEventTracker));
EXPECT_CALL(*byteEventTracker, preSend(_, _, _))
.WillRepeatedly(Return(0));
EXPECT_CALL(*byteEventTracker, drainByteEvents())
.WillRepeatedly(Return(0));
EXPECT_CALL(*byteEventTracker, processByteEvents(_, _))
.WillRepeatedly(Invoke([]
(std::shared_ptr<ByteEventTracker> self,
uint64_t bytesWritten) {
return self->ByteEventTracker::processByteEvents(
self,
bytesWritten);
}));
return byteEventTracker;
}
protected:
EventBase eventBase_;
TestAsyncTransport* transport_; // invalid once httpSession_ is destroyed
folly::HHWheelTimer::UniquePtr transactionTimeouts_;
std::vector<int64_t> flowControl_;
StrictMock<MockController> mockController_;
HTTPDownstreamSession* httpSession_;
IOBufQueue requests_{IOBufQueue::cacheChainLength()};
unique_ptr<HTTPCodec> clientCodec_;
NiceMock<MockHTTPCodecCallback> callbacks_;
IOBufQueue parseOutputStream_{IOBufQueue::cacheChainLength()};
bool breakParseOutput_{false};
typename C::Codec* rawCodec_{nullptr};
HeaderIndexingStrategy testH2IndexingStrat_;
};
// Uses TestAsyncTransport
using HTTPDownstreamSessionTest = HTTPDownstreamTest<HTTP1xCodecPair>;
using SPDY3DownstreamSessionTest = HTTPDownstreamTest<SPDY3CodecPair>;
namespace {
class HTTP2DownstreamSessionTest : public HTTPDownstreamTest<HTTP2CodecPair> {
public:
HTTP2DownstreamSessionTest()
: HTTPDownstreamTest<HTTP2CodecPair>() {}
void SetUp() override {
HTTPDownstreamTest<HTTP2CodecPair>::SetUp();
}
void SetupControlStream(HTTPCodec::StreamID cStreamId) {
// enable EX_HEADERS
clientCodec_->getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
clientCodec_->generateSettings(requests_);
// create a control stream
clientCodec_->generateHeader(requests_, cStreamId, getGetRequest("/cc"),
true, nullptr);
}
void TearDown() override {
}
};
}
namespace {
class HTTP2DownstreamSessionEarlyShutdownTest :
public HTTPDownstreamTest<HTTP2CodecPair> {
public:
HTTP2DownstreamSessionEarlyShutdownTest()
: HTTPDownstreamTest<HTTP2CodecPair>({-1, -1, -1}, false) {}
void SetUp() override {
HTTPDownstreamTest<HTTP2CodecPair>::SetUp();
}
void TearDown() override {
}
};
}
TEST_F(HTTP2DownstreamSessionEarlyShutdownTest, EarlyShutdown) {
folly::DelayedDestruction::DestructorGuard g(httpSession_);
// Try shutting down the session and then starting it. This should be properly
// handled by the HTTPSession such that no HTTP/2 frames are sent in the
// wrong order.
StrictMock<MockHTTPCodecCallback> callbacks;
clientCodec_->setCallback(&callbacks);
EXPECT_CALL(callbacks, onFrameHeader(_, _, _, _, _)).Times(2);
EXPECT_CALL(callbacks, onSettings(_)).Times(1);
EXPECT_CALL(callbacks, onGoaway(_, _, _)).Times(1);
expectDetachSession();
httpSession_->notifyPendingShutdown();
httpSession_->startNow();
eventBase_.loop();
parseOutput(*clientCodec_);
}
TEST_F(HTTPDownstreamSessionTest, ImmediateEof) {
// Send EOF without any request data
EXPECT_CALL(mockController_, getRequestHandler(_, _)).Times(0);
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(0));
}
TEST_F(HTTPDownstreamSessionTest, Http10NoHeaders) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/", msg->getURL());
EXPECT_EQ("/", msg->getPath());
EXPECT_EQ("", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(0, msg->getHTTPVersion().second);
});
onEOMTerminateHandlerExpectShutdown(*handler);
auto req = getGetRequest();
req.setHTTPVersion(1, 0);
sendRequest(req);
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, Http10NoHeadersEof) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("http://example.com/foo?bar", msg->getURL());
EXPECT_EQ("/foo", msg->getPath());
EXPECT_EQ("bar", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(0, msg->getHTTPVersion().second);
});
onEOMTerminateHandlerExpectShutdown(*handler);
const char *req = "GET http://example.com/foo?bar HTTP/1.0\r\n\r\n";
requests_.append(req, strlen(req));
flushRequestsAndLoop(true, milliseconds(0));
}
TEST_F(HTTPDownstreamSessionTest, SingleBytes) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(2, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("connection"));
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/somepath.php?param=foo", msg->getURL());
EXPECT_EQ("/somepath.php", msg->getPath());
EXPECT_EQ("param=foo", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
});
onEOMTerminateHandlerExpectShutdown(*handler);
addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n");
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, SingleBytesWithBody) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(3, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("content-length"));
EXPECT_TRUE(hdrs.exists("myheader"));
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/somepath.php?param=foo", msg->getURL());
EXPECT_EQ("/somepath.php", msg->getPath());
EXPECT_EQ("param=foo", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
});
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("1"))
.WillOnce(ExpectString("2"))
.WillOnce(ExpectString("3"))
.WillOnce(ExpectString("4"))
.WillOnce(ExpectString("5"));
onEOMTerminateHandlerExpectShutdown(*handler);
addSingleByteReads("POST /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"MyHeader: FooBar\r\n"
"Content-Length: 5\r\n"
"\r\n"
"12345");
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, SplitBody) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(2, hdrs.size());
});
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("12345"))
.WillOnce(ExpectString("abcde"));
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("POST / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Length: 10\r\n"
"\r\n"
"12345", milliseconds(0));
transport_->addReadEvent("abcde", milliseconds(5));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, PostChunked) {
InSequence enforceOrder;
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(3, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("content-type"));
EXPECT_TRUE(hdrs.exists("transfer-encoding"));
EXPECT_TRUE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("http://example.com/cgi-bin/foo.aspx?abc&def",
msg->getURL());
EXPECT_EQ("/cgi-bin/foo.aspx", msg->getPath());
EXPECT_EQ("abc&def", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
});
EXPECT_CALL(*handler, onChunkHeader(3));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("bar"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onChunkHeader(0x22));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("0123456789abcdef\nfedcba9876543210\n"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onChunkHeader(3));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("foo"));
EXPECT_CALL(*handler, onChunkComplete());
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("POST http://example.com/cgi-bin/foo.aspx?abc&def "
"HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Type: text/pla", milliseconds(0));
transport_->addReadEvent("in; charset=utf-8\r\n"
"Transfer-encoding: chunked\r\n"
"\r", milliseconds(2));
transport_->addReadEvent("\n"
"3\r\n"
"bar\r\n"
"22\r\n"
"0123456789abcdef\n"
"fedcba9876543210\n"
"\r\n"
"3\r", milliseconds(3));
transport_->addReadEvent("\n"
"foo\r\n"
"0\r\n\r\n", milliseconds(1));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, MultiMessage) {
InSequence enforceOrder;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
EXPECT_CALL(*handler1, onBody(_))
.WillOnce(ExpectString("foo"))
.WillOnce(ExpectString("bar9876"));
handler1->expectEOM([&] { handler1->sendReply(); });
handler1->expectDetachTransaction();
auto handler2 = addSimpleNiceHandler();
handler2->expectHeaders();
EXPECT_CALL(*handler2, onChunkHeader(0xa));
EXPECT_CALL(*handler2, onBody(_))
.WillOnce(ExpectString("some "))
.WillOnce(ExpectString("data\n"));
EXPECT_CALL(*handler2, onChunkComplete());
onEOMTerminateHandlerExpectShutdown(*handler2);
transport_->addReadEvent("POST / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Length: 10\r\n"
"\r\n"
"foo", milliseconds(0));
transport_->addReadEvent("bar9876"
"POST /foo HTTP/1.1\r\n"
"Host: exa", milliseconds(2));
transport_->addReadEvent("mple.com\r\n"
"Connection: close\r\n"
"Trans", milliseconds(0));
transport_->addReadEvent("fer-encoding: chunked\r\n"
"\r\n", milliseconds(2));
transport_->addReadEvent("a\r\nsome ", milliseconds(0));
transport_->addReadEvent("data\n\r\n0\r\n\r\n", milliseconds(2));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, Connect) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
// Send HTTP 200 OK to accept the CONNECT request
handler->expectHeaders([&handler] {
handler->sendHeaders(200, 100);
});
EXPECT_CALL(*handler, onUpgrade(_));
// Data should be received using onBody
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("12345"))
.WillOnce(ExpectString("abcde"));
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("CONNECT test HTTP/1.1\r\n"
"\r\n"
"12345", milliseconds(0));
transport_->addReadEvent("abcde", milliseconds(5));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, ConnectRejected) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
// Send HTTP 400 to reject the CONNECT request
handler->expectHeaders([&handler] {
handler->sendReplyCode(400);
});
onEOMTerminateHandlerExpectShutdown(*handler);
transport_->addReadEvent("CONNECT test HTTP/1.1\r\n"
"\r\n"
"12345", milliseconds(0));
transport_->addReadEvent("abcde", milliseconds(5));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, HttpUpgrade) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
// Send HTTP 101 Switching Protocls to accept the upgrade request
handler->expectHeaders([&handler] {
handler->sendHeaders(101, 100);
});
// Send the response in the new protocol after upgrade
EXPECT_CALL(*handler, onUpgrade(_))
.WillOnce(Invoke([&handler](UpgradeProtocol /*protocol*/) {
handler->sendReplyCode(100);
}));
onEOMTerminateHandlerExpectShutdown(*handler);
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_UPGRADE, "TEST/1.0");
req.getHeaders().add(HTTP_HEADER_CONNECTION, "upgrade");
sendRequest(req);
flushRequestsAndLoop(true, milliseconds(0));
}
TEST(HTTPDownstreamTest, ParseErrorNoTxn) {
// 1) Get a parse error on SYN_STREAM for streamID == 1
// 2) Expect that the codec should be asked to generate an abort on
// streamID==1
EventBase evb;
// Setup the controller and its expecations.
NiceMock<MockController> mockController;
// Setup the codec, its callbacks, and its expectations.
auto codec = makeDownstreamParallelCodec();
HTTPCodec::Callback* codecCallback = nullptr;
EXPECT_CALL(*codec, setCallback(_))
.WillRepeatedly(SaveArg<0>(&codecCallback));
// Expect egress abort for streamID == 1
EXPECT_CALL(*codec, generateRstStream(_, 1, _));
// Setup transport
bool transportGood = true;
auto transport = newMockTransport(&evb);
EXPECT_CALL(*transport, good())
.WillRepeatedly(ReturnPointee(&transportGood));
EXPECT_CALL(*transport, closeNow())
.WillRepeatedly(Assign(&transportGood, false));
EXPECT_CALL(*transport, writeChain(_, _, _))
.WillRepeatedly(
Invoke([&] (folly::AsyncTransportWrapper::WriteCallback* callback,
const shared_ptr<IOBuf>&, WriteFlags) {
callback->writeSuccess();
}));
// Create the downstream session, thus initializing codecCallback
auto transactionTimeouts = makeInternalTimeoutSet(&evb);
auto session = new HTTPDownstreamSession(
transactionTimeouts.get(),
AsyncTransportWrapper::UniquePtr(transport),
localAddr, peerAddr,
&mockController, std::move(codec),
mockTransportInfo,
nullptr);
session->startNow();
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, "foo");
ex.setProxygenError(kErrorParseHeader);
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
codecCallback->onError(HTTPCodec::StreamID(1), ex, true);
// cleanup
session->dropConnection();
evb.loop();
}
TEST(HTTPDownstreamTest, ByteEventsDrained) {
// Test that byte events are drained before socket is closed
EventBase evb;
NiceMock<MockController> mockController;
auto codec = makeDownstreamParallelCodec();
auto byteEventTracker = new MockByteEventTracker(nullptr);
auto transport = newMockTransport(&evb);
auto transactionTimeouts = makeInternalTimeoutSet(&evb);
// Create the downstream session
auto session = new HTTPDownstreamSession(
transactionTimeouts.get(),
AsyncTransportWrapper::UniquePtr(transport),
localAddr, peerAddr,
&mockController, std::move(codec),
mockTransportInfo,
nullptr);
session->setByteEventTracker(
std::unique_ptr<ByteEventTracker>(byteEventTracker));
InSequence enforceOrder;
session->startNow();
// Byte events should be drained first
EXPECT_CALL(*byteEventTracker, drainByteEvents())
.Times(1);
EXPECT_CALL(*transport, closeNow())
.Times(AtLeast(1));
// Close the socket
session->dropConnection();
evb.loop();
}
TEST_F(HTTPDownstreamSessionTest, HttpWithAckTiming) {
// This is to test cases where holding a byte event to a finished HTTP/1.1
// transaction does not masquerade as HTTP pipelining.
auto byteEventTracker = setMockByteEventTracker();
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
handler1->sendChunkedReplyWithBody(200, 100, 100, false);
});
// Hold a pending byte event
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _))
.WillOnce(Invoke([] (HTTPTransaction* txn,
uint64_t /*byteNo*/) {
txn->incrementPendingByteEvents();
}));
sendRequest();
flushRequestsAndLoop();
expectResponse();
// Send the secode request after receiving the first response (eg: clearly
// not pipelined)
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
handler2->sendChunkedReplyWithBody(200, 100, 100, false);
});
// This txn processed and destroyed before txn1
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _));
handler2->expectDetachTransaction();
sendRequest();
flushRequestsAndLoop();
expectResponse();
// Now clear the pending byte event (simulate ack) and the first txn
// goes away too
handler1->expectDetachTransaction();
handler1->txn_->decrementPendingByteEvents();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, TestOnContentMismatch) {
// Test the behavior when the reported content-length on the header
// is different from the actual length of the body.
// The expectation is simply to log the behavior, such as:
// ".. HTTPTransaction.cpp ] Content-Length/body mismatch: expected: .. "
folly::EventBase base;
InSequence enforceOrder;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
// over-estimate the content-length on the header
handler1->sendHeaders(200, 105);
handler1->sendBody(100);
handler1->txn_->sendEOM();
});
sendRequest();
flushRequestsAndLoop();
auto handler2 = addSimpleNiceHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
// under-estimate the content-length on the header
handler2->sendHeaders(200, 95);
handler2->sendBody(100);
handler2->txn_->sendEOM();
});
sendRequest();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, HttpWithAckTimingPipeline) {
// Test a real pipelining case as well. First request is done waiting for
// ack, then receive two pipelined requests.
auto byteEventTracker = setMockByteEventTracker();
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
handler1->sendChunkedReplyWithBody(200, 100, 100, false);
});
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _))
.WillOnce(Invoke([] (HTTPTransaction* txn,
uint64_t /*byteNo*/) {
txn->incrementPendingByteEvents();
}));
sendRequest();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
handler2->sendChunkedReplyWithBody(200, 100, 100, false);
});
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _));
handler2->expectDetachTransaction();
sendRequest();
sendRequest();
auto handler3 = addSimpleStrictHandler();
handler3->expectHeaders();
handler3->expectEOM([&handler3] () {
handler3->sendChunkedReplyWithBody(200, 100, 100, false);
});
EXPECT_CALL(*byteEventTracker, addLastByteEvent(_, _));
handler3->expectDetachTransaction();
flushRequestsAndLoop();
expectResponses(3);
handler1->expectDetachTransaction();
handler1->txn_->decrementPendingByteEvents();
gracefulShutdown();
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] regular request 1st stream (getGetRequest())
* - [server --> client] respond 1st stream (res, 100 bytes, without EOM)
* - [server --> client] request 2nd stream (pub, 200 bytes, EOM)
* - [client --> server] respond 2nd stream (OK, EOM)
* - [client --> server] EOM on the 1st stream
*/
TEST_F(HTTP2DownstreamSessionTest, ExheaderFromServer) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// Create a dummy request and a dummy response messages
auto pub = getGetRequest("/sub/fyi");
// set up the priority for fun
pub.setHTTP2Priority(std::make_tuple(0, false, 7));
InSequence handlerSequence;
auto cHandler = addSimpleStrictHandler();
StrictMock<MockHTTPHandler> pubHandler;
cHandler->expectHeaders([&] {
cHandler->txn_->pauseIngress();
// Generate response for the control stream
cHandler->txn_->sendHeaders(getResponse(200, 0));
cHandler->txn_->sendBody(makeBuf(100));
auto* pubTxn = cHandler->txn_->newExTransaction(&pubHandler);
// Generate a pub request (encapsulated in EX_HEADERS frame)
pubTxn->sendHeaders(pub);
pubTxn->sendBody(makeBuf(200));
pubTxn->sendEOM();
});
EXPECT_CALL(pubHandler, setTransaction(_));
EXPECT_CALL(callbacks_, onSettings(_))
.WillOnce(InvokeWithoutArgs([&] {
clientCodec_->generateSettingsAck(requests_);
}));
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onExMessageBegin(2, _, _, _));
EXPECT_CALL(callbacks_, onHeadersComplete(2, _));
EXPECT_CALL(callbacks_, onMessageComplete(2, _));
EXPECT_CALL(pubHandler, onHeadersComplete(_));
EXPECT_CALL(pubHandler, onEOM());
EXPECT_CALL(pubHandler, detachTransaction());
EXPECT_CALL(*cHandler, onEOM());
EXPECT_CALL(*cHandler, detachTransaction());
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
eventBase_.runAfterDelay([&] {
parseOutput(*clientCodec_);
// send a response from client to server
clientCodec_->generateExHeader(requests_, 2, getResponse(200, 0),
HTTPCodec::ExAttributes(cStreamId, false),
true, nullptr);
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
parseOutput(*clientCodec_);
cHandler->txn_->resumeIngress();
cHandler->txn_->sendEOM();
transport_->addReadEOF(milliseconds(0));
}, 100);
HTTPSession::DestructorGuard g(httpSession_);
expectDetachSession();
eventBase_.loop();
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] regular request on control stream 1
* - [client --> server] Pub request on stream 3
* - [server --> client] response on stream 1 (OK, )
* - [server --> client] response on stream 3 (OK, EOM)
* - [server --> client] response on stream 1 (EOM)
*/
TEST_F(HTTP2DownstreamSessionTest, ExheaderFromClient) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// generate an EX_HEADERS
auto exStreamId = cStreamId + 2;
clientCodec_->generateExHeader(requests_, exStreamId, getGetRequest("/pub"),
HTTPCodec::ExAttributes(cStreamId, false),
true, nullptr);
auto cHandler = addSimpleStrictHandler();
cHandler->expectHeaders([&] {
// send back the response for control stream, but EOM
cHandler->txn_->sendHeaders(getResponse(200, 0));
});
EXPECT_CALL(*cHandler, onEOM());
StrictMock<MockHTTPHandler> pubHandler;
EXPECT_CALL(*cHandler, onExTransaction(_))
.WillOnce(Invoke([&pubHandler] (HTTPTransaction* exTxn) {
exTxn->setHandler(&pubHandler);
pubHandler.txn_ = exTxn;
}));
InSequence handlerSequence;
EXPECT_CALL(pubHandler, setTransaction(_));
pubHandler.expectHeaders([&] {
// send back the response for the pub request
pubHandler.txn_->sendHeadersWithEOM(getResponse(200, 0));
});
EXPECT_CALL(pubHandler, onEOM());
EXPECT_CALL(pubHandler, detachTransaction());
cHandler->expectDetachTransaction();
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onExMessageBegin(exStreamId, _, _, _));
EXPECT_CALL(callbacks_, onHeadersComplete(exStreamId, _));
EXPECT_CALL(callbacks_, onMessageComplete(exStreamId, _));
EXPECT_CALL(callbacks_, onMessageComplete(cStreamId, _));
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
transport_->addReadEOF(milliseconds(0));
eventBase_.loop();
HTTPSession::DestructorGuard g(httpSession_);
expectDetachSession();
cHandler->txn_->sendEOM();
eventBase_.loop();
parseOutput(*clientCodec_);
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] regular request 1st stream (getGetRequest())
* - [server --> client] request 2nd stream (unidirectional)
* - [server --> client] response + EOM on the 1st stream
*/
TEST_F(HTTP2DownstreamSessionTest, UnidirectionalExTransaction) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
InSequence handlerSequence;
auto cHandler = addSimpleStrictHandler();
StrictMock<MockHTTPHandler> uniHandler;
cHandler->expectHeaders([&] {
auto* uniTxn = cHandler->txn_->newExTransaction(&uniHandler, true);
EXPECT_TRUE(uniTxn->isIngressComplete());
uniTxn->sendHeaders(getGetRequest("/uni"));
uniTxn->sendEOM();
// close control stream
cHandler->txn_->sendHeadersWithEOM(getResponse(200, 0));
});
EXPECT_CALL(uniHandler, setTransaction(_));
EXPECT_CALL(*cHandler, onEOM());
EXPECT_CALL(uniHandler, detachTransaction());
EXPECT_CALL(*cHandler, detachTransaction());
transport_->addReadEvent(requests_, milliseconds(0));
transport_->startReadEvents();
eventBase_.runAfterDelay([&] {
transport_->addReadEOF(milliseconds(0));
}, 100);
HTTPSession::DestructorGuard g(httpSession_);
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, PauseResumeControlStream) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// generate an EX_HEADERS
clientCodec_->generateExHeader(requests_, cStreamId + 2, getGetRequest(),
HTTPCodec::ExAttributes(cStreamId, false),
true, nullptr);
auto cHandler = addSimpleStrictHandler();
cHandler->expectHeaders([&] {
cHandler->txn_->pauseIngress();
// send back the response for control stream, but EOM
cHandler->txn_->sendHeaders(getResponse(200, 0));
});
EXPECT_CALL(*cHandler, onEOM());
StrictMock<MockHTTPHandler> pubHandler;
EXPECT_CALL(*cHandler, onExTransaction(_))
.WillOnce(Invoke([&pubHandler] (HTTPTransaction* exTxn) {
exTxn->setHandler(&pubHandler);
pubHandler.txn_ = exTxn;
}));
InSequence handlerSequence;
EXPECT_CALL(pubHandler, setTransaction(_));
pubHandler.expectHeaders([&] {
// send back the response for the pub request
pubHandler.txn_->sendHeadersWithEOM(getResponse(200, 0));
});
EXPECT_CALL(pubHandler, onEOM());
EXPECT_CALL(pubHandler, detachTransaction());
cHandler->expectDetachTransaction();
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId + 2, _));
EXPECT_CALL(callbacks_, onMessageComplete(cStreamId + 2, _));
EXPECT_CALL(callbacks_, onMessageComplete(cStreamId, _));
HTTPSession::DestructorGuard g(httpSession_);
transport_->addReadEvent(requests_, milliseconds(0));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
cHandler->txn_->resumeIngress();
cHandler->txn_->sendEOM();
eventBase_.loop();
expectDetachSession();
parseOutput(*clientCodec_);
}
TEST_F(HTTP2DownstreamSessionTest, InvalidControlStream) {
auto cStreamId = HTTPCodec::StreamID(1);
SetupControlStream(cStreamId);
// generate an EX_HEADERS, but with a non-existing control stream
clientCodec_->generateExHeader(requests_, cStreamId + 2, getGetRequest(),
HTTPCodec::ExAttributes(cStreamId + 4, false),
true, nullptr);
auto cHandler = addSimpleStrictHandler();
InSequence handlerSequence;
cHandler->expectHeaders([&] {
// send back the response for control stream, but EOM
cHandler->txn_->sendHeaders(getResponse(200, 0));
});
EXPECT_CALL(*cHandler, onExTransaction(_)).Times(0);
EXPECT_CALL(*cHandler, onEOM());
cHandler->expectDetachTransaction();
EXPECT_CALL(callbacks_, onMessageBegin(cStreamId, _));
EXPECT_CALL(callbacks_, onHeadersComplete(cStreamId, _));
EXPECT_CALL(callbacks_, onAbort(cStreamId + 2, _));
HTTPSession::DestructorGuard g(httpSession_);
transport_->addReadEvent(requests_, milliseconds(0));
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
cHandler->txn_->sendEOM();
eventBase_.loop();
expectDetachSession();
parseOutput(*clientCodec_);
}
TEST_F(HTTP2DownstreamSessionTest, SetByteEventTracker) {
InSequence enforceOrder;
// Send two requests with writes paused, which will queue several byte events,
// including last byte events which are holding a reference to the
// transaction.
transport_->pauseWrites();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] () {
handler1->sendReplyWithBody(200, 100);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] () {
handler2->sendReplyWithBody(200, 100);
});
sendRequest();
sendRequest();
// Resume writes from the loop callback
eventBase_.runInLoop([this] {
transport_->resumeWrites();
});
// Graceful shutdown will notify of GOAWAY
EXPECT_CALL(*handler1, onGoaway(ErrorCode::NO_ERROR));
EXPECT_CALL(*handler2, onGoaway(ErrorCode::NO_ERROR));
// The original byteEventTracker will process the last byte event of the
// first transaction, and detach by deleting the event. Swap out the tracker.
handler1->expectDetachTransaction([this] {
auto tracker = std::make_unique<ByteEventTracker>(httpSession_);
httpSession_->setByteEventTracker(std::move(tracker));
});
// handler2 should also be detached immediately because the new
// ByteEventTracker continues procesing where the old one left off.
handler2->expectDetachTransaction();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, TestTrackedByteEventTracker) {
auto byteEventTracker = setMockByteEventTracker();
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
size_t bytesToSend = 200;
size_t expectedTrackedByteOffset = bytesToSend + 99;
handler1->expectHeaders();
handler1->expectEOM([&handler1, &bytesToSend] () {
handler1->sendHeaders(200, 200);
handler1->sendBodyWithLastByteTracking(bytesToSend);
handler1->txn_->sendEOM();
});
EXPECT_CALL(*byteEventTracker,
addTrackedByteEvent(_, expectedTrackedByteOffset))
.WillOnce(Invoke([] (HTTPTransaction* txn,
uint64_t /*byteNo*/) {
txn->incrementPendingByteEvents();
}));
sendRequest();
flushRequestsAndLoop();
handler1->expectDetachTransaction();
handler1->txn_->decrementPendingByteEvents();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, Trailers) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&handler]() {
handler->sendReplyWithBody(
200, 100, true /* keepalive */, true /* sendEOM */, true /*trailers*/);
});
handler->expectDetachTransaction();
HTTPSession::DestructorGuard g(httpSession_);
sendRequest();
flushRequestsAndLoop(true, milliseconds(0));
EXPECT_CALL(callbacks_, onMessageBegin(1, _)).Times(1);
EXPECT_CALL(callbacks_, onHeadersComplete(1, _)).Times(1);
EXPECT_CALL(callbacks_, onBody(1, _, _));
EXPECT_CALL(callbacks_, onTrailersComplete(1, _));
EXPECT_CALL(callbacks_, onMessageComplete(1, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTPDownstreamSessionTest, Trailers) {
testChunks(true);
}
TEST_F(HTTPDownstreamSessionTest, ExplicitChunks) {
testChunks(false);
}
template <class C>
void HTTPDownstreamTest<C>::testChunks(bool trailers) {
InSequence enforceOrder;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&handler, trailers] () {
handler->sendChunkedReplyWithBody(200, 100, 17, trailers);
});
handler->expectDetachTransaction();
HTTPSession::DestructorGuard g(httpSession_);
sendRequest();
flushRequestsAndLoop(true, milliseconds(0));
EXPECT_CALL(callbacks_, onMessageBegin(1, _))
.Times(1);
EXPECT_CALL(callbacks_, onHeadersComplete(1, _))
.Times(1);
for (int i = 0; i < 6; i++) {
EXPECT_CALL(callbacks_, onChunkHeader(1, _));
EXPECT_CALL(callbacks_, onBody(1, _, _));
EXPECT_CALL(callbacks_, onChunkComplete(1));
}
if (trailers) {
EXPECT_CALL(callbacks_, onTrailersComplete(1, _));
}
EXPECT_CALL(callbacks_, onMessageComplete(1, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTPDownstreamSessionTest, HttpDrain) {
InSequence enforceOrder;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders([this, &handler1] {
handler1->sendHeaders(200, 100);
httpSession_->notifyPendingShutdown();
});
handler1->expectEOM([&handler1] {
handler1->sendBody(100);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders([&handler2] {
handler2->sendHeaders(200, 100);
});
handler2->expectEOM([&handler2] {
handler2->sendBody(100);
handler2->txn_->sendEOM();
});
handler2->expectDetachTransaction();
expectDetachSession();
sendRequest();
sendRequest();
flushRequestsAndLoop();
}
// 1) receive full request
// 2) notify pending shutdown
// 3) wait for session read timeout -> should be ignored
// 4) response completed
TEST_F(HTTPDownstreamSessionTest, HttpDrainLongRunning) {
InSequence enforceSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders([this, &handler] {
httpSession_->notifyPendingShutdown();
eventBase_.tryRunAfterDelay([this] {
// simulate read timeout
httpSession_->timeoutExpired();
}, 100);
eventBase_.tryRunAfterDelay([&handler] {
handler->sendReplyWithBody(200, 100);
}, 200);
});
handler->expectEOM();
handler->expectDetachTransaction();
expectDetachSession();
sendRequest();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, EarlyAbort) {
StrictMock<MockHTTPHandler> handler;
InSequence enforceOrder;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
handler.txn_ = txn;
handler.txn_->sendAbort();
}));
handler.expectDetachTransaction();
expectDetachSession();
addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n");
transport_->addReadEOF(milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(SPDY3DownstreamSessionTest, HttpPausedBuffered) {
IOBufQueue rst{IOBufQueue::cacheChainLength()};
auto s = sendRequest();
clientCodec_->generateRstStream(rst, s, ErrorCode::CANCEL);
sendRequest();
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
transport_->pauseWrites();
handler1->sendHeaders(200, 65536 * 2);
handler1->sendBody(65536 * 2);
});
handler1->expectEgressPaused();
auto handler2 = addSimpleNiceHandler();
handler2->expectEgressPaused();
handler2->expectHeaders();
handler2->expectEOM([&] {
eventBase_.runInLoop([&] {
transport_->addReadEvent(rst, milliseconds(0)); });
});
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorStreamAbort);
resumeWritesInLoop();
});
handler1->expectDetachTransaction();
handler2->expectEgressResumed([&] {
handler2->sendReplyWithBody(200, 32768);
});
handler2->expectDetachTransaction([this] {
eventBase_.runInLoop([&] { transport_->addReadEOF(milliseconds(0)); });
});
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, HttpWritesDrainingTimeout) {
sendRequest();
sendHeader();
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
transport_->pauseWrites();
handler1->sendHeaders(200, 1000);
});
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("WriteTimeout on transaction id: ",
handler1->txn_->getID()),
std::string(ex.what()));
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, HttpRateLimitNormal) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
// Create a request
sendRequest();
InSequence handlerSequence;
// Set a low rate-limit on the transaction
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders([&] {
uint32_t rateLimit_kbps = 640;
handler1->txn_->setEgressRateLimit(rateLimit_kbps * 1024);
});
// Send a somewhat big response that we know will get rate-limited
handler1->expectEOM([&handler1] {
// At 640kbps, this should take slightly over 800ms
uint32_t rspLengthBytes = 100000;
handler1->sendHeaders(200, rspLengthBytes);
handler1->sendBody(rspLengthBytes);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
proxygen::TimePoint timeFirstWrite =
transport_->getWriteEvents()->front()->getTime();
proxygen::TimePoint timeLastWrite =
transport_->getWriteEvents()->back()->getTime();
int64_t writeDuration =
(int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count();
EXPECT_GE(writeDuration, 800);
cleanup();
}
TEST_F(SPDY3DownstreamSessionTest, SpdyRateLimitNormal) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
100000);
clientCodec_->generateSettings(requests_);
sendRequest();
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders([&] {
uint32_t rateLimit_kbps = 640;
handler1->txn_->setEgressRateLimit(rateLimit_kbps * 1024);
});
handler1->expectEOM([&handler1] {
// At 640kbps, this should take slightly over 800ms
uint32_t rspLengthBytes = 100000;
handler1->sendHeaders(200, rspLengthBytes);
handler1->sendBody(rspLengthBytes);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop(true, milliseconds(50));
proxygen::TimePoint timeFirstWrite =
transport_->getWriteEvents()->front()->getTime();
proxygen::TimePoint timeLastWrite =
transport_->getWriteEvents()->back()->getTime();
int64_t writeDuration =
(int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count();
EXPECT_GE(writeDuration, 800);
expectDetachSession();
}
/**
* This test will reset the connection while the server is waiting around
* to send more bytes (so as to keep under the rate limit).
*/
TEST_F(SPDY3DownstreamSessionTest, SpdyRateLimitRst) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
IOBufQueue rst{IOBufQueue::cacheChainLength()};
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
100000);
clientCodec_->generateSettings(requests_);
auto streamID = sendRequest();
clientCodec_->generateRstStream(rst, streamID, ErrorCode::CANCEL);
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders([&] {
uint32_t rateLimit_kbps = 640;
handler1->txn_->setEgressRateLimit(rateLimit_kbps * 1024);
});
handler1->expectEOM([&handler1] {
uint32_t rspLengthBytes = 100000;
handler1->sendHeaders(200, rspLengthBytes);
handler1->sendBody(rspLengthBytes);
handler1->txn_->sendEOM();
});
handler1->expectError();
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(50), milliseconds(0), [&] {
transport_->addReadEvent(rst, milliseconds(10));
});
}
// Send a 1.0 request, egress the EOM with the last body chunk on a paused
// socket, and let it timeout. dropConnection()
// to removeTransaction with writesDraining_=true
TEST_F(HTTPDownstreamSessionTest, WriteTimeout) {
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
sendRequest(req);
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
handler1->sendHeaders(200, 100);
eventBase_.tryRunAfterDelay([&handler1, this] {
transport_->pauseWrites();
handler1->sendBody(100);
handler1->txn_->sendEOM();
}, 50);
});
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(folly::to<std::string>("WriteTimeout on transaction id: ",
handler1->txn_->getID()),
std::string(ex.what()));
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
// Send an abort from the write timeout path while pipelining
TEST_F(HTTPDownstreamSessionTest, WriteTimeoutPipeline) {
const char* buf = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"
"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
requests_.append(buf, strlen(buf));
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this] {
handler1->sendHeaders(200, 100);
eventBase_.tryRunAfterDelay([&handler1, this] {
transport_->pauseWrites();
handler1->sendBody(100);
handler1->txn_->sendEOM();
}, 50);
});
auto handler2 = addSimpleNiceHandler();
handler2->expectHeaders();
handler2->expectEOM();
handler1->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(folly::to<std::string>("WriteTimeout on transaction id: ",
handler1->txn_->getID()),
std::string(ex.what()));
handler1->txn_->sendAbort();
});
handler2->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(folly::to<std::string>("WriteTimeout on transaction id: ",
handler2->txn_->getID()),
std::string(ex.what()));
handler2->txn_->sendAbort();
});
handler2->expectDetachTransaction();
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTPDownstreamSessionTest, BodyPacketization) {
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
req.setWantsKeepalive(false);
sendRequest(req);
InSequence handlerSequence;
auto handler1 = addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 32768);
});
handler1->expectDetachTransaction();
expectDetachSession();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
EXPECT_EQ(transport_->getWriteEvents()->size(), 1);
}
TEST_F(HTTPDownstreamSessionTest, HttpMalformedPkt1) {
// Create a HTTP connection and keep sending just '\n' to the HTTP1xCodec.
std::string data(90000, '\n');
requests_.append(data.data(), data.length());
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(0));
}
TEST_F(HTTPDownstreamSessionTest, BigExplcitChunkWrite) {
// even when the handler does a massive write, the transport only gets small
// writes
sendRequest();
auto handler = addSimpleNiceHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(200, 100, false);
size_t len = 16 * 1024 * 1024;
handler->txn_->sendChunkHeader(len);
auto chunk = makeBuf(len);
handler->txn_->sendBody(std::move(chunk));
handler->txn_->sendChunkTerminator();
handler->txn_->sendEOM();
});
handler->expectDetachTransaction();
expectDetachSession();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
EXPECT_GT(transport_->getWriteEvents()->size(), 250);
}
// ==== upgrade tests ====
// Test upgrade to a protocol unknown to HTTPSession
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNonNative) {
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(101, 0, true, {{"Upgrade", "blarf"}});
});
EXPECT_CALL(*handler, onUpgrade(UpgradeProtocol::TCP));
handler->expectEOM([&handler] {
handler->txn_->sendEOM();
});
handler->expectDetachTransaction();
sendRequest(getUpgradeRequest("blarf"));
expectDetachSession();
flushRequestsAndLoop(true);
}
// Test upgrade to a protocol unknown to HTTPSession, but don't switch
// protocols
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNonNativeIgnore) {
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectEOM();
handler->expectDetachTransaction();
sendRequest(getUpgradeRequest("blarf"));
expectDetachSession();
flushRequestsAndLoop(true);
}
// Test upgrade to a protocol unknown to HTTPSession
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNonNativePipeline) {
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders([&handler1] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_EQ(msg->getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE),
"blarf");
handler1->sendReplyWithBody(200, 100);
});
handler1->expectEOM();
handler1->expectDetachTransaction();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders([&handler2] {
handler2->sendReplyWithBody(200, 100);
});
handler2->expectEOM();
handler2->expectDetachTransaction();
sendRequest(getUpgradeRequest("blarf"));
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"\r\n");
expectDetachSession();
flushRequestsAndLoop(true);
}
// Helper that does a simple upgrade test - request an upgrade, receive a 101
// and an upgraded response
template <class C>
void HTTPDownstreamTest<C>::testSimpleUpgrade(
const std::string& upgradeHeader,
CodecProtocol expectedProtocol,
const std::string& expectedUpgradeHeader) {
this->rawCodec_->setAllowedUpgradeProtocols({expectedUpgradeHeader});
auto handler = addSimpleStrictHandler();
HeaderIndexingStrategy testH2IndexingStrat;
handler->expectHeaders();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM(
[&handler, expectedProtocol, expectedUpgradeHeader, &testH2IndexingStrat] {
EXPECT_FALSE(handler->txn_->getSetupTransportInfo().secure);
EXPECT_EQ(*handler->txn_->getSetupTransportInfo().appProtocol,
expectedUpgradeHeader);
if (expectedProtocol == CodecProtocol::HTTP_2) {
const HTTP2Codec* codec = dynamic_cast<const HTTP2Codec*>(
&handler->txn_->getTransport().getCodec());
ASSERT_NE(codec, nullptr);
EXPECT_EQ(codec->getHeaderIndexingStrategy(), &testH2IndexingStrat);
}
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
if (expectedProtocol == CodecProtocol::HTTP_2) {
EXPECT_CALL(mockController_, getHeaderIndexingStrategy())
.WillOnce(
Return(&testH2IndexingStrat)
);
}
HTTPMessage req = getUpgradeRequest(upgradeHeader);
if (upgradeHeader == http2::kProtocolCleartextString) {
HTTP2Codec::requestUpgrade(req);
}
sendRequest(req);
flushRequestsAndLoop();
expect101(expectedProtocol, expectedUpgradeHeader);
expectResponse();
gracefulShutdown();
}
// Upgrade to SPDY/3
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNative3) {
testSimpleUpgrade("spdy/3", CodecProtocol::SPDY_3, "spdy/3");
}
// Upgrade to SPDY/3.1
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNative31) {
testSimpleUpgrade("spdy/3.1", CodecProtocol::SPDY_3_1, "spdy/3.1");
}
// Upgrade to HTTP/2
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeH2) {
testSimpleUpgrade("h2c", CodecProtocol::HTTP_2, "h2c");
}
class HTTPDownstreamSessionUpgradeFlowControlTest :
public HTTPDownstreamSessionTest {
public:
HTTPDownstreamSessionUpgradeFlowControlTest()
: HTTPDownstreamSessionTest({100000, 105000, 110000}) {}
};
// Upgrade to HTTP/2, with non-default flow control settings
TEST_F(HTTPDownstreamSessionUpgradeFlowControlTest, UpgradeH2Flowcontrol) {
testSimpleUpgrade("h2c", CodecProtocol::HTTP_2, "h2c");
}
// Upgrade to SPDY/3.1 with a non-native proto in the list
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeUnknown) {
// This is maybe weird, the client asked for non-native as first choice,
// but we go native
testSimpleUpgrade("blarf, spdy/3.1, spdy/3",
CodecProtocol::SPDY_3_1, "spdy/3.1");
}
// Upgrade header with extra whitespace
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeWhitespace) {
testSimpleUpgrade(" \tspdy/3.1\t , spdy/3",
CodecProtocol::SPDY_3_1, "spdy/3.1");
}
// Upgrade header with random junk
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeJunk) {
testSimpleUpgrade(",,,, ,,\t~^%$(*&@(@$^^*(,spdy/3",
CodecProtocol::SPDY_3, "spdy/3");
}
// Attempt to upgrade on second txn
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeTxn2) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 100);
});
handler1->expectDetachTransaction();
sendRequest(getGetRequest());
flushRequestsAndLoop();
expectResponse();
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2] {
handler2->sendReplyWithBody(200, 100);
});
handler2->expectDetachTransaction();
sendRequest(getUpgradeRequest("spdy/3"));
flushRequestsAndLoop();
expectResponse();
gracefulShutdown();
}
// Upgrade on POST
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePost) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
// cheat and not sending EOM, it's a no-op
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3");
expectResponse();
gracefulShutdown();
}
// Upgrade on POST with a reply that comes before EOM, don't switch protocols
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePostEarlyResp) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectBody();
handler->expectEOM();
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expectResponse();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePostEarlyPartialResp) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(200, 100);
});
handler->expectBody();
handler->expectEOM([&handler] {
handler->sendBody(100);
handler->txn_->sendEOM();
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expectResponse();
gracefulShutdown();
}
// Upgrade but with a pipelined HTTP request. It is parsed as SPDY and
// rejected
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativeExtra) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
sendRequest(getUpgradeRequest("spdy/3"));
// It's a fatal to send this out on the HTTP1xCodec, so hack it manually
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"Upgrade: spdy/3\r\n"
"\r\n");
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3");
expectResponse(200, ErrorCode::_SPDY_INVALID_STREAM);
gracefulShutdown();
}
// Upgrade on POST with Expect: 100-Continue. If the 100 goes out
// before the EOM is parsed, the 100 will be in HTTP. This should be the normal
// case since the client *should* wait a bit for the 100 continue to come back
// before sending the POST. But if the 101 is delayed beyond EOM, the 101
// will come via SPDY.
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePost100) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders([&handler] {
handler->sendHeaders(100, 0);
});
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
req.getHeaders().add(HTTP_HEADER_EXPECT, "100-continue");
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3", true /* expect 100 continue */);
expectResponse();
gracefulShutdown();
}
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeNativePost100Late) {
this->rawCodec_->setAllowedUpgradeProtocols({"spdy/3"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM([&handler] {
handler->sendHeaders(100, 0);
handler->sendReplyWithBody(200, 100);
});
handler->expectDetachTransaction();
HTTPMessage req = getUpgradeRequest("spdy/3", HTTPMethod::POST, 10);
req.getHeaders().add(HTTP_HEADER_EXPECT, "100-continue");
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
flushRequestsAndLoop();
expect101(CodecProtocol::SPDY_3, "spdy/3");
expectResponse(200, ErrorCode::NO_ERROR, true /* expect 100 via SPDY */);
gracefulShutdown();
}
TEST_F(SPDY3DownstreamSessionTest, SpdyPrio) {
testPriorities(8);
cleanup();
}
// Test sending a GOAWAY while the downstream session is still processing
// the request that was an upgrade. The reply GOAWAY should have last good
// stream = 1, not 0.
TEST_F(HTTPDownstreamSessionTest, HttpUpgradeGoawayDrain) {
this->rawCodec_->setAllowedUpgradeProtocols({"h2c"});
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectBody();
EXPECT_CALL(mockController_, onSessionCodecChange(httpSession_));
handler->expectEOM();
handler->expectGoaway();
handler->expectDetachTransaction();
EXPECT_CALL(mockController_, getHeaderIndexingStrategy())
.WillOnce(
Return(&testH2IndexingStrat_)
);
HTTPMessage req = getUpgradeRequest("h2c", HTTPMethod::POST, 10);
HTTP2Codec::requestUpgrade(req);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(10),
HTTPCodec::NoPadding, true);
// cheat and not sending EOM, it's a no-op
flushRequestsAndLoop();
expect101(CodecProtocol::HTTP_2, "h2c");
clientCodec_->generateConnectionPreface(requests_);
clientCodec_->generateGoaway(requests_, 0, ErrorCode::NO_ERROR);
flushRequestsAndLoop();
eventBase_.runInLoop([&handler] {
handler->sendReplyWithBody(200, 100);
});
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
expectResponse(200, ErrorCode::NO_ERROR, false, true);
expectDetachSession();
}
template <class C>
void HTTPDownstreamTest<C>::testPriorities(uint32_t numPriorities) {
uint32_t iterations = 10;
uint32_t maxPriority = numPriorities - 1;
std::vector<std::unique_ptr<testing::NiceMock<MockHTTPHandler>>> handlers;
for (int pri = numPriorities - 1; pri >= 0; pri--) {
for (uint32_t i = 0; i < iterations; i++) {
sendRequest("/", pri * (8 / numPriorities));
InSequence handlerSequence;
auto handler = addSimpleNiceHandler();
auto rawHandler = handler.get();
handlers.push_back(std::move(handler));
rawHandler->expectHeaders();
rawHandler->expectEOM([rawHandler] {
rawHandler->sendReplyWithBody(200, 1000);
});
rawHandler->expectDetachTransaction([] { });
}
}
auto buf = requests_.move();
buf->coalesce();
requests_.append(std::move(buf));
flushRequestsAndLoop();
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks_, onMessageBegin(_, _))
.Times(iterations * numPriorities);
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.Times(iterations * numPriorities);
// body is variable and hence ignored
EXPECT_CALL(callbacks_, onMessageComplete(_, _))
.Times(iterations * numPriorities)
.WillRepeatedly(Invoke([&](HTTPCodec::StreamID stream, bool /*upgrade*/) {
streams.push_back(stream);
}));
parseOutput(*clientCodec_);
// transactions finish in priority order (higher streamIDs first)
EXPECT_EQ(streams.size(), iterations * numPriorities);
auto txn = streams.begin();
for (int band = maxPriority; band >= 0; band--) {
auto upperID = iterations * 2 * (band + 1);
auto lowerID = iterations * 2 * band;
for (uint32_t i = 0; i < iterations; i++) {
EXPECT_LE(lowerID, (uint32_t)*txn);
EXPECT_GE(upperID, (uint32_t)*txn);
++txn;
}
}
}
// Verifies that the read timeout is not running when no ingress is expected/
// required to proceed
TEST_F(SPDY3DownstreamSessionTest, SpdyTimeout) {
sendRequest();
sendRequest();
httpSession_->setWriteBufferLimit(512);
InSequence handlerSequence;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders([this] { transport_->pauseWrites(); });
handler1->expectEOM([&] {
handler1->sendHeaders(200, 1000);
handler1->sendBody(1000);
});
handler1->expectEgressPaused();
auto handler2 = addSimpleStrictHandler();
// handler2 is paused before it gets headers
handler2->expectEgressPaused();
handler2->expectHeaders();
handler2->expectEOM([this] {
// This transaction should start egress paused. We've received the
// EOM, so the timeout shouldn't be running delay 400ms and resume
// writes, this keeps txn1 from getting a write timeout
resumeWritesAfterDelay(milliseconds(400));
});
handler1->expectEgressResumed([&handler1] { handler1->txn_->sendEOM(); });
handler2->expectEgressResumed([&handler2, this] {
// delay an additional 200ms. The total 600ms delay shouldn't fire
// onTimeout
eventBase_.tryRunAfterDelay([&handler2] {
handler2->sendReplyWithBody(200, 400); }, 200
);
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoop(false, milliseconds(0), milliseconds(10));
cleanup();
}
// Verifies that the read timer is running while a transaction is blocked
// on a window update
TEST_F(SPDY3DownstreamSessionTest, SpdyTimeoutWin) {
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec_->generateSettings(requests_);
auto streamID = sendRequest();
InSequence handlerSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&] {
handler->sendReplyWithBody(200, 1000);
});
handler->expectEgressPaused();
handler->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("ingress timeout, streamID=", streamID),
std::string(ex.what()));
handler->terminate();
});
handler->expectDetachTransaction();
flushRequestsAndLoop();
cleanup();
}
TYPED_TEST_CASE_P(HTTPDownstreamTest);
TYPED_TEST_P(HTTPDownstreamTest, TestWritesDraining) {
auto badCodec =
makeServerCodec<typename TypeParam::Codec>(TypeParam::version);
this->sendRequest();
badCodec->generatePushPromise(this->requests_, 2 /* bad */, getGetRequest(),
1);
this->expectDetachSession();
InSequence handlerSequence;
auto handler1 = this->addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM();
handler1->expectError([&](const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorEOF);
ASSERT_TRUE(
folly::StringPiece(ex.what()).startsWith("Shutdown transport: EOF"))
<< ex.what();
});
handler1->expectDetachTransaction();
this->flushRequestsAndLoop();
}
TYPED_TEST_P(HTTPDownstreamTest, TestBodySizeLimit) {
this->clientCodec_->generateWindowUpdate(this->requests_, 0, 65536);
this->sendRequest();
this->sendRequest();
InSequence handlerSequence;
auto handler1 = this->addSimpleNiceHandler();
handler1->expectHeaders();
handler1->expectEOM();
auto handler2 = this->addSimpleNiceHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler1->sendReplyWithBody(200, 33000);
handler2->sendReplyWithBody(200, 33000);
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
this->flushRequestsAndLoop();
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(this->callbacks_, onMessageBegin(1, _));
EXPECT_CALL(this->callbacks_, onHeadersComplete(1, _));
EXPECT_CALL(this->callbacks_, onMessageBegin(3, _));
EXPECT_CALL(this->callbacks_, onHeadersComplete(3, _));
for (uint32_t i = 0; i < 8; i++) {
EXPECT_CALL(this->callbacks_, onBody(1, _, _));
EXPECT_CALL(this->callbacks_, onBody(3, _, _));
}
EXPECT_CALL(this->callbacks_, onBody(1, _, _));
EXPECT_CALL(this->callbacks_, onMessageComplete(1, _));
EXPECT_CALL(this->callbacks_, onBody(3, _, _));
EXPECT_CALL(this->callbacks_, onMessageComplete(3, _));
this->parseOutput(*this->clientCodec_);
this->cleanup();
}
#define IF_HTTP2(X) \
if (this->clientCodec_->getProtocol() == CodecProtocol::HTTP_2) { X; }
TYPED_TEST_P(HTTPDownstreamTest, TestUniformPauseState) {
this->httpSession_->setWriteBufferLimit(12000);
this->clientCodec_->getEgressSettings()->setSetting(
SettingsId::INITIAL_WINDOW_SIZE, 1000000);
this->clientCodec_->generateSettings(this->requests_);
this->clientCodec_->generateWindowUpdate(this->requests_, 0, 1000000);
this->sendRequest("/", 1);
this->sendRequest("/", 1);
this->sendRequest("/", 2);
InSequence handlerSequence;
auto handler1 = this->addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM();
auto handler2 = this->addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler1->sendHeaders(200, 24002);
// triggers pause of all txns
this->transport_->pauseWrites();
handler1->txn_->sendBody(std::move(makeBuf(12001)));
this->resumeWritesAfterDelay(milliseconds(50));
});
handler1->expectEgressPaused();
handler2->expectEgressPaused();
auto handler3 = this->addSimpleStrictHandler();
handler3->expectEgressPaused();
handler3->expectHeaders();
handler3->expectEOM();
handler1->expectEgressResumed([&] {
// resume does not trigger another pause,
handler1->txn_->sendBody(std::move(makeBuf(12001)));
});
// handler2 gets a fair shot, handler3 is not resumed
// HTTP/2 priority is not implemented, so handler3 is like another 0 pri txn
handler2->expectEgressResumed();
IF_HTTP2(handler3->expectEgressResumed());
handler1->expectEgressPaused();
handler2->expectEgressPaused();
IF_HTTP2(handler3->expectEgressPaused());
handler1->expectEgressResumed();
handler2->expectEgressResumed([&] {
handler2->sendHeaders(200, 12001);
handler2->txn_->sendBody(std::move(makeBuf(12001)));
this->transport_->pauseWrites();
this->resumeWritesAfterDelay(milliseconds(50));
});
// handler3 not resumed
IF_HTTP2(handler3->expectEgressResumed());
handler1->expectEgressPaused();
handler2->expectEgressPaused();
IF_HTTP2(handler3->expectEgressPaused());
handler1->expectEgressResumed();
handler2->expectEgressResumed([&] {
handler1->txn_->sendEOM();
handler2->txn_->sendEOM();
});
handler3->expectEgressResumed([&] {
handler3->txn_->sendAbort();
});
handler3->expectDetachTransaction();
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
this->flushRequestsAndLoop();
this->cleanup();
}
// Test exceeding the MAX_CONCURRENT_STREAMS setting. The txn should get
// REFUSED_STREAM, and other streams can complete normally
TYPED_TEST_P(HTTPDownstreamTest, TestMaxTxns) {
auto settings = this->rawCodec_->getEgressSettings();
auto maxTxns = settings->getSetting(SettingsId::MAX_CONCURRENT_STREAMS,
100);
std::list<unique_ptr<StrictMock<MockHTTPHandler>>> handlers;
{
InSequence enforceOrder;
for (auto i = 0U; i < maxTxns; i++) {
this->sendRequest();
auto handler = this->addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM();
handlers.push_back(std::move(handler));
}
auto streamID = this->sendRequest();
this->clientCodec_->generateGoaway(this->requests_, 0, ErrorCode::NO_ERROR);
for (auto& handler: handlers) {
EXPECT_CALL(*handler, onGoaway(ErrorCode::NO_ERROR));
}
this->flushRequestsAndLoop();
EXPECT_CALL(this->callbacks_, onSettings(_));
EXPECT_CALL(this->callbacks_, onAbort(streamID, ErrorCode::REFUSED_STREAM));
this->parseOutput(*this->clientCodec_);
}
// handlers can finish out of order?
for (auto& handler: handlers) {
handler->sendReplyWithBody(200, 100);
handler->expectDetachTransaction();
}
this->expectDetachSession();
this->eventBase_.loop();
}
// Set max streams=1
// send two spdy requests a few ms apart.
// Block writes
// generate a complete response for txn=1 before parsing txn=3
// HTTPSession should allow the txn=3 to be served rather than refusing it
TEST_F(SPDY3DownstreamSessionTest, SpdyMaxConcurrentStreams) {
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
req.setWantsKeepalive(false);
sendRequest(req);
auto req2p = sendRequestLater(req, true);
httpSession_->setEgressSettings({{
SettingsId::MAX_CONCURRENT_STREAMS, 1}});
InSequence handlerSequence;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, req, this, &req2p] {
transport_->pauseWrites();
handler1->sendReplyWithBody(200, 100);
req2p.setValue();
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2, this] {
handler2->sendReplyWithBody(200, 100);
resumeWritesInLoop();
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
REGISTER_TYPED_TEST_CASE_P(HTTPDownstreamTest,
TestWritesDraining, TestBodySizeLimit,
TestUniformPauseState, TestMaxTxns);
typedef ::testing::Types<SPDY3CodecPair, SPDY3_1CodecPair,
HTTP2CodecPair> ParallelCodecs;
INSTANTIATE_TYPED_TEST_CASE_P(ParallelCodecs,
HTTPDownstreamTest,
ParallelCodecs);
class SPDY31DownstreamTest : public HTTPDownstreamTest<SPDY3_1CodecPair> {
public:
SPDY31DownstreamTest()
: HTTPDownstreamTest<SPDY3_1CodecPair>({-1, -1,
2 * spdy::kInitialWindow}) {}
};
TEST_F(SPDY31DownstreamTest, TestSessionFlowControl) {
eventBase_.loopOnce();
InSequence sequence;
EXPECT_CALL(callbacks_, onSettings(_));
EXPECT_CALL(callbacks_, onWindowUpdate(0, spdy::kInitialWindow));
parseOutput(*clientCodec_);
cleanup();
}
TEST_F(SPDY3DownstreamSessionTest, TestEOFOnBlockedStream) {
sendRequest();
auto handler1 = addSimpleStrictHandler();
InSequence handlerSequence;
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 80000);
});
handler1->expectEgressPaused();
handler1->expectError([&] (const HTTPException& ex) {
// Not optimal to have a different error code here than the session
// flow control case, but HTTPException direction is immutable and
// building another one seems not future proof.
EXPECT_EQ(ex.getDirection(), HTTPException::Direction::INGRESS);
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop(true, milliseconds(10));
}
TEST_F(SPDY31DownstreamTest, TestEOFOnBlockedSession) {
sendRequest();
sendRequest();
InSequence handlerSequence;
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendHeaders(200, 40000);
handler1->sendBody(32769);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&handler2, this] {
handler2->sendHeaders(200, 40000);
handler2->sendBody(32768);
eventBase_.runInLoop([this] { transport_->addReadEOF(milliseconds(0)); });
});
handler1->expectEgressPaused();
handler2->expectEgressPaused();
handler1->expectEgressResumed();
handler2->expectEgressResumed();
handler1->expectError([&] (const HTTPException& ex) {
EXPECT_EQ(ex.getDirection(),
HTTPException::Direction::INGRESS_AND_EGRESS);
});
handler1->expectDetachTransaction();
handler2->expectError([&] (const HTTPException& ex) {
EXPECT_EQ(ex.getDirection(),
HTTPException::Direction::INGRESS_AND_EGRESS);
});
handler2->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(SPDY3DownstreamSessionTest, NewTxnEgressPaused) {
// Send 1 request with prio=0
// Have egress pause while sending the first response
// Send a second request with prio=1
// -- the new txn should start egress paused
// Finish the body and eom both responses
// Unpause egress
// The first txn should complete first
sendRequest("/", 0);
auto req2 = getGetRequest();
req2.setPriority(1);
auto req2p = sendRequestLater(req2, true);
unique_ptr<StrictMock<MockHTTPHandler>> handler1;
unique_ptr<StrictMock<MockHTTPHandler>> handler2;
httpSession_->setWriteBufferLimit(200); // lower the per session buffer limit
{
InSequence handlerSequence;
handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1, this, &req2p] {
this->transport_->pauseWrites();
handler1->sendHeaders(200, 1000);
handler1->sendBody(100); // headers + 100 bytes - over the limit
req2p.setValue();
});
handler1->expectEgressPaused([] { LOG(INFO) << "paused 1"; });
handler2 = addSimpleStrictHandler();
handler2->expectEgressPaused(); // starts paused
handler2->expectHeaders();
handler2->expectEOM([&] {
// Technically shouldn't send while handler is egress paused, but meh.
handler1->sendBody(900);
handler1->txn_->sendEOM();
handler2->sendReplyWithBody(200, 1000);
resumeWritesInLoop();
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
}
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop();
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks_, onMessageBegin(_, _))
.Times(2);
EXPECT_CALL(callbacks_, onHeadersComplete(_, _))
.Times(2);
// body is variable and hence ignored;
EXPECT_CALL(callbacks_, onMessageComplete(_, _))
.WillRepeatedly(Invoke([&](HTTPCodec::StreamID stream, bool /*upgrade*/) {
streams.push_back(stream);
}));
parseOutput(*clientCodec_);
cleanup();
}
TEST_F(HTTP2DownstreamSessionTest, ZeroDeltaWindowUpdate) {
// generateHeader() will create a session and a transaction
auto streamID = sendHeader();
// First generate a frame with delta=1 so as to pass the checks, and then
// hack the frame so that delta=0 without modifying other checks
clientCodec_->generateWindowUpdate(requests_, streamID, 1);
requests_.trimEnd(http2::kFrameWindowUpdateSize);
QueueAppender appender(&requests_, http2::kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(0);
auto handler = addSimpleStrictHandler();
InSequence handlerSequence;
handler->expectHeaders();
handler->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getCodecStatusCode(), ErrorCode::PROTOCOL_ERROR);
ASSERT_EQ(
"streamID=1 with HTTP2Codec stream error: window update delta=0",
std::string(ex.what()));
});
handler->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTP2DownstreamSessionTest, PaddingFlowControl) {
// generateHeader() will create a session and a transaction
auto streamID = sendHeader();
// This sends a total of 33kb including padding, so we should get a session
// and stream window update
for (auto i = 0; i < 129; i++) {
clientCodec_->generateBody(requests_, streamID, makeBuf(1), 255, false);
}
auto handler = addSimpleStrictHandler();
InSequence handlerSequence;
handler->expectHeaders([&] {
handler->txn_->pauseIngress();
eventBase_.runAfterDelay([&] { handler->txn_->resumeIngress(); },
100);
});
EXPECT_CALL(*handler, onBody(_))
.Times(129);
handler->expectError();
handler->expectDetachTransaction();
HTTPSession::DestructorGuard g(httpSession_);
flushRequestsAndLoop(false, milliseconds(0), milliseconds(0), [&] {
clientCodec_->generateRstStream(requests_, streamID, ErrorCode::CANCEL);
clientCodec_->generateGoaway(requests_, 0, ErrorCode::NO_ERROR);
transport_->addReadEvent(requests_, milliseconds(110));
});
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks_, onWindowUpdate(0, _));
EXPECT_CALL(callbacks_, onWindowUpdate(1, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTP2DownstreamSessionTest, GracefulDrainOnTimeout) {
InSequence handlerSequence;
std::chrono::milliseconds gracefulTimeout(200);
httpSession_->enableDoubleGoawayDrain();
EXPECT_CALL(mockController_, getGracefulShutdownTimeout())
.WillOnce(InvokeWithoutArgs([&] {
// Once session asks for graceful shutdown timeout, expect the client
// to receive the first GOAWAY
eventBase_.runInLoop([&] {
EXPECT_CALL(callbacks_,
onGoaway(std::numeric_limits<int32_t>::max(),
ErrorCode::NO_ERROR, _));
parseOutput(*clientCodec_);
});
return gracefulTimeout;
}));
// Simulate ConnectionManager idle timeout
eventBase_.runAfterDelay([&] { httpSession_->timeoutExpired(); },
transactionTimeouts_->getDefaultTimeout().count());
HTTPSession::DestructorGuard g(httpSession_);
auto start = getCurrentTime();
eventBase_.loop();
auto finish = getCurrentTime();
auto minDuration =
gracefulTimeout + transactionTimeouts_->getDefaultTimeout();
EXPECT_GE((finish - start).count(), minDuration.count());
EXPECT_CALL(callbacks_, onGoaway(0, ErrorCode::NO_ERROR, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
/*
* The sequence of streams are generated in the following order:
* - [client --> server] request 1st stream (getGetRequest())
* - [server --> client] respond 1st stream (res with length 100)
* - [server --> client] request 2nd stream (req)
* - [server --> client] respond 2nd stream (res with length 200 + EOM)
* - [client --> server] RST_STREAM on the 1st stream
*/
TEST_F(HTTP2DownstreamSessionTest, ServerPush) {
// Create a dummy request and a dummy response messages
HTTPMessage req, res;
req.getHeaders().set("HOST", "www.foo.com");
req.setURL("https://www.foo.com/");
res.setStatusCode(200);
res.setStatusMessage("Ohai");
// enable server push
clientCodec_->getEgressSettings()->setSetting(SettingsId::ENABLE_PUSH, 1);
clientCodec_->generateSettings(requests_);
// generateHeader() will create a session and a transaction
auto assocStreamId = HTTPCodec::StreamID(1);
clientCodec_->generateHeader(requests_, assocStreamId, getGetRequest(),
false, nullptr);
auto handler = addSimpleStrictHandler();
StrictMock<MockHTTPPushHandler> pushHandler;
InSequence handlerSequence;
handler->expectHeaders([&] {
// Generate response for the associated stream
handler->txn_->sendHeaders(res);
handler->txn_->sendBody(makeBuf(100));
handler->txn_->pauseIngress();
auto* pushTxn = handler->txn_->newPushedTransaction(&pushHandler);
ASSERT_NE(pushTxn, nullptr);
// Generate a push request (PUSH_PROMISE)
auto outgoingStreams = httpSession_->getNumOutgoingStreams();
pushTxn->sendHeaders(req);
EXPECT_EQ(httpSession_->getNumOutgoingStreams(), outgoingStreams);
// Generate a push response
auto pri = handler->txn_->getPriority();
res.setHTTP2Priority(std::make_tuple(pri.streamDependency,
pri.exclusive, pri.weight));
pushTxn->sendHeaders(res);
EXPECT_EQ(httpSession_->getNumOutgoingStreams(), outgoingStreams + 1);
pushTxn->sendBody(makeBuf(200));
pushTxn->sendEOM();
eventBase_.runAfterDelay([&] { handler->txn_->resumeIngress(); },
100);
});
EXPECT_CALL(pushHandler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
pushHandler.txn_ = txn; }));
EXPECT_CALL(pushHandler, detachTransaction());
handler->expectError();
handler->expectDetachTransaction();
transport_->addReadEvent(requests_, milliseconds(0));
clientCodec_->generateRstStream(requests_, assocStreamId, ErrorCode::CANCEL);
clientCodec_->generateGoaway(requests_, 2, ErrorCode::NO_ERROR);
transport_->addReadEvent(requests_, milliseconds(200));
transport_->startReadEvents();
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
EXPECT_CALL(callbacks_, onMessageBegin(1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(1, _));
EXPECT_CALL(callbacks_, onPushMessageBegin(2, 1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(2, _));
EXPECT_CALL(callbacks_, onMessageBegin(2, _));
EXPECT_CALL(callbacks_, onHeadersComplete(2, _));
EXPECT_CALL(callbacks_, onMessageComplete(2, _));
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTP2DownstreamSessionTest, ServerPushAbortPaused) {
// Create a dummy request and a dummy response messages
HTTPMessage req, res;
req.getHeaders().set("HOST", "www.foo.com");
req.setURL("https://www.foo.com/");
res.setStatusCode(200);
res.setStatusMessage("Ohai");
// enable server push
clientCodec_->getEgressSettings()->setSetting(SettingsId::ENABLE_PUSH, 1);
clientCodec_->generateSettings(requests_);
// generateHeader() will create a session and a transaction
auto assocStreamId = HTTPCodec::StreamID(1);
clientCodec_->generateHeader(requests_, assocStreamId, getGetRequest(),
false, nullptr);
auto handler = addSimpleStrictHandler();
StrictMock<MockHTTPPushHandler> pushHandler;
InSequence handlerSequence;
handler->expectHeaders([&] {
// Generate response for the associated stream
this->transport_->pauseWrites();
handler->txn_->sendHeaders(res);
handler->txn_->sendBody(makeBuf(100));
handler->txn_->pauseIngress();
auto* pushTxn = handler->txn_->newPushedTransaction(&pushHandler);
ASSERT_NE(pushTxn, nullptr);
// Generate a push request (PUSH_PROMISE)
pushTxn->sendHeaders(req);
});
EXPECT_CALL(pushHandler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
pushHandler.txn_ = txn; }));
EXPECT_CALL(pushHandler, onError(_));
EXPECT_CALL(pushHandler, detachTransaction());
handler->expectError();
handler->expectDetachTransaction();
transport_->addReadEvent(requests_, milliseconds(0));
// Cancels everything
clientCodec_->generateRstStream(requests_, assocStreamId, ErrorCode::CANCEL);
transport_->addReadEvent(requests_, milliseconds(10));
transport_->startReadEvents();
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
parseOutput(*clientCodec_);
expectDetachSession();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityWeightsTinyRatio) {
// Create a transaction with egress and a ratio small enough that
// ratio*4096 < 1.
//
// root
// / \ level 1
// 256 1 (no egress)
// / \ level 2
// 256 1 <-- has ratio (1/257)^2
InSequence enforceOrder;
auto req1 = getGetRequest();
auto req2 = getGetRequest();
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 255});
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 0});
sendRequest(req1);
auto id2 = sendRequest(req2);
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{id2, false, 255});
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{id2, false, 0});
sendRequest(req1);
sendRequest(req2);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 4 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM();
auto handler3 = addSimpleStrictHandler();
handler3->expectHeaders();
handler3->expectEOM([&] {
handler3->sendReplyWithBody(200, 15);
});
auto handler4 = addSimpleStrictHandler();
handler4->expectHeaders();
handler4->expectEOM([&] {
handler4->sendReplyWithBody(200, 1);
});
handler1->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler1->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler1->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// id1 had no egress when id2 was running, so id1 was contending only with
// id3 and id4. Average number of contentions for id1 is 3
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 3);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 3);
// this is a first level transaction, depth == 1
EXPECT_EQ(summary.depth_.byTransactionBytes_, 1);
EXPECT_EQ(summary.depth_.bySessionBytes_, 1);
// the expected relative weight is 256/257 ~= 0.9961
EXPECT_GT(summary.expected_weight_, 0.996);
EXPECT_LT(summary.expected_weight_, 0.9962);
// the measured relative weight is 4096/(4096+15) ~= 0.99635
// This value is higher than the expected relative weight of 0.9961.
// Due to the arithmetical rounding to the lowest integer, the measured
// relative weight tends to be higher for transactions with high relative
// weights and lower for transactions with the low relative weights.
EXPECT_GT(summary.measured_weight_, 0.9963);
EXPECT_LT(summary.measured_weight_, 0.9964);
});
handler3->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler3->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler3->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// Similarly, id3 was contenting with id1 and id4
// Average number of contentions for id3 is 3
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 3);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 3);
// this is a second level transaction where parent has
// no egress, depth == 2
EXPECT_EQ(summary.depth_.byTransactionBytes_, 2);
EXPECT_EQ(summary.depth_.bySessionBytes_, 2);
// the expected relative weight should be
// 1/257 * 256/257 ~= 0.00388. However, in the calculation of the
// allowed bytes to send we rounding to the lowest positive integer.
// Therefore, the measured relative weight tends to be less than
// it should be. In this example, the allowed bytes sent is
// 4096 * 0.00388 ~= 15.89, which is rounded to 15. Hence the measured
// relative weight is 15/(4096+15) ~= 0.00365
EXPECT_GT(summary.expected_weight_, 0.00388);
EXPECT_LT(summary.expected_weight_, 0.0039);
EXPECT_GT(summary.measured_weight_, 0.00364);
EXPECT_LT(summary.measured_weight_, 0.00366);
});
handler4->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler4->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler4->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// This is the priority-based blocking situation. id4 was blocked by
// higher priority transactions id1 and id3. Only when id1 and id3
// finished, id4 had a chance to transfer its data.
// Average contention number weighted by transaction bytes is 1, which
// means that when id4 had a chance to transfer bytes it did not contend
// with any other transactions.
// id4 was waiting for id1 and id3 during transfer of 4256 bytes (encoded)
// after which it tranferred 10 bytes (encoded) without contention.
// Therefore, the average number contentions weighted by session bytes is
// (4111*3 + 1*1)/(4111 + 1) = 12334/4112 ~= 2.999
// The difference in average contentions weighted by transaction and
// session bytes tells that id4 was mostly blocked by rather than blocking
// other transactions.
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 1);
EXPECT_GT(summary.contentions_.bySessionBytes_, 2.99);
EXPECT_LT(summary.contentions_.bySessionBytes_, 3.00);
// this is a second level transaction where parent has
// no egress, depth == 2
EXPECT_EQ(summary.depth_.byTransactionBytes_, 2);
EXPECT_EQ(summary.depth_.bySessionBytes_, 2);
// the expected relative weight should be
// 1/257 * 1/257 ~= 0.000015.
// Because no bytes of this transaction were sent during the previous
// egress, the expected relative weight was calculated as:
// (0*4111 + 1*1)/(4111 + 1) ~= 0.000243
EXPECT_GT(summary.expected_weight_, 0.000243);
EXPECT_LT(summary.expected_weight_, 0.000244);
// The measured weight is (0+1)/(4111+1) ~= 0.000243
// The difference between the theoretical value of 0.000015 and the
// measured one is not because of the arithmetical rounding, but because
// all other transactions are completed and the relative waight for the
// only survived transaction was elevated to 1.0
EXPECT_GT(summary.measured_weight_, 0.000243);
EXPECT_LT(summary.measured_weight_, 0.000244);
handler2->txn_->sendAbort();
});
handler2->expectDetachTransaction();
flushRequestsAndLoop();
httpSession_->closeWhenIdle();
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityDependentTransactions) {
// Create a dependent transaction to test the priority blocked by dependency.
// ratio*4096 < 1.
//
// root
// \ level 1
// 16
// \ level 2
// 16
InSequence enforceOrder;
auto req1 = getGetRequest();
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 15});
auto id1 = sendRequest(req1);
auto req2 = getGetRequest();
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{id1, false, 15});
sendRequest(req2);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 1024);
});
handler1->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler1->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler1->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// id1 is contending with id2 during the entire transfer.
// Average number of contentions for id1 is 2 in both cases.
// The same number of average contentions weighted by both transaction
// and session bytes tells that id1 was not blocked by any other
// transaction during the entire transfer.
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 2);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 2);
// this is a first level transaction, depth == 1
EXPECT_EQ(summary.depth_.byTransactionBytes_, 1);
EXPECT_EQ(summary.depth_.bySessionBytes_, 1);
// dependent transaction is blocked, the parent is egressing on 100%
EXPECT_EQ(summary.expected_weight_, 1);
EXPECT_EQ(summary.measured_weight_, 1);
});
handler2->expectDetachTransaction([&] {
HTTPTransaction::PrioritySampleSummary summary;
EXPECT_EQ(handler2->txn_->getPrioritySampleSummary(summary), true);
EXPECT_EQ(handler2->txn_->getTransport().getHTTP2PrioritiesEnabled(),
true);
// This is the dependency-based blocking. id2 is blocked by id1.
// When id2 had a chance to transfer bytes, it was no longer contended
// with any other transaction. Hence the average contention weighted by
// transaction bytes is 1.
// The average number of contentions weighted by the session bytes is
// computed as (1024*2 + 1024*1)/(1024 + 1024) = 3072/2048 = 1.5
EXPECT_EQ(summary.contentions_.byTransactionBytes_, 1);
EXPECT_EQ(summary.contentions_.bySessionBytes_, 1.5);
// The transaction transferred bytes only when its parent transaction
// completed. At that time its level decreased to 1. The average depth
// weighted by session bytes is (2*1024 + 1*1024)/(2048) = 1.5.
EXPECT_EQ(summary.depth_.byTransactionBytes_, 1);
EXPECT_EQ(summary.depth_.bySessionBytes_, 1.5);
// this dependent transaction was bloted, so it was egressiong only 1/2
// of the session bytes.
EXPECT_EQ(summary.expected_weight_, 0.5);
EXPECT_EQ(summary.measured_weight_, 0.5);
handler2->txn_->sendAbort();
});
flushRequestsAndLoop();
httpSession_->closeWhenIdle();
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestDisablePriorities) {
// turn off HTTP2 priorities
httpSession_->setHTTP2PrioritiesEnabled(false);
InSequence enforceOrder;
HTTPMessage req1 = getGetRequest();
req1.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 0});
sendRequest(req1);
HTTPMessage req2 = getGetRequest();
req2.setHTTP2Priority(HTTPMessage::HTTPPriority{0, false, 255});
sendRequest(req2);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 4 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 4 * 1024);
});
// expecting handler 1 to finish first irrespective of
// request 2 having higher weight
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoop();
httpSession_->closeWhenIdle();
expectDetachSession();
eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityWeights) {
// virtual priority node with pri=4
auto priGroupID = clientCodec_->createStream();
clientCodec_->generatePriority(
requests_, priGroupID, HTTPMessage::HTTPPriority(0, false, 3));
// Both txn's are at equal pri=16
auto id1 = sendRequest();
auto id2 = sendRequest();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendHeaders(200, 12 * 1024);
handler1->txn_->sendBody(makeBuf(4 * 1024));
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendHeaders(200, 12 * 1024);
handler2->txn_->sendBody(makeBuf(4 * 1024));
});
// twice- once to send and once to receive
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onSettings(_));
EXPECT_CALL(callbacks_, onMessageBegin(id1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id1, _));
EXPECT_CALL(callbacks_, onMessageBegin(id2, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id2, _));
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
parseOutput(*clientCodec_);
// update handler2 to be in the pri-group (which has lower weight)
clientCodec_->generatePriority(
requests_, id2, HTTPMessage::HTTPPriority(priGroupID, false, 15));
eventBase_.runInLoop([&] {
handler1->txn_->sendBody(makeBuf(4 * 1024));
handler2->txn_->sendBody(makeBuf(4 * 1024));
});
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(1 * 1024))
.WillOnce(ExpectBodyLen(3 * 1024));
parseOutput(*clientCodec_);
// update vnode weight to match txn1 weight
clientCodec_->generatePriority(requests_, priGroupID,
HTTPMessage::HTTPPriority(0, false, 15));
eventBase_.runInLoop([&] {
handler1->txn_->sendBody(makeBuf(4 * 1024));
handler1->txn_->sendEOM();
handler2->txn_->sendBody(makeBuf(4 * 1024));
handler2->txn_->sendEOM();
});
handler1->expectDetachTransaction();
handler2->expectDetachTransaction();
flushRequestsAndLoopN(2);
// expect 32/32
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onMessageComplete(id1, _));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onMessageComplete(id2, _));
parseOutput(*clientCodec_);
httpSession_->closeWhenIdle();
expectDetachSession();
this->eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestPriorityWeightsTinyWindow) {
httpSession_->setWriteBufferLimit(2 * 65536);
InSequence enforceOrder;
auto id1 = sendRequest();
auto id2 = sendRequest();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 32 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 32 * 1024);
});
handler1->expectDetachTransaction();
// twice- once to send and once to receive
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onSettings(_));
EXPECT_CALL(callbacks_, onMessageBegin(id1, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id1, _));
EXPECT_CALL(callbacks_, onMessageBegin(id2, _));
EXPECT_CALL(callbacks_, onHeadersComplete(id2, _));
for (auto i = 0; i < 7; i++) {
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024));
}
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(4 * 1024 - 1));
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(4 * 1024 - 1));
EXPECT_CALL(callbacks_, onBody(id1, _, _))
.WillOnce(ExpectBodyLen(1));
EXPECT_CALL(callbacks_, onMessageComplete(id1, _));
parseOutput(*clientCodec_);
// open the window
clientCodec_->generateWindowUpdate(requests_, 0, 100);
handler2->expectDetachTransaction();
flushRequestsAndLoopN(2);
EXPECT_CALL(callbacks_, onBody(id2, _, _))
.WillOnce(ExpectBodyLen(1));
EXPECT_CALL(callbacks_, onMessageComplete(id2, _));
parseOutput(*clientCodec_);
httpSession_->closeWhenIdle();
expectDetachSession();
this->eventBase_.loop();
}
TEST_F(HTTP2DownstreamSessionTest, TestShortContentLength) {
auto req = getPostRequest(10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectError([&handler1] (const HTTPException& ex) {
EXPECT_EQ(ex.getProxygenError(), kErrorParseBody);
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
/**
* If handler chooses to untie itself with transaction during onError,
* detachTransaction shouldn't be expected
*/
TEST_F(HTTP2DownstreamSessionTest, TestBadContentLengthUntieHandler) {
auto req = getPostRequest(10);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(
requests_,
streamID,
makeBuf(20),
HTTPCodec::NoPadding,
true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectError([&] (const HTTPException&) {
if (handler1->txn_) {
handler1->txn_->setHandler(nullptr);
}
handler1->txn_ = nullptr;
});
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestLongContentLength) {
auto req = getPostRequest(30);
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectBody();
handler1->expectError([&handler1] (const HTTPException& ex) {
EXPECT_EQ(ex.getProxygenError(), kErrorParseBody);
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestMalformedContentLength) {
auto req = getPostRequest();
req.getHeaders().set(HTTP_HEADER_CONTENT_LENGTH, "malformed");
auto streamID = sendRequest(req, false);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, true);
auto handler1 = addSimpleStrictHandler();
InSequence enforceOrder;
handler1->expectHeaders();
handler1->expectBody();
handler1->expectEOM([&handler1] {
handler1->sendReplyWithBody(200, 100);
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestHeadContentLength) {
InSequence enforceOrder;
auto req = getGetRequest();
req.setMethod(HTTPMethod::HEAD);
sendRequest(req);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendHeaders(200, 100);
// no body for head
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, Test304ContentLength) {
InSequence enforceOrder;
auto req = getGetRequest();
req.setMethod(HTTPMethod::HEAD);
sendRequest(req);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&handler1] {
handler1->sendHeaders(304, 100);
handler1->txn_->sendEOM();
});
handler1->expectDetachTransaction();
flushRequestsAndLoop();
gracefulShutdown();
}
// chunked with wrong content-length
TEST_F(HTTPDownstreamSessionTest, HttpShortContentLength) {
InSequence enforceOrder;
auto req = getPostRequest(10);
req.setIsChunked(true);
req.getHeaders().add(HTTP_HEADER_TRANSFER_ENCODING, "chunked");
auto streamID = sendRequest(req, false);
clientCodec_->generateChunkHeader(requests_, streamID, 20);
clientCodec_->generateBody(requests_, streamID, makeBuf(20),
HTTPCodec::NoPadding, false);
clientCodec_->generateChunkTerminator(requests_, streamID);
clientCodec_->generateEOM(requests_, streamID);
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
EXPECT_CALL(*handler1, onChunkHeader(20));
handler1->expectError([&handler1] (const HTTPException& ex) {
EXPECT_EQ(ex.getProxygenError(), kErrorParseBody);
handler1->txn_->sendAbort();
});
handler1->expectDetachTransaction();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTP2DownstreamSessionTest, TestSessionStallByFlowControl) {
NiceMock<MockHTTPSessionStats> stats;
// By default the send and receive windows are 64K each.
// If we use only a single transaction, that transaction
// will be paused on reaching 64K. Therefore, to pause the session,
// it is used 2 transactions each sending 32K.
// Make write buffer limit exceding 64K, for example 128K
httpSession_->setWriteBufferLimit(128 * 1024);
httpSession_->setSessionStats(&stats);
InSequence enforceOrder;
sendRequest();
sendRequest();
auto handler1 = addSimpleStrictHandler();
handler1->expectHeaders();
handler1->expectEOM([&] {
handler1->sendReplyWithBody(200, 32 * 1024);
});
auto handler2 = addSimpleStrictHandler();
handler2->expectHeaders();
handler2->expectEOM([&] {
handler2->sendReplyWithBody(200, 32 * 1024);
});
EXPECT_CALL(stats, recordSessionStalled()).Times(1);
handler1->expectDetachTransaction();
// twice- once to send and once to receive
flushRequestsAndLoopN(2);
// open the window
clientCodec_->generateWindowUpdate(requests_, 0, 100);
handler2->expectDetachTransaction();
flushRequestsAndLoopN(2);
httpSession_->closeWhenIdle();
expectDetachSession();
flushRequestsAndLoop();
}
TEST_F(HTTP2DownstreamSessionTest, TestTransactionStallByFlowControl) {
StrictMock<MockHTTPSessionStats> stats;
httpSession_->setSessionStats(&stats);
// Set the client side stream level flow control wind to 500 bytes,
// and try to send 1000 bytes through it.
// Then the flow control kicks in and stalls the transaction.
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec_->generateSettings(requests_);
auto streamID = sendRequest();
EXPECT_CALL(stats, recordTransactionOpened());
InSequence handlerSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&] {
handler->sendReplyWithBody(200, 1000);
});
EXPECT_CALL(stats, recordTransactionStalled());
handler->expectEgressPaused();
handler->expectError([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("ingress timeout, streamID=", streamID),
std::string(ex.what()));
handler->terminate();
});
handler->expectDetachTransaction();
EXPECT_CALL(stats, recordTransactionClosed());
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestTransactionNotStallByFlowControl) {
StrictMock<MockHTTPSessionStats> stats;
httpSession_->setSessionStats(&stats);
clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec_->generateSettings(requests_);
sendRequest();
EXPECT_CALL(stats, recordTransactionOpened());
InSequence handlerSequence;
auto handler = addSimpleStrictHandler();
handler->expectHeaders();
handler->expectEOM([&] {
handler->sendReplyWithBody(200, 500);
});
// The egtress paused is notified due to existing logics,
// but egress transaction should not be counted as stalled by flow control,
// because there is nore more bytes to send
handler->expectEgressPaused();
handler->expectDetachTransaction();
EXPECT_CALL(stats, recordTransactionClosed());
flushRequestsAndLoop();
gracefulShutdown();
}
TEST_F(HTTP2DownstreamSessionTest, TestSetEgressSettings) {
SettingsList settings = {{ SettingsId::HEADER_TABLE_SIZE, 5555 },
{ SettingsId::MAX_FRAME_SIZE, 16384 },
{ SettingsId::ENABLE_PUSH, 1 }};
const HTTPSettings* codecSettings = rawCodec_->getEgressSettings();
for (const auto& setting: settings) {
const HTTPSetting* currSetting = codecSettings->getSetting(setting.id);
if (currSetting) {
EXPECT_EQ(setting.value, currSetting->value);
}
}
flushRequestsAndLoop();
gracefulShutdown();
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_600_2 |
crossvul-cpp_data_good_592_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/server/upload.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/request-event-handler.h"
#include "hphp/runtime/base/request-local.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/runtime/ext/apc/ext_apc.h"
#include "hphp/util/logger.h"
#include "hphp/util/text-util.h"
#include <folly/FileUtil.h>
using std::set;
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
static void destroy_uploaded_files();
struct Rfc1867Data final : RequestEventHandler {
std::set<std::string> rfc1867ProtectedVariables;
std::set<std::string> rfc1867UploadedFiles;
apc_rfc1867_data rfc1867ApcData;
int (*rfc1867Callback)(apc_rfc1867_data *rfc1867ApcData,
unsigned int event, void *event_data, void **extra);
void requestInit() override {
if (RuntimeOption::EnableUploadProgress) {
rfc1867Callback = apc_rfc1867_progress;
} else {
rfc1867Callback = nullptr;
}
}
void requestShutdown() override {
if (!rfc1867UploadedFiles.empty()) destroy_uploaded_files();
}
};
IMPLEMENT_STATIC_REQUEST_LOCAL(Rfc1867Data, s_rfc1867_data);
/*
* This product includes software developed by the Apache Group
* for use in the Apache HTTP server project (http://www.apache.org/).
*
*/
static void safe_php_register_variable(char *var, const Variant& val,
Array& track_vars_array,
bool override_protection);
#define FAILURE -1
/* The longest property name we use in an uploaded file array */
#define MAX_SIZE_OF_INDEX sizeof("[tmp_name]")
/* The longest anonymous name */
#define MAX_SIZE_ANONNAME 33
/* Errors */
#define UPLOAD_ERROR_OK 0 /* File upload successful */
#define UPLOAD_ERROR_A 1 /* Uploaded file exceeded upload_max_filesize */
#define UPLOAD_ERROR_B 2 /* Uploaded file exceeded MAX_FILE_SIZE */
#define UPLOAD_ERROR_C 3 /* Partially uploaded */
#define UPLOAD_ERROR_D 4 /* No file uploaded */
#define UPLOAD_ERROR_E 6 /* Missing /tmp or similar directory */
#define UPLOAD_ERROR_F 7 /* Failed to write file to disk */
#define UPLOAD_ERROR_X 8 /* File upload stopped by extension */
static void normalize_protected_variable(char *varname) {
char *s=varname, *index=nullptr, *indexend=nullptr, *p;
/* overjump leading space */
while (*s == ' ') {
s++;
}
/* and remove it */
if (s != varname) {
memmove(varname, s, strlen(s)+1);
}
for (p=varname; *p && *p != '['; p++) {
switch(*p) {
case ' ':
case '.':
*p='_';
break;
}
}
/* find index */
index = strchr(varname, '[');
if (index) {
index++;
s=index;
} else {
return;
}
/* done? */
while (index) {
while (*index == ' ' || *index == '\r' ||
*index == '\n' || *index=='\t') {
index++;
}
indexend = strchr(index, ']');
indexend = indexend ? indexend + 1 : index + strlen(index);
if (s != index) {
memmove(s, index, strlen(index)+1);
s += indexend-index;
} else {
s = indexend;
}
if (*s == '[') {
s++;
index = s;
} else {
index = nullptr;
}
}
*s++='\0';
}
static void add_protected_variable(char *varname) {
normalize_protected_variable(varname);
s_rfc1867_data->rfc1867ProtectedVariables.insert(varname);
}
static bool is_protected_variable(char *varname) {
normalize_protected_variable(varname);
auto iter = s_rfc1867_data->rfc1867ProtectedVariables.find(varname);
return iter != s_rfc1867_data->rfc1867ProtectedVariables.end();
}
static void safe_php_register_variable(char *var, const Variant& val,
Array& track_vars_array,
bool override_protection) {
if (override_protection || !is_protected_variable(var)) {
register_variable(track_vars_array, var, val);
}
}
bool is_uploaded_file(const std::string filename) {
std::set<std::string> &rfc1867UploadedFiles =
s_rfc1867_data->rfc1867UploadedFiles;
return rfc1867UploadedFiles.find(filename) != rfc1867UploadedFiles.end();
}
const std::set<std::string> &get_uploaded_files() {
return s_rfc1867_data->rfc1867UploadedFiles;
}
static void destroy_uploaded_files() {
std::set<std::string> &rfc1867UploadedFiles =
s_rfc1867_data->rfc1867UploadedFiles;
for (auto iter = rfc1867UploadedFiles.begin();
iter != rfc1867UploadedFiles.end(); iter++) {
unlink(iter->c_str());
}
rfc1867UploadedFiles.clear();
}
/*
* Following code is based on apache_multipart_buffer.c from
* libapreq-0.33 package.
*
*/
constexpr size_t FILLUNIT = 1024 * 5;
namespace {
struct multipart_buffer {
Transport *transport;
/* read buffer */
char *buffer;
char *buf_begin;
size_t bufsize;
int64_t bytes_in_buffer; // signed to catch underflow errors
/* boundary info */
char *boundary;
char *boundary_next;
int boundary_next_len;
/* post data */
const char *post_data;
uint64_t post_size;
uint64_t throw_size; // sum of all previously read chunks
char *cursor;
uint64_t read_post_bytes;
};
}
using header_list = std::list<std::pair<std::string, std::string>>;
static uint32_t read_post(multipart_buffer *self, char *buf,
uint32_t bytes_to_read) {
always_assert(bytes_to_read > 0);
always_assert(self->post_data);
always_assert(self->cursor >= self->post_data);
int64_t bytes_remaining = (self->post_size - self->throw_size) -
(self->cursor - self->post_data);
always_assert(bytes_remaining >= 0);
if (bytes_to_read <= bytes_remaining) {
memcpy(buf, self->cursor, bytes_to_read);
self->cursor += bytes_to_read;
return bytes_to_read;
}
uint32_t bytes_read = bytes_remaining;
memcpy(buf, self->cursor, bytes_remaining);
bytes_to_read -= bytes_remaining;
self->cursor += bytes_remaining;
always_assert(self->cursor == (char *)self->post_data +
(self->post_size - self->throw_size));
while (bytes_to_read > 0 && self->transport->hasMorePostData()) {
size_t extra_byte_read = 0;
const void *extra = self->transport->getMorePostData(extra_byte_read);
if (extra_byte_read == 0) break;
if (RuntimeOption::AlwaysPopulateRawPostData) {
// Possible overflow in buffer_append if post_size + extra_byte_read >=
// MAX INT
self->post_data = (const char *)buffer_append(
self->post_data, self->post_size, extra, extra_byte_read);
self->cursor = (char*)self->post_data + self->post_size;
} else {
self->post_data = (const char *)extra;
self->throw_size = self->post_size;
self->cursor = (char*)self->post_data;
}
self->post_size += extra_byte_read;
if (bytes_to_read <= extra_byte_read) {
memcpy(buf + bytes_read, self->cursor, bytes_to_read);
self->cursor += bytes_to_read;
return bytes_read + bytes_to_read;
}
memcpy(buf + bytes_read, self->cursor, extra_byte_read);
bytes_to_read -= extra_byte_read;
bytes_read += extra_byte_read;
self->cursor += extra_byte_read;
}
return bytes_read;
}
/*
fill up the buffer with client data.
returns number of bytes added to buffer.
*/
static uint32_t fill_buffer(multipart_buffer *self) {
uint32_t bytes_to_read, total_read = 0, actual_read = 0;
/* shift the existing data if necessary */
if (self->bytes_in_buffer > 0 && self->buf_begin != self->buffer) {
memmove(self->buffer, self->buf_begin, self->bytes_in_buffer);
}
self->buf_begin = self->buffer;
/* calculate the free space in the buffer */
bytes_to_read = self->bufsize - self->bytes_in_buffer;
always_assert(self->bufsize > 0);
always_assert(self->bytes_in_buffer >= 0);
/* read the required number of bytes */
while (bytes_to_read > 0) {
char *buf = self->buffer + self->bytes_in_buffer;
actual_read = read_post(self, buf, bytes_to_read);
/* update the buffer length */
if (actual_read > 0) {
always_assert(bytes_to_read >= actual_read);
self->bytes_in_buffer += actual_read;
self->read_post_bytes += actual_read;
total_read += actual_read;
bytes_to_read -= actual_read;
} else {
break;
}
}
return total_read;
}
/* eof if we are out of bytes, or if we hit the final boundary */
static int multipart_buffer_eof(multipart_buffer *self) {
if ( (self->bytes_in_buffer == 0 && fill_buffer(self) < 1) ) {
return 1;
} else {
return 0;
}
}
/* create new multipart_buffer structure */
static multipart_buffer *multipart_buffer_new(Transport *transport,
const char *data, size_t size,
std::string boundary) {
multipart_buffer *self =
(multipart_buffer *)calloc(1, sizeof(multipart_buffer));
self->transport = transport;
auto minsize = boundary.length() + 6;
if (minsize < FILLUNIT) minsize = FILLUNIT;
self->buffer = (char *) calloc(1, minsize + 1);
self->bufsize = minsize;
vspprintf(&self->boundary, 0, "--%s", boundary.c_str());
self->boundary_next_len =
vspprintf(&self->boundary_next, 0, "\n--%s", boundary.c_str());
self->buf_begin = self->buffer;
self->bytes_in_buffer = 0;
self->post_data = data;
self->cursor = (char*)self->post_data;
self->post_size = size;
self->throw_size = 0;
return self;
}
/*
gets the next CRLF terminated line from the input buffer.
if it doesn't find a CRLF, and the buffer isn't completely full, returns
NULL; otherwise, returns the beginning of the null-terminated line,
minus the CRLF.
note that we really just look for LF terminated lines. this works
around a bug in internet explorer for the macintosh which sends mime
boundaries that are only LF terminated when you use an image submit
button in a multipart/form-data form.
*/
static char *next_line(multipart_buffer *self) {
/* look for LF in the data */
char* line = self->buf_begin;
char* ptr = (char*)memchr(self->buf_begin, '\n', self->bytes_in_buffer);
if (ptr) { /* LF found */
/* terminate the string, remove CRLF */
if ((ptr - line) > 0 && *(ptr-1) == '\r') {
*(ptr-1) = 0;
} else {
*ptr = 0;
}
/* bump the pointer */
self->buf_begin = ptr + 1;
self->bytes_in_buffer -= (self->buf_begin - line);
} else { /* no LF found */
/* buffer isn't completely full, fail */
if (self->bytes_in_buffer < self->bufsize) {
return nullptr;
}
/* return entire buffer as a partial line */
line[self->bufsize] = 0;
self->buf_begin = ptr;
self->bytes_in_buffer = 0;
}
return line;
}
/* returns the next CRLF terminated line from the client */
static char *get_line(multipart_buffer *self) {
char* ptr = next_line(self);
if (!ptr) {
fill_buffer(self);
ptr = next_line(self);
}
return ptr;
}
/* finds a boundary */
static int find_boundary(multipart_buffer *self, char *boundary) {
char *line;
/* loop thru lines */
while( (line = get_line(self)) )
{
/* finished if we found the boundary */
if (!strcmp(line, boundary)) {
return 1;
}
}
/* didn't find the boundary */
return 0;
}
/* parse headers */
static int multipart_buffer_headers(multipart_buffer *self,
header_list &header) {
char *line;
std::string key;
std::string buf_value;
std::pair<std::string, std::string> entry;
/* didn't find boundary, abort */
if (!find_boundary(self, self->boundary)) {
return 0;
}
/* get lines of text, or CRLF_CRLF */
while( (line = get_line(self)) && strlen(line) > 0 )
{
/* add header to table */
char *value = nullptr;
/* space in the beginning means same header */
if (!isspace(line[0])) {
value = strchr(line, ':');
}
if (value) {
if (!buf_value.empty() && !key.empty() ) {
entry = std::make_pair(key, buf_value);
header.push_back(entry);
buf_value.erase();
key.erase();
}
*value = '\0';
do { value++; } while(isspace(*value));
key.assign(line);
buf_value.append(value);
} else if (!buf_value.empty() ) {
/* If no ':' on the line, add to previous line */
buf_value.append(line);
} else {
continue;
}
}
if (!buf_value.empty() && !key.empty()) {
entry = std::make_pair(key, buf_value);
header.push_back(entry);
}
return 1;
}
static char *php_mime_get_hdr_value(header_list &header, char *key) {
if (key == nullptr) return nullptr;
for (header_list::iterator iter = header.begin();
iter != header.end(); iter++) {
if (!strcasecmp(iter->first.c_str(), key)) {
return (char *)iter->second.c_str();
}
}
return nullptr;
}
static char *php_ap_getword(char **line, char stop) {
char *pos = *line, quote;
char *res;
while (*pos && *pos != stop) {
if ((quote = *pos) == '"' || quote == '\'') {
++pos;
while (*pos && *pos != quote) {
if (*pos == '\\' && pos[1] && pos[1] == quote) {
pos += 2;
} else {
++pos;
}
}
if (*pos) {
++pos;
}
} else ++pos;
}
if (*pos == '\0') {
res = strdup(*line);
*line += strlen(*line);
return res;
}
res = (char*)malloc(pos - *line + 1);
memcpy(res, *line, pos - *line);
res[pos - *line] = 0;
while (*pos == stop) {
++pos;
}
*line = pos;
return res;
}
static char *substring_conf(char *start, int len, char quote) {
char *result = (char *)malloc(len + 2);
char *resp = result;
int i;
for (i = 0; i < len; ++i) {
if (start[i] == '\\' &&
(start[i + 1] == '\\' || (quote && start[i + 1] == quote))) {
*resp++ = start[++i];
} else {
*resp++ = start[i];
}
}
*resp++ = '\0';
return result;
}
static char *php_ap_getword_conf(char **line) {
char *str = *line, *strend, *res, quote;
while (*str && isspace(*str)) {
++str;
}
if (!*str) {
*line = str;
return strdup("");
}
if ((quote = *str) == '"' || quote == '\'') {
strend = str + 1;
look_for_quote:
while (*strend && *strend != quote) {
if (*strend == '\\' && strend[1] && strend[1] == quote) {
strend += 2;
} else {
++strend;
}
}
if (*strend && *strend == quote) {
char p = *(strend + 1);
if (p != '\r' && p != '\n' && p != '\0') {
strend++;
goto look_for_quote;
}
}
res = substring_conf(str + 1, strend - str - 1, quote);
if (*strend == quote) {
++strend;
}
} else {
strend = str;
while (*strend && !isspace(*strend)) {
++strend;
}
res = substring_conf(str, strend - str, 0);
}
while (*strend && isspace(*strend)) {
++strend;
}
*line = strend;
return res;
}
/*
search for a string in a fixed-length byte string.
if partial is true, partial matches are allowed at the end of the buffer.
returns NULL if not found, or a pointer to the start of the first match.
*/
static char *php_ap_memstr(char *haystack, int haystacklen, char *needle,
int needlen, int partial) {
int len = haystacklen;
char *ptr = haystack;
/* iterate through first character matches */
while( (ptr = (char *)memchr(ptr, needle[0], len)) ) {
/* calculate length after match */
len = haystacklen - (ptr - (char *)haystack);
/* done if matches up to capacity of buffer */
if (memcmp(needle, ptr, needlen < len ? needlen : len) == 0 &&
(partial || len >= needlen)) {
break;
}
/* next character */
ptr++; len--;
}
return ptr;
}
/* read until a boundary condition */
static int multipart_buffer_read(multipart_buffer *self, char *buf,
int bytes, int *end) {
int len, max;
char *bound;
/* fill buffer if needed */
if (bytes > self->bytes_in_buffer) {
fill_buffer(self);
}
/* look for a potential boundary match, only read data up to that point */
if ((bound =
php_ap_memstr(self->buf_begin, self->bytes_in_buffer,
self->boundary_next, self->boundary_next_len, 1))) {
max = bound - self->buf_begin;
if (end &&
php_ap_memstr(self->buf_begin, self->bytes_in_buffer,
self->boundary_next, self->boundary_next_len, 0)) {
*end = 1;
}
} else {
max = self->bytes_in_buffer;
}
/* maximum number of bytes we are reading */
len = max < bytes-1 ? max : bytes-1;
/* if we read any data... */
if (len > 0) {
/* copy the data */
memcpy(buf, self->buf_begin, len);
buf[len] = 0;
if (bound && len > 0 && buf[len-1] == '\r') {
buf[--len] = 0;
}
/* update the buffer */
self->bytes_in_buffer -= len;
self->buf_begin += len;
}
return len;
}
/*
XXX: this is horrible memory-usage-wise, but we only expect
to do this on small pieces of form data.
*/
static char *multipart_buffer_read_body(multipart_buffer *self,
unsigned int *len) {
char buf[FILLUNIT], *out=nullptr;
int total_bytes=0, read_bytes=0;
while((read_bytes = multipart_buffer_read(self, buf, sizeof(buf), nullptr))) {
out = (char *)realloc(out, total_bytes + read_bytes + 1);
memcpy(out + total_bytes, buf, read_bytes);
total_bytes += read_bytes;
}
if (out) out[total_bytes] = '\0';
*len = total_bytes;
return out;
}
/*
* The combined READER/HANDLER
*
*/
void rfc1867PostHandler(Transport* transport,
Array& post,
Array& files,
size_t content_length,
const void*& data, size_t& size,
const std::string boundary) {
char *s=nullptr, *start_arr=nullptr;
std::string array_index, abuf;
char *lbuf=nullptr;
int total_bytes=0, cancel_upload=0, is_arr_upload=0, array_len=0;
int max_file_size=0, skip_upload=0, anonindex=0;
std::set<std::string> &uploaded_files = s_rfc1867_data->rfc1867UploadedFiles;
multipart_buffer *mbuff;
int fd=-1;
void *event_extra_data = nullptr;
unsigned int llen = 0;
int upload_count = RuntimeOption::MaxFileUploads;
/* Initialize the buffer */
if (!(mbuff = multipart_buffer_new(transport,
(const char *)data, size, boundary))) {
Logger::Warning("Unable to initialize the input buffer");
return;
}
/* Initialize $_FILES[] */
s_rfc1867_data->rfc1867ProtectedVariables.clear();
uploaded_files.clear();
int (*php_rfc1867_callback)(apc_rfc1867_data *rfc1867ApcData,
unsigned int event, void *event_data,
void **extra) = s_rfc1867_data->rfc1867Callback;
if (php_rfc1867_callback != nullptr) {
multipart_event_start event_start;
event_start.content_length = content_length;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_START, &event_start,
&event_extra_data) == FAILURE) {
goto fileupload_done;
}
}
while (!multipart_buffer_eof(mbuff)) {
std::string temp_filename;
char buff[FILLUNIT];
char *cd=nullptr,*param=nullptr,*filename=nullptr, *tmp=nullptr;
size_t blen=0, wlen=0;
off_t offset;
header_list header;
if (!multipart_buffer_headers(mbuff, header)) {
goto fileupload_done;
}
if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) {
char *pair=nullptr;
int end=0;
while (isspace(*cd)) {
++cd;
}
while (*cd && (pair = php_ap_getword(&cd, ';')))
{
char *key=nullptr, *word = pair;
while (isspace(*cd)) {
++cd;
}
if (strchr(pair, '=')) {
key = php_ap_getword(&pair, '=');
if (!strcasecmp(key, "name")) {
if (param) {
free(param);
}
param = php_ap_getword_conf(&pair);
} else if (!strcasecmp(key, "filename")) {
if (filename) {
free(filename);
}
filename = php_ap_getword_conf(&pair);
}
}
if (key) free(key);
free(word);
}
/* Normal form variable, safe to read all data into memory */
if (!filename && param) {
unsigned int value_len;
char *value = multipart_buffer_read_body(mbuff, &value_len);
unsigned int new_val_len; /* Dummy variable */
if (!value) {
value = strdup("");
}
new_val_len = value_len;
if (php_rfc1867_callback != nullptr) {
multipart_event_formdata event_formdata;
size_t newlength = new_val_len;
event_formdata.post_bytes_processed = mbuff->read_post_bytes;
event_formdata.name = param;
event_formdata.value = &value;
event_formdata.length = new_val_len;
event_formdata.newlength = &newlength;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FORMDATA, &event_formdata,
&event_extra_data) == FAILURE) {
free(param);
free(value);
continue;
}
new_val_len = newlength;
}
String val(value, new_val_len, CopyString);
safe_php_register_variable(param, val, post, 0);
if (!strcasecmp(param, "MAX_FILE_SIZE")) {
max_file_size = atol(value);
}
free(param);
free(value);
continue;
}
/* If file_uploads=off, skip the file part */
if (!RuntimeOption::EnableFileUploads) {
skip_upload = 1;
} else if (upload_count <= 0) {
Logger::Warning(
"Maximum number of allowable file uploads has been exceeded"
);
skip_upload = 1;
}
/* Return with an error if the posted data is garbled */
if (!param && !filename) {
Logger::Warning("File Upload Mime headers garbled");
goto fileupload_done;
}
if (!param) {
param = (char*)malloc(MAX_SIZE_ANONNAME);
snprintf(param, MAX_SIZE_ANONNAME, "%u", anonindex++);
}
/* New Rule: never repair potential malicious user input */
if (!skip_upload) {
tmp = param;
long c = 0;
while (*tmp) {
if (*tmp == '[') {
c++;
} else if (*tmp == ']') {
c--;
if (tmp[1] && tmp[1] != '[') {
skip_upload = 1;
break;
}
}
if (c < 0) {
skip_upload = 1;
break;
}
tmp++;
}
}
total_bytes = cancel_upload = 0;
if (!skip_upload) {
/* Handle file */
char path[PATH_MAX];
// open a temporary file
snprintf(path, sizeof(path), "%s/XXXXXX",
RuntimeOption::UploadTmpDir.c_str());
fd = mkstemp(path);
upload_count--;
if (fd == -1) {
Logger::Warning("Unable to open temporary file");
Logger::Warning("File upload error - unable to create a "
"temporary file");
cancel_upload = UPLOAD_ERROR_E;
}
temp_filename = path;
}
if (!skip_upload && php_rfc1867_callback != nullptr) {
multipart_event_file_start event_file_start;
event_file_start.post_bytes_processed = mbuff->read_post_bytes;
event_file_start.name = param;
event_file_start.filename = &filename;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FILE_START,
&event_file_start,
&event_extra_data) == FAILURE) {
if (!temp_filename.empty()) {
if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */
close(fd);
unlink(temp_filename.c_str());
}
}
temp_filename="";
free(param);
free(filename);
continue;
}
}
if (skip_upload) {
free(param);
free(filename);
continue;
}
if (strlen(filename) == 0) {
Logger::Verbose("No file uploaded");
cancel_upload = UPLOAD_ERROR_D;
}
offset = 0;
end = 0;
while (!cancel_upload &&
(blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end)))
{
if (php_rfc1867_callback != nullptr) {
multipart_event_file_data event_file_data;
event_file_data.post_bytes_processed = mbuff->read_post_bytes;
event_file_data.offset = offset;
event_file_data.data = buff;
event_file_data.length = blen;
event_file_data.newlength = &blen;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FILE_DATA,
&event_file_data,
&event_extra_data) == FAILURE) {
cancel_upload = UPLOAD_ERROR_X;
continue;
}
}
if (VirtualHost::GetUploadMaxFileSize() > 0 &&
total_bytes > VirtualHost::GetUploadMaxFileSize()) {
Logger::Verbose("upload_max_filesize of %" PRId64 " bytes exceeded "
"- file [%s=%s] not saved",
VirtualHost::GetUploadMaxFileSize(),
param, filename);
cancel_upload = UPLOAD_ERROR_A;
} else if (max_file_size && (total_bytes > max_file_size)) {
Logger::Verbose("MAX_FILE_SIZE of %d bytes exceeded - "
"file [%s=%s] not saved",
max_file_size, param, filename);
cancel_upload = UPLOAD_ERROR_B;
} else if (blen > 0) {
wlen = folly::writeFull(fd, buff, blen);
if (wlen < blen) {
Logger::Verbose("Only %zd bytes were written, expected to "
"write %zd", wlen, blen);
cancel_upload = UPLOAD_ERROR_F;
} else {
total_bytes += wlen;
}
offset += wlen;
}
}
if (fd!=-1) { /* may not be initialized if file could not be created */
close(fd);
}
if (!cancel_upload && !end) {
Logger::Verbose("Missing mime boundary at the end of the data for "
"file %s", strlen(filename) > 0 ? filename : "");
cancel_upload = UPLOAD_ERROR_C;
}
if (strlen(filename) > 0 && total_bytes == 0 && !cancel_upload) {
Logger::Verbose("Uploaded file size 0 - file [%s=%s] not saved",
param, filename);
cancel_upload = 5;
}
if (php_rfc1867_callback != nullptr) {
multipart_event_file_end event_file_end;
event_file_end.post_bytes_processed = mbuff->read_post_bytes;
event_file_end.temp_filename = temp_filename.c_str();
event_file_end.cancel_upload = cancel_upload;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FILE_END,
&event_file_end,
&event_extra_data) == FAILURE) {
cancel_upload = UPLOAD_ERROR_X;
}
}
if (cancel_upload && cancel_upload != UPLOAD_ERROR_C) {
if (!temp_filename.empty()) {
if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */
unlink(temp_filename.c_str());
}
}
temp_filename="";
} else {
s_rfc1867_data->rfc1867UploadedFiles.insert(temp_filename);
}
/* is_arr_upload is true when name of file upload field
* ends in [.*]
* start_arr is set to point to 1st [
*/
is_arr_upload = (start_arr = strchr(param,'[')) &&
(param[strlen(param)-1] == ']');
if (is_arr_upload) {
array_len = strlen(start_arr);
array_index = std::string(start_arr+1, array_len-2);
}
/* Add $foo_name */
if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) {
llen = strlen(param);
lbuf = (char *) realloc(lbuf, llen + MAX_SIZE_OF_INDEX + 1);
llen += MAX_SIZE_OF_INDEX + 1;
}
if (is_arr_upload) {
abuf = std::string(param, strlen(param)-array_len);
snprintf(lbuf, llen, "%s_name[%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s_name", param);
}
/* The \ check should technically be needed for win32 systems only
* where it is a valid path separator. However, IE in all it's wisdom
* always sends the full path of the file on the user's filesystem,
* which means that unless the user does basename() they get a bogus
* file name. Until IE's user base drops to nill or problem is fixed
* this code must remain enabled for all systems.
*/
s = strrchr(filename, '\\');
if ((tmp = strrchr(filename, '/')) > s) {
s = tmp;
}
/* Add $foo[name] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[name][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[name]", param);
}
if (s) {
String val(s+1, strlen(s+1), CopyString);
safe_php_register_variable(lbuf, val, files, 0);
} else {
String val(filename, strlen(filename), CopyString);
safe_php_register_variable(lbuf, val, files, 0);
}
free(filename);
s = nullptr;
/* Possible Content-Type: */
if ((cancel_upload && cancel_upload != UPLOAD_ERROR_C) ||
!(cd = php_mime_get_hdr_value(header, "Content-Type"))) {
cd = "";
} else {
/* fix for Opera 6.01 */
s = strchr(cd, ';');
if (s != nullptr) {
*s = '\0';
}
}
/* Add $foo[type] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[type][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[type]", param);
}
String val(cd, strlen(cd), CopyString);
safe_php_register_variable(lbuf, val, files, 0);
/* Restore Content-Type Header */
if (s != nullptr) {
*s = ';';
}
s = "";
/* Initialize variables */
add_protected_variable(param);
Variant tempFileName(temp_filename);
/* Add $foo[tmp_name] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[tmp_name][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[tmp_name]", param);
}
add_protected_variable(lbuf);
safe_php_register_variable(lbuf, tempFileName, files, 1);
Variant file_size, error_type;
error_type = cancel_upload;
/* Add $foo[error] */
if (cancel_upload) {
file_size = 0;
} else {
file_size = total_bytes;
}
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[error][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[error]", param);
}
safe_php_register_variable(lbuf, error_type, files, 0);
/* Add $foo[size] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[size][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[size]", param);
}
safe_php_register_variable(lbuf, file_size, files, 0);
free(param);
}
}
fileupload_done:
data = mbuff->post_data;
size = mbuff->post_size;
if (php_rfc1867_callback != nullptr) {
multipart_event_end event_end;
event_end.post_bytes_processed = mbuff->read_post_bytes;
php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_END, &event_end, &event_extra_data);
}
if (lbuf) free(lbuf);
s_rfc1867_data->rfc1867ProtectedVariables.clear();
if (mbuff->boundary_next) free(mbuff->boundary_next);
if (mbuff->boundary) free(mbuff->boundary);
if (mbuff->buffer) free(mbuff->buffer);
if (mbuff) free(mbuff);
}
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_592_0 |
crossvul-cpp_data_good_239_1 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/IRCSock.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Server.h>
#include <znc/Query.h>
#include <znc/ZNCDebug.h>
#include <time.h>
using std::set;
using std::vector;
using std::map;
#define IRCSOCKMODULECALL(macFUNC, macEXITER) \
NETWORKMODULECALL(macFUNC, m_pNetwork->GetUser(), m_pNetwork, nullptr, \
macEXITER)
// These are used in OnGeneralCTCP()
const time_t CIRCSock::m_uCTCPFloodTime = 5;
const unsigned int CIRCSock::m_uCTCPFloodCount = 5;
// It will be bad if user sets it to 0.00000000000001
// If you want no flood protection, set network's flood rate to -1
// TODO move this constant to CIRCNetwork?
static const double FLOOD_MINIMAL_RATE = 0.3;
class CIRCFloodTimer : public CCron {
CIRCSock* m_pSock;
public:
CIRCFloodTimer(CIRCSock* pSock) : m_pSock(pSock) {
StartMaxCycles(m_pSock->m_fFloodRate, 0);
}
CIRCFloodTimer(const CIRCFloodTimer&) = delete;
CIRCFloodTimer& operator=(const CIRCFloodTimer&) = delete;
void RunJob() override {
if (m_pSock->m_iSendsAllowed < m_pSock->m_uFloodBurst) {
m_pSock->m_iSendsAllowed++;
}
m_pSock->TrySend();
}
};
bool CIRCSock::IsFloodProtected(double fRate) {
return fRate > FLOOD_MINIMAL_RATE;
}
CIRCSock::CIRCSock(CIRCNetwork* pNetwork)
: CIRCSocket(),
m_bAuthed(false),
m_bNamesx(false),
m_bUHNames(false),
m_bAwayNotify(false),
m_bAccountNotify(false),
m_bExtendedJoin(false),
m_bServerTime(false),
m_sPerms("*!@%+"),
m_sPermModes("qaohv"),
m_scUserModes(),
m_mceChanModes(),
m_pNetwork(pNetwork),
m_Nick(),
m_sPass(""),
m_msChans(),
m_uMaxNickLen(9),
m_uCapPaused(0),
m_ssAcceptedCaps(),
m_ssPendingCaps(),
m_lastCTCP(0),
m_uNumCTCP(0),
m_mISupport(),
m_vSendQueue(),
m_iSendsAllowed(pNetwork->GetFloodBurst()),
m_uFloodBurst(pNetwork->GetFloodBurst()),
m_fFloodRate(pNetwork->GetFloodRate()),
m_bFloodProtection(IsFloodProtected(pNetwork->GetFloodRate())) {
EnableReadLine();
m_Nick.SetIdent(m_pNetwork->GetIdent());
m_Nick.SetHost(m_pNetwork->GetBindHost());
SetEncoding(m_pNetwork->GetEncoding());
m_mceChanModes['b'] = ListArg;
m_mceChanModes['e'] = ListArg;
m_mceChanModes['I'] = ListArg;
m_mceChanModes['k'] = HasArg;
m_mceChanModes['l'] = ArgWhenSet;
m_mceChanModes['p'] = NoArg;
m_mceChanModes['s'] = NoArg;
m_mceChanModes['t'] = NoArg;
m_mceChanModes['i'] = NoArg;
m_mceChanModes['n'] = NoArg;
pNetwork->SetIRCSocket(this);
// RFC says a line can have 512 chars max + 512 chars for message tags, but
// we don't care ;)
SetMaxBufferThreshold(2048);
if (m_bFloodProtection) {
AddCron(new CIRCFloodTimer(this));
}
}
CIRCSock::~CIRCSock() {
if (!m_bAuthed) {
IRCSOCKMODULECALL(OnIRCConnectionError(this), NOTHING);
}
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
pChan->Reset();
}
m_pNetwork->IRCDisconnected();
for (const auto& it : m_msChans) {
delete it.second;
}
Quit();
m_msChans.clear();
m_pNetwork->AddBytesRead(GetBytesRead());
m_pNetwork->AddBytesWritten(GetBytesWritten());
}
void CIRCSock::Quit(const CString& sQuitMsg) {
if (IsClosed()) {
return;
}
if (!m_bAuthed) {
Close(CLT_NOW);
return;
}
if (!sQuitMsg.empty()) {
PutIRC("QUIT :" + sQuitMsg);
} else {
PutIRC("QUIT :" + m_pNetwork->ExpandString(m_pNetwork->GetQuitMsg()));
}
Close(CLT_AFTERWRITE);
}
void CIRCSock::ReadLine(const CString& sData) {
CString sLine = sData;
sLine.Replace("\n", "");
sLine.Replace("\r", "");
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") IRC -> ZNC [" << sLine << "]");
bool bReturn = false;
IRCSOCKMODULECALL(OnRaw(sLine), &bReturn);
if (bReturn) return;
CMessage Message(sLine);
Message.SetNetwork(m_pNetwork);
IRCSOCKMODULECALL(OnRawMessage(Message), &bReturn);
if (bReturn) return;
switch (Message.GetType()) {
case CMessage::Type::Account:
bReturn = OnAccountMessage(Message);
break;
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::Away:
bReturn = OnAwayMessage(Message);
break;
case CMessage::Type::Capability:
bReturn = OnCapabilityMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Error:
bReturn = OnErrorMessage(Message);
break;
case CMessage::Type::Invite:
bReturn = OnInviteMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Kick:
bReturn = OnKickMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Nick:
bReturn = OnNickMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Numeric:
bReturn = OnNumericMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
case CMessage::Type::Wallops:
bReturn = OnWallopsMessage(Message);
break;
default:
break;
}
if (bReturn) return;
m_pNetwork->PutUser(Message);
}
void CIRCSock::SendNextCap() {
if (!m_uCapPaused) {
if (m_ssPendingCaps.empty()) {
// We already got all needed ACK/NAK replies.
PutIRC("CAP END");
} else {
CString sCap = *m_ssPendingCaps.begin();
m_ssPendingCaps.erase(m_ssPendingCaps.begin());
PutIRC("CAP REQ :" + sCap);
}
}
}
void CIRCSock::PauseCap() { ++m_uCapPaused; }
void CIRCSock::ResumeCap() {
--m_uCapPaused;
SendNextCap();
}
bool CIRCSock::OnServerCapAvailable(const CString& sCap) {
bool bResult = false;
IRCSOCKMODULECALL(OnServerCapAvailable(sCap), &bResult);
return bResult;
}
// #124: OnChanMsg(): nick doesn't have perms
static void FixupChanNick(CNick& Nick, CChan* pChan) {
// A channel nick has up-to-date channel perms, but might be
// lacking (usernames-in-host) the associated ident & host.
// An incoming message, on the other hand, has normally a full
// nick!ident@host prefix. Sync the two so that channel nicks
// get the potentially missing piece of info and module hooks
// get the perms.
CNick* pChanNick = pChan->FindNick(Nick.GetNick());
if (pChanNick) {
if (!Nick.GetIdent().empty()) {
pChanNick->SetIdent(Nick.GetIdent());
}
if (!Nick.GetHost().empty()) {
pChanNick->SetHost(Nick.GetHost());
}
Nick.Clone(*pChanNick);
}
}
bool CIRCSock::OnAccountMessage(CMessage& Message) {
// TODO: IRCSOCKMODULECALL(OnAccountMessage(Message)) ?
return false;
}
bool CIRCSock::OnActionMessage(CActionMessage& Message) {
bool bResult = false;
CChan* pChan = nullptr;
CString sTarget = Message.GetTarget();
if (sTarget.Equals(GetNick())) {
IRCSOCKMODULECALL(OnPrivCTCPMessage(Message), &bResult);
if (bResult) return true;
IRCSOCKMODULECALL(OnPrivActionMessage(Message), &bResult);
if (bResult) return true;
if (!m_pNetwork->IsUserOnline() ||
!m_pNetwork->GetUser()->AutoClearQueryBuffer()) {
const CNick& Nick = Message.GetNick();
CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick());
if (pQuery) {
CActionMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Nick.GetNickMask()));
Format.SetTarget("{target}");
Format.SetText("{text}");
pQuery->AddBuffer(Format, Message.GetText());
}
}
} else {
pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanCTCPMessage(Message), &bResult);
if (bResult) return true;
IRCSOCKMODULECALL(OnChanActionMessage(Message), &bResult);
if (bResult) return true;
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() ||
pChan->IsDetached()) {
CActionMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask()));
Format.SetTarget(_NAMEDFMT(Message.GetTarget()));
Format.SetText("{text}");
pChan->AddBuffer(Format, Message.GetText());
}
}
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnAwayMessage(CMessage& Message) {
// TODO: IRCSOCKMODULECALL(OnAwayMessage(Message)) ?
return false;
}
bool CIRCSock::OnCapabilityMessage(CMessage& Message) {
// CAPs are supported only before authorization.
if (!m_bAuthed) {
// The first parameter is most likely "*". No idea why, the
// CAP spec don't mention this, but all implementations
// I've seen add this extra asterisk
CString sSubCmd = Message.GetParam(1);
// If the caplist of a reply is too long, it's split
// into multiple replies. A "*" is prepended to show
// that the list was split into multiple replies.
// This is useful mainly for LS. For ACK and NAK
// replies, there's no real need for this, because
// we request only 1 capability per line.
// If we will need to support broken servers or will
// send several requests per line, need to delay ACK
// actions until all ACK lines are received and
// to recognize past request of NAK by 100 chars
// of this reply.
CString sArgs;
if (Message.GetParam(2) == "*") {
sArgs = Message.GetParam(3);
} else {
sArgs = Message.GetParam(2);
}
std::map<CString, std::function<void(bool bVal)>> mSupportedCaps = {
{"multi-prefix", [this](bool bVal) { m_bNamesx = bVal; }},
{"userhost-in-names", [this](bool bVal) { m_bUHNames = bVal; }},
{"away-notify", [this](bool bVal) { m_bAwayNotify = bVal; }},
{"account-notify", [this](bool bVal) { m_bAccountNotify = bVal; }},
{"extended-join", [this](bool bVal) { m_bExtendedJoin = bVal; }},
{"server-time", [this](bool bVal) { m_bServerTime = bVal; }},
{"znc.in/server-time-iso",
[this](bool bVal) { m_bServerTime = bVal; }},
};
if (sSubCmd == "LS") {
VCString vsTokens;
sArgs.Split(" ", vsTokens, false);
for (const CString& sCap : vsTokens) {
if (OnServerCapAvailable(sCap) || mSupportedCaps.count(sCap)) {
m_ssPendingCaps.insert(sCap);
}
}
} else if (sSubCmd == "ACK") {
sArgs.Trim();
IRCSOCKMODULECALL(OnServerCapResult(sArgs, true), NOTHING);
const auto& it = mSupportedCaps.find(sArgs);
if (it != mSupportedCaps.end()) {
it->second(true);
}
m_ssAcceptedCaps.insert(sArgs);
} else if (sSubCmd == "NAK") {
// This should work because there's no [known]
// capability with length of name more than 100 characters.
sArgs.Trim();
IRCSOCKMODULECALL(OnServerCapResult(sArgs, false), NOTHING);
}
SendNextCap();
}
// Don't forward any CAP stuff to the client
return true;
}
bool CIRCSock::OnCTCPMessage(CCTCPMessage& Message) {
bool bResult = false;
CChan* pChan = nullptr;
CString sTarget = Message.GetTarget();
if (sTarget.Equals(GetNick())) {
if (Message.IsReply()) {
IRCSOCKMODULECALL(OnCTCPReplyMessage(Message), &bResult);
return bResult;
} else {
IRCSOCKMODULECALL(OnPrivCTCPMessage(Message), &bResult);
if (bResult) return true;
}
} else {
pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanCTCPMessage(Message), &bResult);
if (bResult) return true;
}
}
const CNick& Nick = Message.GetNick();
const CString& sMessage = Message.GetText();
const MCString& mssCTCPReplies = m_pNetwork->GetUser()->GetCTCPReplies();
CString sQuery = sMessage.Token(0).AsUpper();
MCString::const_iterator it = mssCTCPReplies.find(sQuery);
bool bHaveReply = false;
CString sReply;
if (it != mssCTCPReplies.end()) {
sReply = m_pNetwork->ExpandString(it->second);
bHaveReply = true;
if (sReply.empty()) {
return true;
}
}
if (!bHaveReply && !m_pNetwork->IsUserAttached()) {
if (sQuery == "VERSION") {
sReply = CZNC::GetTag(false);
} else if (sQuery == "PING") {
sReply = sMessage.Token(1, true);
}
}
if (!sReply.empty()) {
time_t now = time(nullptr);
// If the last CTCP is older than m_uCTCPFloodTime, reset the counter
if (m_lastCTCP + m_uCTCPFloodTime < now) m_uNumCTCP = 0;
m_lastCTCP = now;
// If we are over the limit, don't reply to this CTCP
if (m_uNumCTCP >= m_uCTCPFloodCount) {
DEBUG("CTCP flood detected - not replying to query");
return true;
}
m_uNumCTCP++;
PutIRC("NOTICE " + Nick.GetNick() + " :\001" + sQuery + " " + sReply +
"\001");
return true;
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnErrorMessage(CMessage& Message) {
// ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
CString sError = Message.GetParam(0);
m_pNetwork->PutStatus(t_f("Error from server: {1}")(sError));
return true;
}
bool CIRCSock::OnInviteMessage(CMessage& Message) {
bool bResult = false;
IRCSOCKMODULECALL(OnInvite(Message.GetNick(), Message.GetParam(1)),
&bResult);
return bResult;
}
bool CIRCSock::OnJoinMessage(CJoinMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sChan = Message.GetParam(0);
CChan* pChan = nullptr;
if (Nick.NickEquals(GetNick())) {
m_pNetwork->AddChan(sChan, false);
pChan = m_pNetwork->FindChan(sChan);
if (pChan) {
pChan->Enable();
pChan->SetIsOn(true);
PutIRC("MODE " + sChan);
}
} else {
pChan = m_pNetwork->FindChan(sChan);
}
if (pChan) {
pChan->AddNick(Nick.GetNickMask());
Message.SetChan(pChan);
IRCSOCKMODULECALL(OnJoinMessage(Message), NOTHING);
if (pChan->IsDetached()) {
return true;
}
}
return false;
}
bool CIRCSock::OnKickMessage(CKickMessage& Message) {
CString sChan = Message.GetParam(0);
CString sKickedNick = Message.GetKickedNick();
CChan* pChan = m_pNetwork->FindChan(sChan);
if (pChan) {
Message.SetChan(pChan);
IRCSOCKMODULECALL(OnKickMessage(Message), NOTHING);
// do not remove the nick till after the OnKick call, so modules
// can do Chan.FindNick or something to get more info.
pChan->RemNick(sKickedNick);
}
if (GetNick().Equals(sKickedNick) && pChan) {
pChan->SetIsOn(false);
// Don't try to rejoin!
pChan->Disable();
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnModeMessage(CModeMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sTarget = Message.GetTarget();
CString sModes = Message.GetModes();
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
pChan->ModeChange(sModes, &Nick);
if (pChan->IsDetached()) {
return true;
}
} else if (sTarget == m_Nick.GetNick()) {
CString sModeArg = sModes.Token(0);
bool bAdd = true;
/* no module call defined (yet?)
MODULECALL(OnRawUserMode(*pOpNick, *this, sModeArg, sArgs),
m_pNetwork->GetUser(), nullptr, );
*/
for (unsigned int a = 0; a < sModeArg.size(); a++) {
const char& cMode = sModeArg[a];
if (cMode == '+') {
bAdd = true;
} else if (cMode == '-') {
bAdd = false;
} else {
if (bAdd) {
m_scUserModes.insert(cMode);
} else {
m_scUserModes.erase(cMode);
}
}
}
}
return false;
}
bool CIRCSock::OnNickMessage(CNickMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sNewNick = Message.GetNewNick();
bool bIsVisible = false;
vector<CChan*> vFoundChans;
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
if (pChan->ChangeNick(Nick.GetNick(), sNewNick)) {
vFoundChans.push_back(pChan);
if (!pChan->IsDetached()) {
bIsVisible = true;
}
}
}
if (Nick.NickEquals(GetNick())) {
// We are changing our own nick, the clients always must see this!
bIsVisible = false;
SetNick(sNewNick);
m_pNetwork->PutUser(Message);
}
IRCSOCKMODULECALL(OnNickMessage(Message, vFoundChans), NOTHING);
return !bIsVisible;
}
bool CIRCSock::OnNoticeMessage(CNoticeMessage& Message) {
CString sTarget = Message.GetTarget();
bool bResult = false;
if (sTarget.Equals(GetNick())) {
IRCSOCKMODULECALL(OnPrivNoticeMessage(Message), &bResult);
if (bResult) return true;
if (!m_pNetwork->IsUserOnline()) {
// If the user is detached, add to the buffer
CNoticeMessage Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(Message.GetNick().GetNickMask())));
Format.SetTarget("{target}");
Format.SetText("{text}");
m_pNetwork->AddNoticeBuffer(Format, Message.GetText());
}
return false;
} else {
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanNoticeMessage(Message), &bResult);
if (bResult) return true;
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() ||
pChan->IsDetached()) {
CNoticeMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask()));
Format.SetTarget(_NAMEDFMT(Message.GetTarget()));
Format.SetText("{text}");
pChan->AddBuffer(Format, Message.GetText());
}
}
return (pChan && pChan->IsDetached());
}
}
static CMessage BufferMessage(const CNumericMessage& Message) {
CMessage Format(Message);
Format.SetNick(CNick(_NAMEDFMT(Message.GetNick().GetHostMask())));
Format.SetParam(0, "{target}");
unsigned uParams = Format.GetParams().size();
for (unsigned int i = 1; i < uParams; ++i) {
Format.SetParam(i, _NAMEDFMT(Format.GetParam(i)));
}
return Format;
}
bool CIRCSock::OnNumericMessage(CNumericMessage& Message) {
const CString& sCmd = Message.GetCommand();
CString sServer = Message.GetNick().GetHostMask();
unsigned int uRaw = Message.GetCode();
CString sNick = Message.GetParam(0);
bool bResult = false;
IRCSOCKMODULECALL(OnNumericMessage(Message), &bResult);
if (bResult) return true;
switch (uRaw) {
case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay
if (m_bAuthed && sServer == "irc.znc.in") {
// m_bAuthed == true => we already received another 001 => we
// might be in a traffic loop
m_pNetwork->PutStatus(t_s(
"ZNC seems to be connected to itself, disconnecting..."));
Quit();
return true;
}
m_pNetwork->SetIRCServer(sServer);
// Now that we are connected, let nature take its course
SetTimeout(m_pNetwork->GetUser()->GetNoTrafficTimeout(), TMO_READ);
PutIRC("WHO " + sNick);
m_bAuthed = true;
m_pNetwork->PutStatus("Connected!");
const vector<CClient*>& vClients = m_pNetwork->GetClients();
for (CClient* pClient : vClients) {
CString sClientNick = pClient->GetNick(false);
if (!sClientNick.Equals(sNick)) {
// If they connected with a nick that doesn't match the one
// we got on irc, then we need to update them
pClient->PutClient(":" + sClientNick + "!" +
m_Nick.GetIdent() + "@" +
m_Nick.GetHost() + " NICK :" + sNick);
}
}
SetNick(sNick);
IRCSOCKMODULECALL(OnIRCConnected(), NOTHING);
m_pNetwork->ClearRawBuffer();
m_pNetwork->AddRawBuffer(BufferMessage(Message));
m_pNetwork->IRCConnected();
break;
}
case 5:
ParseISupport(Message);
m_pNetwork->UpdateExactRawBuffer(BufferMessage(Message));
break;
case 10: { // :irc.server.com 010 nick <hostname> <port> :<info>
CString sHost = Message.GetParam(1);
CString sPort = Message.GetParam(2);
CString sInfo = Message.GetParam(3);
m_pNetwork->PutStatus(
t_f("Server {1} redirects us to {2}:{3} with reason: {4}")(
m_pNetwork->GetCurrentServer()->GetString(false), sHost,
sPort, sInfo));
m_pNetwork->PutStatus(
t_s("Perhaps you want to add it as a new server."));
// Don't send server redirects to the client
return true;
}
case 2:
case 3:
case 4:
case 250: // highest connection count
case 251: // user count
case 252: // oper count
case 254: // channel count
case 255: // client count
case 265: // local users
case 266: // global users
m_pNetwork->UpdateRawBuffer(sCmd, BufferMessage(Message));
break;
case 305:
m_pNetwork->SetIRCAway(false);
break;
case 306:
m_pNetwork->SetIRCAway(true);
break;
case 324: { // MODE
// :irc.server.com 324 nick #chan +nstk key
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
pChan->SetModes(Message.GetParamsColon(2));
// We don't SetModeKnown(true) here,
// because a 329 will follow
if (!pChan->IsModeKnown()) {
// When we JOIN, we send a MODE
// request. This makes sure the
// reply isn't forwarded.
return true;
}
if (pChan->IsDetached()) {
return true;
}
}
} break;
case 329: {
// :irc.server.com 329 nick #chan 1234567890
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
unsigned long ulDate = Message.GetParam(2).ToULong();
pChan->SetCreationDate(ulDate);
if (!pChan->IsModeKnown()) {
pChan->SetModeKnown(true);
// When we JOIN, we send a MODE
// request. This makes sure the
// reply isn't forwarded.
return true;
}
if (pChan->IsDetached()) {
return true;
}
}
} break;
case 331: {
// :irc.server.com 331 yournick #chan :No topic is set.
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
pChan->SetTopic("");
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 332: {
// :irc.server.com 332 yournick #chan :This is a topic
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
CString sTopic = Message.GetParam(2);
pChan->SetTopic(sTopic);
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 333: {
// :irc.server.com 333 yournick #chan setternick 1112320796
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
sNick = Message.GetParam(2);
unsigned long ulDate = Message.GetParam(3).ToULong();
pChan->SetTopicOwner(sNick);
pChan->SetTopicDate(ulDate);
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 352: { // WHO
// :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name
sNick = Message.GetParam(5);
CString sChan = Message.GetParam(1);
CString sIdent = Message.GetParam(2);
CString sHost = Message.GetParam(3);
if (sNick.Equals(GetNick())) {
m_Nick.SetIdent(sIdent);
m_Nick.SetHost(sHost);
}
m_pNetwork->SetIRCNick(m_Nick);
m_pNetwork->SetIRCServer(sServer);
// A nick can only have one ident and hostname. Yes, you can query
// this information per-channel, but it is still global. For
// example, if the client supports UHNAMES, but the IRC server does
// not, then AFAIR "passive snooping of WHO replies" is the only way
// that ZNC can figure out the ident and host for the UHNAMES
// replies.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
pChan->OnWho(sNick, sIdent, sHost);
}
CChan* pChan = m_pNetwork->FindChan(sChan);
if (pChan && pChan->IsDetached()) {
return true;
}
break;
}
case 353: { // NAMES
// :irc.server.com 353 nick @ #chan :nick1 nick2
// Todo: allow for non @+= server msgs
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(2));
// If we don't know that channel, some client might have
// requested a /names for it and we really should forward this.
if (pChan) {
CString sNicks = Message.GetParam(3);
pChan->AddNicks(sNicks);
if (pChan->IsDetached()) {
return true;
}
}
break;
}
case 366: { // end of names list
// :irc.server.com 366 nick #chan :End of /NAMES list.
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (pChan) {
if (pChan->IsOn()) {
// If we are the only one in the chan, set our default modes
if (pChan->GetNickCount() == 1) {
CString sModes = pChan->GetDefaultModes();
if (sModes.empty()) {
sModes =
m_pNetwork->GetUser()->GetDefaultChanModes();
}
if (!sModes.empty()) {
PutIRC("MODE " + pChan->GetName() + " " + sModes);
}
}
}
if (pChan->IsDetached()) {
// don't put it to clients
return true;
}
}
break;
}
case 375: // begin motd
case 422: // MOTD File is missing
if (m_pNetwork->GetIRCServer().Equals(sServer)) {
m_pNetwork->ClearMotdBuffer();
}
case 372: // motd
case 376: // end motd
if (m_pNetwork->GetIRCServer().Equals(sServer)) {
m_pNetwork->AddMotdBuffer(BufferMessage(Message));
}
break;
case 437:
// :irc.server.net 437 * badnick :Nick/channel is temporarily unavailable
// :irc.server.net 437 mynick badnick :Nick/channel is temporarily unavailable
// :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel
if (m_pNetwork->IsChan(Message.GetParam(1)) || sNick != "*") break;
case 432:
// :irc.server.com 432 * nick :Erroneous Nickname: Illegal chars
case 433: {
CString sBadNick = Message.GetParam(1);
if (!m_bAuthed) {
SendAltNick(sBadNick);
return true;
}
break;
}
case 451:
// :irc.server.com 451 CAP :You have not registered
// Servers that don't support CAP will give us this error, don't send
// it to the client
if (sNick.Equals("CAP")) return true;
case 470: {
// :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to the linked channel #chan2
// :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel
// freenode style numeric
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1));
if (!pChan) {
// unreal style numeric
pChan = m_pNetwork->FindChan(Message.GetParam(2));
}
if (pChan) {
pChan->Disable();
m_pNetwork->PutStatus(
t_f("Channel {1} is linked to another channel and was thus "
"disabled.")(pChan->GetName()));
}
break;
}
case 670:
// :hydra.sector5d.org 670 kylef :STARTTLS successful, go ahead with TLS handshake
//
// 670 is a response to `STARTTLS` telling the client to switch to
// TLS
if (!GetSSL()) {
StartTLS();
m_pNetwork->PutStatus(t_s("Switched to SSL (STARTTLS)"));
}
return true;
}
return false;
}
bool CIRCSock::OnPartMessage(CPartMessage& Message) {
const CNick& Nick = Message.GetNick();
CString sChan = Message.GetTarget();
CChan* pChan = m_pNetwork->FindChan(sChan);
bool bDetached = false;
if (pChan) {
pChan->RemNick(Nick.GetNick());
Message.SetChan(pChan);
IRCSOCKMODULECALL(OnPartMessage(Message), NOTHING);
if (pChan->IsDetached()) bDetached = true;
}
if (Nick.NickEquals(GetNick())) {
m_pNetwork->DelChan(sChan);
}
/*
* We use this boolean because
* m_pNetwork->DelChan() will delete this channel
* and thus we would dereference an
* already-freed pointer!
*/
return bDetached;
}
bool CIRCSock::OnPingMessage(CMessage& Message) {
// Generate a reply and don't forward this to any user,
// we don't want any PING forwarded
PutIRCQuick("PONG " + Message.GetParam(0));
return true;
}
bool CIRCSock::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CIRCSock::OnQuitMessage(CQuitMessage& Message) {
const CNick& Nick = Message.GetNick();
bool bIsVisible = false;
if (Nick.NickEquals(GetNick())) {
m_pNetwork->PutStatus(t_f("You quit: {1}")(Message.GetReason()));
// We don't call module hooks and we don't
// forward this quit to clients (Some clients
// disconnect if they receive such a QUIT)
return true;
}
vector<CChan*> vFoundChans;
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (CChan* pChan : vChans) {
if (pChan->RemNick(Nick.GetNick())) {
vFoundChans.push_back(pChan);
if (!pChan->IsDetached()) {
bIsVisible = true;
}
}
}
IRCSOCKMODULECALL(OnQuitMessage(Message, vFoundChans), NOTHING);
return !bIsVisible;
}
bool CIRCSock::OnTextMessage(CTextMessage& Message) {
bool bResult = false;
CChan* pChan = nullptr;
CString sTarget = Message.GetTarget();
if (sTarget.Equals(GetNick())) {
IRCSOCKMODULECALL(OnPrivTextMessage(Message), &bResult);
if (bResult) return true;
if (!m_pNetwork->IsUserOnline() ||
!m_pNetwork->GetUser()->AutoClearQueryBuffer()) {
const CNick& Nick = Message.GetNick();
CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick());
if (pQuery) {
CTextMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Nick.GetNickMask()));
Format.SetTarget("{target}");
Format.SetText("{text}");
pQuery->AddBuffer(Format, Message.GetText());
}
}
} else {
pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
Message.SetChan(pChan);
FixupChanNick(Message.GetNick(), pChan);
IRCSOCKMODULECALL(OnChanTextMessage(Message), &bResult);
if (bResult) return true;
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() ||
pChan->IsDetached()) {
CTextMessage Format;
Format.Clone(Message);
Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask()));
Format.SetTarget(_NAMEDFMT(Message.GetTarget()));
Format.SetText("{text}");
pChan->AddBuffer(Format, Message.GetText());
}
}
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnTopicMessage(CTopicMessage& Message) {
const CNick& Nick = Message.GetNick();
CChan* pChan = m_pNetwork->FindChan(Message.GetParam(0));
if (pChan) {
Message.SetChan(pChan);
bool bReturn = false;
IRCSOCKMODULECALL(OnTopicMessage(Message), &bReturn);
if (bReturn) return true;
pChan->SetTopicOwner(Nick.GetNick());
pChan->SetTopicDate((unsigned long)time(nullptr));
pChan->SetTopic(Message.GetTopic());
}
return (pChan && pChan->IsDetached());
}
bool CIRCSock::OnWallopsMessage(CMessage& Message) {
// :blub!dummy@rox-8DBEFE92 WALLOPS :this is a test
CString sMsg = Message.GetParam(0);
if (!m_pNetwork->IsUserOnline()) {
CMessage Format(Message);
Format.SetNick(CNick(_NAMEDFMT(Message.GetNick().GetHostMask())));
Format.SetParam(0, "{text}");
m_pNetwork->AddNoticeBuffer(Format, sMsg);
}
return false;
}
void CIRCSock::PutIRC(const CString& sLine) {
PutIRC(CMessage(sLine));
}
void CIRCSock::PutIRC(const CMessage& Message) {
// Only print if the line won't get sent immediately (same condition as in
// TrySend()!)
if (m_bFloodProtection && m_iSendsAllowed <= 0) {
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") ZNC -> IRC ["
<< CDebug::Filter(Message.ToString()) << "] (queued)");
}
m_vSendQueue.push_back(Message);
TrySend();
}
void CIRCSock::PutIRCQuick(const CString& sLine) {
// Only print if the line won't get sent immediately (same condition as in
// TrySend()!)
if (m_bFloodProtection && m_iSendsAllowed <= 0) {
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") ZNC -> IRC ["
<< CDebug::Filter(sLine) << "] (queued to front)");
}
m_vSendQueue.emplace_front(sLine);
TrySend();
}
void CIRCSock::TrySend() {
// This condition must be the same as in PutIRC() and PutIRCQuick()!
while (!m_vSendQueue.empty() &&
(!m_bFloodProtection || m_iSendsAllowed > 0)) {
m_iSendsAllowed--;
CMessage& Message = m_vSendQueue.front();
MCString mssTags;
for (const auto& it : Message.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
Message.SetTags(mssTags);
Message.SetNetwork(m_pNetwork);
bool bSkip = false;
IRCSOCKMODULECALL(OnSendToIRCMessage(Message), &bSkip);
if (!bSkip) {
PutIRCRaw(Message.ToString());
}
m_vSendQueue.pop_front();
}
}
void CIRCSock::PutIRCRaw(const CString& sLine) {
CString sCopy = sLine;
bool bSkip = false;
IRCSOCKMODULECALL(OnSendToIRC(sCopy), &bSkip);
if (!bSkip) {
DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/"
<< m_pNetwork->GetName() << ") ZNC -> IRC ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
}
}
void CIRCSock::SetNick(const CString& sNick) {
m_Nick.SetNick(sNick);
m_pNetwork->SetIRCNick(m_Nick);
}
void CIRCSock::Connected() {
DEBUG(GetSockName() << " == Connected()");
CString sPass = m_sPass;
CString sNick = m_pNetwork->GetNick();
CString sIdent = m_pNetwork->GetIdent();
CString sRealName = m_pNetwork->GetRealName();
bool bReturn = false;
IRCSOCKMODULECALL(OnIRCRegistration(sPass, sNick, sIdent, sRealName),
&bReturn);
if (bReturn) return;
PutIRC("CAP LS");
if (!sPass.empty()) {
PutIRC("PASS " + sPass);
}
PutIRC("NICK " + sNick);
PutIRC("USER " + sIdent + " \"" + sIdent + "\" \"" + sIdent + "\" :" +
sRealName);
// SendAltNick() needs this
m_Nick.SetNick(sNick);
}
void CIRCSock::Disconnected() {
IRCSOCKMODULECALL(OnIRCDisconnected(), NOTHING);
DEBUG(GetSockName() << " == Disconnected()");
if (!m_pNetwork->GetUser()->IsBeingDeleted() &&
m_pNetwork->GetIRCConnectEnabled() &&
m_pNetwork->GetServers().size() != 0) {
m_pNetwork->PutStatus(t_s("Disconnected from IRC. Reconnecting..."));
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
ResetChans();
// send a "reset user modes" cmd to the client.
// otherwise, on reconnect, it might think it still
// had user modes that it actually doesn't have.
CString sUserMode;
for (char cMode : m_scUserModes) {
sUserMode += cMode;
}
if (!sUserMode.empty()) {
m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" MODE " + m_pNetwork->GetIRCNick().GetNick() +
" :-" + sUserMode);
}
// also clear the user modes in our space:
m_scUserModes.clear();
}
void CIRCSock::SockError(int iErrno, const CString& sDescription) {
CString sError = sDescription;
DEBUG(GetSockName() << " == SockError(" << iErrno << " " << sError << ")");
if (!m_pNetwork->GetUser()->IsBeingDeleted()) {
if (GetConState() != CST_OK) {
m_pNetwork->PutStatus(
t_f("Cannot connect to IRC ({1}). Retrying...")(sError));
} else {
m_pNetwork->PutStatus(
t_f("Disconnected from IRC ({1}). Reconnecting...")(sError));
}
#ifdef HAVE_LIBSSL
if (iErrno == errnoBadSSLCert) {
// Stringify bad cert
X509* pCert = GetX509();
if (pCert) {
BIO* mem = BIO_new(BIO_s_mem());
X509_print(mem, pCert);
X509_free(pCert);
char* pCertStr = nullptr;
long iLen = BIO_get_mem_data(mem, &pCertStr);
CString sCert(pCertStr, iLen);
BIO_free(mem);
VCString vsCert;
sCert.Split("\n", vsCert);
for (const CString& s : vsCert) {
// It shouldn't contain any bad characters, but let's be
// safe...
m_pNetwork->PutStatus("|" + s.Escape_n(CString::EDEBUG));
}
CString sSHA1;
if (GetPeerFingerprint(sSHA1))
m_pNetwork->PutStatus(
"SHA1: " +
sSHA1.Escape_n(CString::EHEXCOLON, CString::EHEXCOLON));
CString sSHA256 = GetSSLPeerFingerprint();
m_pNetwork->PutStatus("SHA-256: " + sSHA256);
m_pNetwork->PutStatus(
t_f("If you trust this certificate, do /znc "
"AddTrustedServerFingerprint {1}")(sSHA256));
}
}
#endif
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
ResetChans();
m_scUserModes.clear();
}
void CIRCSock::Timeout() {
DEBUG(GetSockName() << " == Timeout()");
if (!m_pNetwork->GetUser()->IsBeingDeleted()) {
m_pNetwork->PutStatus(
t_s("IRC connection timed out. Reconnecting..."));
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
ResetChans();
m_scUserModes.clear();
}
void CIRCSock::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
if (!m_pNetwork->GetUser()->IsBeingDeleted()) {
m_pNetwork->PutStatus(t_s("Connection Refused. Reconnecting..."));
}
m_pNetwork->ClearRawBuffer();
m_pNetwork->ClearMotdBuffer();
}
void CIRCSock::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
m_pNetwork->PutStatus(t_s("Received a too long line from the IRC server!"));
Quit();
}
void CIRCSock::ParseISupport(const CMessage& Message) {
const VCString vsParams = Message.GetParams();
for (size_t i = 1; i + 1 < vsParams.size(); ++i) {
const CString& sParam = vsParams[i];
CString sName = sParam.Token(0, false, "=");
CString sValue = sParam.Token(1, true, "=");
if (0 < sName.length() && ':' == sName[0]) {
break;
}
m_mISupport[sName] = sValue;
if (sName.Equals("PREFIX")) {
CString sPrefixes = sValue.Token(1, false, ")");
CString sPermModes = sValue.Token(0, false, ")");
sPermModes.TrimLeft("(");
if (!sPrefixes.empty() && sPermModes.size() == sPrefixes.size()) {
m_sPerms = sPrefixes;
m_sPermModes = sPermModes;
}
} else if (sName.Equals("CHANTYPES")) {
m_pNetwork->SetChanPrefixes(sValue);
} else if (sName.Equals("NICKLEN")) {
unsigned int uMax = sValue.ToUInt();
if (uMax) {
m_uMaxNickLen = uMax;
}
} else if (sName.Equals("CHANMODES")) {
if (!sValue.empty()) {
m_mceChanModes.clear();
for (unsigned int a = 0; a < 4; a++) {
CString sModes = sValue.Token(a, false, ",");
for (unsigned int b = 0; b < sModes.size(); b++) {
m_mceChanModes[sModes[b]] = (EChanModeArgs)a;
}
}
}
} else if (sName.Equals("NAMESX")) {
if (m_bNamesx) continue;
m_bNamesx = true;
PutIRC("PROTOCTL NAMESX");
} else if (sName.Equals("UHNAMES")) {
if (m_bUHNames) continue;
m_bUHNames = true;
PutIRC("PROTOCTL UHNAMES");
}
}
}
CString CIRCSock::GetISupport(const CString& sKey,
const CString& sDefault) const {
MCString::const_iterator i = m_mISupport.find(sKey.AsUpper());
if (i == m_mISupport.end()) {
return sDefault;
} else {
return i->second;
}
}
void CIRCSock::SendAltNick(const CString& sBadNick) {
const CString& sLastNick = m_Nick.GetNick();
// We don't know the maximum allowed nick length yet, but we know which
// nick we sent last. If sBadNick is shorter than that, we assume the
// server truncated our nick.
if (sBadNick.length() < sLastNick.length())
m_uMaxNickLen = (unsigned int)sBadNick.length();
unsigned int uMax = m_uMaxNickLen;
const CString& sConfNick = m_pNetwork->GetNick();
const CString& sAltNick = m_pNetwork->GetAltNick();
CString sNewNick = sConfNick.Left(uMax - 1);
if (sLastNick.Equals(sConfNick)) {
if ((!sAltNick.empty()) && (!sConfNick.Equals(sAltNick))) {
sNewNick = sAltNick;
} else {
sNewNick += "-";
}
} else if (sLastNick.Equals(sAltNick) && !sAltNick.Equals(sNewNick + "-")) {
sNewNick += "-";
} else if (sLastNick.Equals(sNewNick + "-") &&
!sAltNick.Equals(sNewNick + "|")) {
sNewNick += "|";
} else if (sLastNick.Equals(sNewNick + "|") &&
!sAltNick.Equals(sNewNick + "^")) {
sNewNick += "^";
} else if (sLastNick.Equals(sNewNick + "^") &&
!sAltNick.Equals(sNewNick + "a")) {
sNewNick += "a";
} else {
char cLetter = 0;
if (sBadNick.empty()) {
m_pNetwork->PutUser(t_s("No free nick available"));
Quit();
return;
}
cLetter = sBadNick.back();
if (cLetter == 'z') {
m_pNetwork->PutUser(t_s("No free nick found"));
Quit();
return;
}
sNewNick = sConfNick.Left(uMax - 1) + ++cLetter;
if (sNewNick.Equals(sAltNick))
sNewNick = sConfNick.Left(uMax - 1) + ++cLetter;
}
PutIRC("NICK " + sNewNick);
m_Nick.SetNick(sNewNick);
}
char CIRCSock::GetPermFromMode(char cMode) const {
if (m_sPermModes.size() == m_sPerms.size()) {
for (unsigned int a = 0; a < m_sPermModes.size(); a++) {
if (m_sPermModes[a] == cMode) {
return m_sPerms[a];
}
}
}
return 0;
}
CIRCSock::EChanModeArgs CIRCSock::GetModeType(char cMode) const {
map<char, EChanModeArgs>::const_iterator it =
m_mceChanModes.find(cMode);
if (it == m_mceChanModes.end()) {
return NoArg;
}
return it->second;
}
void CIRCSock::ResetChans() {
for (const auto& it : m_msChans) {
it.second->Reset();
}
}
void CIRCSock::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_239_1 |
crossvul-cpp_data_bad_3220_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_3220_0 |
crossvul-cpp_data_bad_1581_0 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: ParaNdis-Common.c
*
* This file contains NDIS driver procedures, common for NDIS5 and NDIS6
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
static VOID ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext);
static __inline pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue);
// TODO: remove when the problem solved
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue);
//#define ROUNDSIZE(sz) ((sz + 15) & ~15)
#define MAX_VLAN_ID 4095
#define ABSTRACT_PATHES_TAG 'APVR'
/**********************************************************
Validates MAC address
Valid MAC address is not broadcast, not multicast, not empty
if bLocal is set, it must be LOCAL
if not, is must be non-local or local
Parameters:
PUCHAR pcMacAddress - MAC address to validate
BOOLEAN bLocal - TRUE, if we validate locally administered address
Return value:
TRUE if valid
***********************************************************/
BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal)
{
BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE;
bBroadcast = ETH_IS_BROADCAST(pcMacAddress);
bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress);
bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress);
bEmpty = ETH_IS_EMPTY(pcMacAddress);
return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA);
}
typedef struct _tagConfigurationEntry
{
const char *Name;
ULONG ulValue;
ULONG ulMinimal;
ULONG ulMaximal;
}tConfigurationEntry;
typedef struct _tagConfigurationEntries
{
tConfigurationEntry PrioritySupport;
tConfigurationEntry ConnectRate;
tConfigurationEntry isLogEnabled;
tConfigurationEntry debugLevel;
tConfigurationEntry TxCapacity;
tConfigurationEntry RxCapacity;
tConfigurationEntry LogStatistics;
tConfigurationEntry OffloadTxChecksum;
tConfigurationEntry OffloadTxLSO;
tConfigurationEntry OffloadRxCS;
tConfigurationEntry stdIpcsV4;
tConfigurationEntry stdTcpcsV4;
tConfigurationEntry stdTcpcsV6;
tConfigurationEntry stdUdpcsV4;
tConfigurationEntry stdUdpcsV6;
tConfigurationEntry stdLsoV1;
tConfigurationEntry stdLsoV2ip4;
tConfigurationEntry stdLsoV2ip6;
tConfigurationEntry PriorityVlanTagging;
tConfigurationEntry VlanId;
tConfigurationEntry PublishIndices;
tConfigurationEntry MTU;
tConfigurationEntry NumberOfHandledRXPackersInDPC;
#if PARANDIS_SUPPORT_RSS
tConfigurationEntry RSSOffloadSupported;
tConfigurationEntry NumRSSQueues;
#endif
#if PARANDIS_SUPPORT_RSC
tConfigurationEntry RSCIPv4Supported;
tConfigurationEntry RSCIPv6Supported;
#endif
}tConfigurationEntries;
static const tConfigurationEntries defaultConfiguration =
{
{ "Priority", 0, 0, 1 },
{ "ConnectRate", 100,10,10000 },
{ "DoLog", 1, 0, 1 },
{ "DebugLevel", 2, 0, 8 },
{ "TxCapacity", 1024, 16, 1024 },
{ "RxCapacity", 256, 32, 1024 },
{ "LogStatistics", 0, 0, 10000},
{ "Offload.TxChecksum", 0, 0, 31},
{ "Offload.TxLSO", 0, 0, 2},
{ "Offload.RxCS", 0, 0, 31},
{ "*IPChecksumOffloadIPv4", 3, 0, 3 },
{ "*TCPChecksumOffloadIPv4",3, 0, 3 },
{ "*TCPChecksumOffloadIPv6",3, 0, 3 },
{ "*UDPChecksumOffloadIPv4",3, 0, 3 },
{ "*UDPChecksumOffloadIPv6",3, 0, 3 },
{ "*LsoV1IPv4", 1, 0, 1 },
{ "*LsoV2IPv4", 1, 0, 1 },
{ "*LsoV2IPv6", 1, 0, 1 },
{ "*PriorityVLANTag", 3, 0, 3},
{ "VlanId", 0, 0, MAX_VLAN_ID},
{ "PublishIndices", 1, 0, 1},
{ "MTU", 1500, 576, 65500},
{ "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000},
#if PARANDIS_SUPPORT_RSS
{ "*RSS", 1, 0, 1},
{ "*NumRssQueues", 8, 1, PARANDIS_RSS_MAX_RECEIVE_QUEUES},
#endif
#if PARANDIS_SUPPORT_RSC
{ "*RscIPv4", 1, 0, 1},
{ "*RscIPv6", 1, 0, 1},
#endif
};
static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext)
{
VirtIODeviceReset(pContext->IODevice);
DPrintf(0, ("[%s] Done\n", __FUNCTION__));
/* reset all the features in the device */
pContext->ulCurrentVlansFilterSet = 0;
}
/**********************************************************
Gets integer value for specifies in pEntry->Name name
Parameters:
NDIS_HANDLE cfg previously open configuration
tConfigurationEntry *pEntry - Entry to fill value in
***********************************************************/
static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry)
{
NDIS_STATUS status;
const char *statusName;
NDIS_STRING name = {0};
PNDIS_CONFIGURATION_PARAMETER pParam = NULL;
NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger;
NdisInitializeString(&name, (PUCHAR)pEntry->Name);
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadConfiguration(
&status,
&pParam,
cfg,
&name,
ParameterType);
if (status == NDIS_STATUS_SUCCESS)
{
ULONG ulValue = pParam->ParameterData.IntegerData;
if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal)
{
pEntry->ulValue = ulValue;
statusName = "value";
}
else
{
statusName = "out of range";
}
}
else
{
statusName = "nothing";
}
#pragma warning(pop)
DPrintf(2, ("[%s] %s read for %s - 0x%x\n",
__FUNCTION__,
statusName,
pEntry->Name,
pEntry->ulValue));
if (name.Buffer) NdisFreeString(name);
}
static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT4Lso)
{
DPrintf(0, ("[%s] Warning: %s", procname, reason));
pContext->Offload.flagsValue &= ~osbT4Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
if (pContext->Offload.flagsValue & osbT6Lso)
{
DPrintf(0, ("[%s] Warning: %s\n", procname, reason));
pContext->Offload.flagsValue &= ~osbT6Lso;
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
}
}
/**********************************************************
Loads NIC parameters from adapter registry key
Parameters:
context
PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host
***********************************************************/
static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR pNewMACAddress)
{
NDIS_HANDLE cfg;
tConfigurationEntries *pConfiguration = (tConfigurationEntries *) ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries));
if (pConfiguration)
{
*pConfiguration = defaultConfiguration;
cfg = ParaNdis_OpenNICConfiguration(pContext);
if (cfg)
{
GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled);
GetConfigurationEntry(cfg, &pConfiguration->debugLevel);
GetConfigurationEntry(cfg, &pConfiguration->ConnectRate);
GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport);
GetConfigurationEntry(cfg, &pConfiguration->TxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->RxCapacity);
GetConfigurationEntry(cfg, &pConfiguration->LogStatistics);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum);
GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO);
GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS);
GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4);
GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4);
GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6);
GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging);
GetConfigurationEntry(cfg, &pConfiguration->VlanId);
GetConfigurationEntry(cfg, &pConfiguration->PublishIndices);
GetConfigurationEntry(cfg, &pConfiguration->MTU);
GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC);
#if PARANDIS_SUPPORT_RSS
GetConfigurationEntry(cfg, &pConfiguration->RSSOffloadSupported);
GetConfigurationEntry(cfg, &pConfiguration->NumRSSQueues);
#endif
#if PARANDIS_SUPPORT_RSC
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv4Supported);
GetConfigurationEntry(cfg, &pConfiguration->RSCIPv6Supported);
#endif
bDebugPrint = pConfiguration->isLogEnabled.ulValue;
virtioDebugLevel = pConfiguration->debugLevel.ulValue;
pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue;
pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue;
pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue;
pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue;
pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0;
pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue;
pContext->ulFormalLinkSpeed *= 1000000;
pContext->Offload.flagsValue = 0;
// TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum;
if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum;
if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp;
if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions;
// RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum;
if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum;
/* full packet size that can be configured as GSO for VIRTIO is short */
/* NDIS test fails sometimes fails on segments 50-60K */
pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE;
pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue;
pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue;
pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue;
pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue;
pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue;
pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue;
pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue;
pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff;
pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue;
#if PARANDIS_SUPPORT_RSS
pContext->bRSSOffloadSupported = pConfiguration->RSSOffloadSupported.ulValue ? TRUE : FALSE;
pContext->RSSMaxQueuesNumber = (CCHAR) pConfiguration->NumRSSQueues.ulValue;
#endif
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4SupportedSW = (UCHAR)pConfiguration->RSCIPv4Supported.ulValue;
pContext->RSC.bIPv6SupportedSW = (UCHAR)pConfiguration->RSCIPv6Supported.ulValue;
#endif
if (!pContext->bDoSupportPriority)
pContext->ulPriorityVlanSetting = 0;
// if Vlan not supported
if (!IsVlanSupported(pContext)) {
pContext->VlanId = 0;
}
{
NDIS_STATUS status;
PVOID p;
UINT len = 0;
#pragma warning(push)
#pragma warning(disable:6102)
NdisReadNetworkAddress(&status, &p, &len, cfg);
if (status == NDIS_STATUS_SUCCESS && len == ETH_LENGTH_OF_ADDRESS)
{
NdisMoveMemory(pNewMACAddress, p, len);
}
else if (len && len != ETH_LENGTH_OF_ADDRESS)
{
DPrintf(0, ("[%s] MAC address has wrong length of %d\n", __FUNCTION__, len));
}
else
{
DPrintf(4, ("[%s] Nothing read for MAC, error %X\n", __FUNCTION__, status));
}
#pragma warning(pop)
}
NdisCloseConfiguration(cfg);
}
NdisFreeMemory(pConfiguration, 0, 0);
}
}
void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from)
{
if (!pDest) pDest = &pContext->Offload.flags;
if (!from) from = &pContext->Offload.flagsValue;
pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum);
pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum);
pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum);
pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum);
pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum);
pDest->fTxLso = !!(*from & osbT4Lso);
pDest->fTxLsoIP = !!(*from & osbT4LsoIp);
pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp);
pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum);
pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum);
pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum);
pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum);
pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum);
pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum);
pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum);
pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum);
pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum);
pDest->fTxLsov6 = !!(*from & osbT6Lso);
pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt);
pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions);
pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum);
pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum);
pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum);
pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum);
}
/**********************************************************
Enumerates adapter resources and fills the structure holding them
Verifies that IO assigned and has correct size
Verifies that interrupt assigned
Parameters:
PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS
tAdapterResources *pResources - structure to fill
Return value:
TRUE if everything is OK
***********************************************************/
static BOOLEAN GetAdapterResources(PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources)
{
UINT i;
NdisZeroMemory(pResources, sizeof(*pResources));
for (i = 0; i < RList->Count; ++i)
{
ULONG type = RList->PartialDescriptors[i].Type;
if (type == CmResourceTypePort)
{
PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start;
ULONG len = RList->PartialDescriptors[i].u.Port.Length;
DPrintf(0, ("Found IO ports at %08lX(%d)\n", Start.LowPart, len));
pResources->ulIOAddress = Start.LowPart;
pResources->IOLength = len;
}
else if (type == CmResourceTypeInterrupt)
{
pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector;
pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level;
pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity;
pResources->InterruptFlags = RList->PartialDescriptors[i].Flags;
DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X\n",
pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags));
}
}
return pResources->ulIOAddress && pResources->Vector;
}
static void DumpVirtIOFeatures(PPARANDIS_ADAPTER pContext)
{
static const struct { ULONG bitmask; PCHAR Name; } Features[] =
{
{VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" },
{VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" },
{VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" },
{VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" },
{VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"},
{VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"},
{VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"},
{VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"},
{VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"},
{VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"},
{VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"},
{VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"},
{VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"},
{VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"},
{VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"},
{VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"},
{VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"},
{VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"},
{VIRTIO_NET_F_CTRL_MAC_ADDR, "VIRTIO_NET_F_CTRL_MAC_ADDR"},
{VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"},
{VIRTIO_F_ANY_LAYOUT, "VIRTIO_F_ANY_LAYOUT"},
{ VIRTIO_RING_F_EVENT_IDX, "VIRTIO_RING_F_EVENT_IDX" },
};
UINT i;
for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Features[i].bitmask))
{
DPrintf(0, ("VirtIO Host Feature %s\n", Features[i].Name));
}
}
}
static BOOLEAN
AckFeature(PPARANDIS_ADAPTER pContext, UINT32 Feature)
{
if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Feature))
{
VirtIOFeatureEnable(pContext->u32GuestFeatures, Feature);
return TRUE;
}
return FALSE;
}
/**********************************************************
Prints out statistics
***********************************************************/
static void PrintStatistics(PARANDIS_ADAPTER *pContext)
{
ULONG64 totalTxFrames =
pContext->Statistics.ifHCOutBroadcastPkts +
pContext->Statistics.ifHCOutMulticastPkts +
pContext->Statistics.ifHCOutUcastPkts;
ULONG64 totalRxFrames =
pContext->Statistics.ifHCInBroadcastPkts +
pContext->Statistics.ifHCInMulticastPkts +
pContext->Statistics.ifHCInUcastPkts;
#if 0 /* TODO - setup accessor functions*/
DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d\n",
pContext->CurrentMacAddress[5],
pContext->RXPath.m_NetNofReceiveBuffers,
pContext->NetMaxReceiveBuffers));
DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d\n",
pContext->TXPath.GetFreeTXDescriptors(),
pContext->maxFreeTxDescriptors,
pContext->TXPath.GetFreeHWBuffers()));
#endif
DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u\n",
pContext->Statistics.ifHCOutOctets,
pContext->Statistics.ifHCInOctets));
DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d\n",
totalTxFrames,
pContext->extraStatistics.framesCSOffload,
pContext->extraStatistics.framesLSO,
pContext->extraStatistics.framesIndirect));
DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d\n",
totalRxFrames, pContext->extraStatistics.framesRxPriority,
pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut));
if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood)
{
DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d\n",
pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood));
}
}
static
VOID InitializeRSCState(PPARANDIS_ADAPTER pContext)
{
#if PARANDIS_SUPPORT_RSC
pContext->RSC.bIPv4Enabled = FALSE;
pContext->RSC.bIPv6Enabled = FALSE;
if(!pContext->bGuestChecksumSupported)
{
DPrintf(0, ("[%s] Guest TSO cannot be enabled without guest checksum\n", __FUNCTION__) );
return;
}
if(pContext->RSC.bIPv4SupportedSW)
{
pContext->RSC.bIPv4Enabled =
pContext->RSC.bIPv4SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO4);
}
else
{
pContext->RSC.bIPv4SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO4);
}
if(pContext->RSC.bIPv6SupportedSW)
{
pContext->RSC.bIPv6Enabled =
pContext->RSC.bIPv6SupportedHW =
AckFeature(pContext, VIRTIO_NET_F_GUEST_TSO6);
}
else
{
pContext->RSC.bIPv6SupportedHW =
VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO6);
}
pContext->RSC.bHasDynamicConfig = (pContext->RSC.bIPv4Enabled || pContext->RSC.bIPv6Enabled) &&
AckFeature(pContext, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
DPrintf(0, ("[%s] Guest TSO state: IP4=%d, IP6=%d, Dynamic=%d\n", __FUNCTION__,
pContext->RSC.bIPv4Enabled, pContext->RSC.bIPv6Enabled, pContext->RSC.bHasDynamicConfig) );
#else
UNREFERENCED_PARAMETER(pContext);
#endif
}
static __inline void
DumpMac(int dbg_level, const char* header_str, UCHAR* mac)
{
DPrintf(dbg_level,("%s: %02x-%02x-%02x-%02x-%02x-%02x\n",
header_str, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]));
}
static __inline void
SetDeviceMAC(PPARANDIS_ADAPTER pContext, PUCHAR pDeviceMAC)
{
if(pContext->bCfgMACAddrSupported && !pContext->bCtrlMACAddrSupported)
{
VirtIODeviceSet(pContext->IODevice, 0, pDeviceMAC, ETH_LENGTH_OF_ADDRESS);
}
}
static void
InitializeMAC(PPARANDIS_ADAPTER pContext, PUCHAR pCurrentMAC)
{
//Acknowledge related features
pContext->bCfgMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_MAC);
pContext->bCtrlMACAddrSupported = AckFeature(pContext, VIRTIO_NET_F_CTRL_MAC_ADDR);
//Read and validate permanent MAC address
if (pContext->bCfgMACAddrSupported)
{
VirtIODeviceGet(pContext->IODevice, 0, &pContext->PermanentMacAddress, ETH_LENGTH_OF_ADDRESS);
if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE))
{
DumpMac(0, "Invalid device MAC ignored", pContext->PermanentMacAddress);
NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress));
}
}
if (ETH_IS_EMPTY(pContext->PermanentMacAddress))
{
pContext->PermanentMacAddress[0] = 0x02;
pContext->PermanentMacAddress[1] = 0x50;
pContext->PermanentMacAddress[2] = 0xF2;
pContext->PermanentMacAddress[3] = 0x00;
pContext->PermanentMacAddress[4] = 0x01;
pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF);
DumpMac(0, "No device MAC present, use default", pContext->PermanentMacAddress);
}
DumpMac(0, "Permanent device MAC", pContext->PermanentMacAddress);
//Read and validate configured MAC address
if (ParaNdis_ValidateMacAddress(pCurrentMAC, TRUE))
{
DPrintf(0, ("[%s] MAC address from configuration used\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pCurrentMAC);
}
else
{
DPrintf(0, ("No valid MAC configured\n", __FUNCTION__));
ETH_COPY_NETWORK_ADDRESS(pContext->CurrentMacAddress, pContext->PermanentMacAddress);
}
//If control channel message for MAC address configuration is not supported
// Configure device with actual MAC address via configurations space
//Else actual MAC address will be configured later via control queue
SetDeviceMAC(pContext, pContext->CurrentMacAddress);
DumpMac(0, "Actual MAC", pContext->CurrentMacAddress);
}
static __inline void
RestoreMAC(PPARANDIS_ADAPTER pContext)
{
SetDeviceMAC(pContext, pContext->PermanentMacAddress);
}
/**********************************************************
Initializes the context structure
Major variables, received from NDIS on initialization, must be be set before this call
(for ex. pContext->MiniportHandle)
If this procedure fails, no need to call
ParaNdis_CleanupContext
Parameters:
Return value:
SUCCESS, if resources are OK
NDIS_STATUS_RESOURCE_CONFLICT if not
***********************************************************/
NDIS_STATUS ParaNdis_InitializeContext(
PARANDIS_ADAPTER *pContext,
PNDIS_RESOURCE_LIST pResourceList)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
USHORT linkStatus = 0;
UCHAR CurrentMAC[ETH_LENGTH_OF_ADDRESS] = {0};
ULONG dependentOptions;
DEBUG_ENTRY(0);
ReadNicConfiguration(pContext, CurrentMAC);
pContext->fCurrentLinkState = MediaConnectStateUnknown;
pContext->powerState = NdisDeviceStateUnspecified;
pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS;
#if PARANDIS_SUPPORT_RSC
pContext->MaxPacketSize.nMaxDataSizeHwRx = MAX_HW_RX_PACKET_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = MAX_OS_RX_PACKET_SIZE;
#else
pContext->MaxPacketSize.nMaxDataSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
pContext->MaxPacketSize.nMaxFullSizeOsRx = pContext->MaxPacketSize.nMaxFullSizeOS;
#endif
if (pContext->ulPriorityVlanSetting)
pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
if (GetAdapterResources(pResourceList, &pContext->AdapterResources) &&
NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange(
&pContext->pIoPortOffset,
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength)
)
{
if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE)
{
DPrintf(0, ("[%s] Message interrupt assigned\n", __FUNCTION__));
pContext->bUsingMSIX = TRUE;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(*pContext->IODevice));
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER);
pContext->u32HostFeatures = VirtIODeviceReadHostFeatures(pContext->IODevice);
DumpVirtIOFeatures(pContext);
pContext->bLinkDetectSupported = AckFeature(pContext, VIRTIO_NET_F_STATUS);
if(pContext->bLinkDetectSupported) {
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0;
DPrintf(0, ("[%s] Link status on driver startup: %d\n", __FUNCTION__, pContext->bConnected));
}
InitializeMAC(pContext, CurrentMAC);
pContext->bUseMergedBuffers = AckFeature(pContext, VIRTIO_NET_F_MRG_RXBUF);
pContext->nVirtioHeaderSize = (pContext->bUseMergedBuffers) ? sizeof(virtio_net_hdr_ext) : sizeof(virtio_net_hdr_basic);
pContext->bDoPublishIndices = AckFeature(pContext, VIRTIO_RING_F_EVENT_IDX);
}
else
{
DPrintf(0, ("[%s] Error: Incomplete resources\n", __FUNCTION__));
/* avoid deregistering if failed */
pContext->AdapterResources.ulIOAddress = 0;
status = NDIS_STATUS_RESOURCE_CONFLICT;
}
pContext->bMultiQueue = AckFeature(pContext, VIRTIO_NET_F_CTRL_MQ);
if (pContext->bMultiQueue)
{
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS + sizeof(USHORT), &pContext->nHardwareQueues,
sizeof(pContext->nHardwareQueues));
}
else
{
pContext->nHardwareQueues = 1;
}
dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum;
if((pContext->Offload.flagsValue & dependentOptions) && !AckFeature(pContext, VIRTIO_NET_F_CSUM))
{
DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload\n", __FUNCTION__) );
pContext->Offload.flagsValue &= ~dependentOptions;
}
pContext->bGuestChecksumSupported = AckFeature(pContext, VIRTIO_NET_F_GUEST_CSUM);
AckFeature(pContext, VIRTIO_NET_F_CTRL_VQ);
InitializeRSCState(pContext);
// now, after we checked the capabilities, we can initialize current
// configuration of offload tasks
ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
if (pContext->Offload.flags.fTxLso && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO4))
{
DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4\n");
}
if (pContext->Offload.flags.fTxLsov6 && !AckFeature(pContext, VIRTIO_NET_F_HOST_TSO6))
{
DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6");
}
pContext->bUseIndirect = AckFeature(pContext, VIRTIO_F_INDIRECT);
pContext->bAnyLaypout = AckFeature(pContext, VIRTIO_F_ANY_LAYOUT);
pContext->bHasHardwareFilters = AckFeature(pContext, VIRTIO_NET_F_CTRL_RX_EXTRA);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
NdisInitializeEvent(&pContext->ResetEvent);
DEBUG_EXIT_STATUS(0, status);
return status;
}
void ParaNdis_FreeRxBufferDescriptor(PARANDIS_ADAPTER *pContext, pRxNetDescriptor p)
{
ULONG i;
for(i = 0; i < p->PagesAllocated; i++)
{
ParaNdis_FreePhysicalMemory(pContext, &p->PhysicalPages[i]);
}
if(p->BufferSGArray) NdisFreeMemory(p->BufferSGArray, 0, 0);
if(p->PhysicalPages) NdisFreeMemory(p->PhysicalPages, 0, 0);
NdisFreeMemory(p, 0, 0);
}
/**********************************************************
Allocates maximum RX buffers for incoming packets
Buffers are chained in NetReceiveBuffers
Parameters:
context
***********************************************************/
void ParaNdis_DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa)
{
if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL);
*ppq = NULL;
if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa);
RtlZeroMemory(ppa, sizeof(*ppa));
}
#if PARANDIS_SUPPORT_RSS
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *pContext)
{
if (!pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] No MSIX, using 1 queue\n", __FUNCTION__));
return 1;
}
if (pContext->bMultiQueue)
{
DPrintf(0, ("[%s] Number of hardware queues = %d\n", __FUNCTION__, pContext->nHardwareQueues));
}
else
{
DPrintf(0, ("[%s] - CTRL_MQ not acked, # bindles set to 1\n", __FUNCTION__));
return 1;
}
ULONG lnProcessors;
#if NDIS_SUPPORT_NDIS620
lnProcessors = NdisGroupActiveProcessorCount(ALL_PROCESSOR_GROUPS);
#elif NDIS_SUPPORT_NDIS6
lnProcessors = NdisSystemProcessorCount();
#else
lnProcessors = 1;
#endif
ULONG lnMSIs = (pContext->pMSIXInfoTable->MessageCount - 1) / 2; /* RX/TX pairs + control queue*/
DPrintf(0, ("[%s] %lu CPUs reported\n", __FUNCTION__, lnProcessors));
DPrintf(0, ("[%s] %lu MSIs, %lu queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, lnMSIs));
USHORT nMSIs = USHORT(lnMSIs & 0xFFFF);
USHORT nProcessors = USHORT(lnProcessors & 0xFFFF);
DPrintf(0, ("[%s] %u CPUs reported\n", __FUNCTION__, nProcessors));
DPrintf(0, ("[%s] %lu MSIs, %u queues\n", __FUNCTION__, pContext->pMSIXInfoTable->MessageCount, nMSIs));
USHORT nBundles = (pContext->nHardwareQueues < nProcessors) ? pContext->nHardwareQueues : nProcessors;
nBundles = (nMSIs < nBundles) ? nMSIs : nBundles;
DPrintf(0, ("[%s] # of path bundles = %u\n", __FUNCTION__, nBundles));
return nBundles;
}
#else
static USHORT DetermineQueueNumber(PARANDIS_ADAPTER *)
{
return 1;
}
#endif
static NDIS_STATUS SetupDPCTarget(PARANDIS_ADAPTER *pContext)
{
ULONG i;
#if NDIS_SUPPORT_NDIS620
NDIS_STATUS status;
PROCESSOR_NUMBER procNumber;
#endif
for (i = 0; i < pContext->nPathBundles; i++)
{
#if NDIS_SUPPORT_NDIS620
status = KeGetProcessorNumberFromIndex(i, &procNumber);
if (status != NDIS_STATUS_SUCCESS)
{
DPrintf(0, ("[%s] - KeGetProcessorNumberFromIndex failed for index %lu - %d\n", __FUNCTION__, i, status));
return status;
}
ParaNdis_ProcessorNumberToGroupAffinity(&pContext->pPathBundles[i].rxPath.DPCAffinity, &procNumber);
pContext->pPathBundles[i].txPath.DPCAffinity = pContext->pPathBundles[i].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->pPathBundles[i].rxPath.DPCTargetProcessor = 1i64 << i;
pContext->pPathBundles[i].txPath.DPCTargetProcessor = pContext->pPathBundles[i].rxPath.DPCTargetProcessor;
#else
#error not supported
#endif
}
#if NDIS_SUPPORT_NDIS620
pContext->CXPath.DPCAffinity = pContext->pPathBundles[0].rxPath.DPCAffinity;
#elif NDIS_SUPPORT_NDIS6
pContext->CXPath.DPCTargetProcessor = pContext->pPathBundles[0].rxPath.DPCTargetProcessor;
#else
#error not yet defined
#endif
return NDIS_STATUS_SUCCESS;
}
#if PARANDIS_SUPPORT_RSS
NDIS_STATUS ParaNdis_SetupRSSQueueMap(PARANDIS_ADAPTER *pContext)
{
USHORT rssIndex, bundleIndex;
ULONG cpuIndex;
ULONG rssTableSize = pContext->RSSParameters.RSSScalingSettings.IndirectionTableSize / sizeof(PROCESSOR_NUMBER);
rssIndex = 0;
bundleIndex = 0;
USHORT *cpuIndexTable;
ULONG cpuNumbers;
cpuNumbers = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS);
cpuIndexTable = (USHORT *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, cpuNumbers * sizeof(*cpuIndexTable),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (cpuIndexTable == nullptr)
{
DPrintf(0, ("[%s] cpu index table allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(cpuIndexTable, sizeof(*cpuIndexTable) * cpuNumbers);
for (bundleIndex = 0; bundleIndex < pContext->nPathBundles; ++bundleIndex)
{
cpuIndex = pContext->pPathBundles[bundleIndex].rxPath.getCPUIndex();
if (cpuIndex == INVALID_PROCESSOR_INDEX)
{
DPrintf(0, ("[%s] Invalid CPU index for path %u\n", __FUNCTION__, bundleIndex));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else if (cpuIndex >= cpuNumbers)
{
DPrintf(0, ("[%s] CPU index %lu exceeds CPU range %lu\n", __FUNCTION__, cpuIndex, cpuNumbers));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SOFT_ERRORS;
}
else
{
cpuIndexTable[cpuIndex] = bundleIndex;
}
}
DPrintf(0, ("[%s] Entering, RSS table size = %lu, # of path bundles = %u. RSS2QueueLength = %u, RSS2QueueMap =0x%p\n",
__FUNCTION__, rssTableSize, pContext->nPathBundles,
pContext->RSS2QueueLength, pContext->RSS2QueueMap));
if (pContext->RSS2QueueLength && pContext->RSS2QueueLength < rssTableSize)
{
DPrintf(0, ("[%s] Freeing RSS2Queue Map\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueLength = 0;
}
if (!pContext->RSS2QueueLength)
{
pContext->RSS2QueueLength = USHORT(rssTableSize);
pContext->RSS2QueueMap = (CPUPathesBundle **)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, rssTableSize * sizeof(*pContext->RSS2QueueMap),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->RSS2QueueMap == nullptr)
{
DPrintf(0, ("[%s] - Allocating RSS to queue mapping failed\n", __FUNCTION__));
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_RESOURCES;
}
NdisZeroMemory(pContext->RSS2QueueMap, sizeof(*pContext->RSS2QueueMap) * pContext->RSS2QueueLength);
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles;
}
for (rssIndex = 0; rssIndex < rssTableSize; rssIndex++)
{
cpuIndex = NdisProcessorNumberToIndex(pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex]);
bundleIndex = cpuIndexTable[cpuIndex];
DPrintf(3, ("[%s] filling the relationship, rssIndex = %u, bundleIndex = %u\n", __FUNCTION__, rssIndex, bundleIndex));
DPrintf(3, ("[%s] RSS proc number %u/%u, bundle affinity %u/%u\n", __FUNCTION__,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Group,
pContext->RSSParameters.RSSScalingSettings.IndirectionTable[rssIndex].Number,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Group,
pContext->pPathBundles[bundleIndex].txPath.DPCAffinity.Mask));
pContext->RSS2QueueMap[rssIndex] = pContext->pPathBundles + bundleIndex;
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, cpuIndexTable, PARANDIS_MEMORY_TAG);
return NDIS_STATUS_SUCCESS;
}
#endif
/**********************************************************
Initializes VirtIO buffering and related stuff:
Allocates RX and TX queues and buffers
Parameters:
context
Return value:
TRUE if both queues are allocated
***********************************************************/
static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_RESOURCES;
DEBUG_ENTRY(0);
UINT i;
USHORT nVirtIOQueues = pContext->nHardwareQueues * 2 + 2;
pContext->nPathBundles = DetermineQueueNumber(pContext);
if (pContext->nPathBundles == 0)
{
DPrintf(0, ("[%s] - no I/O pathes\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
if (nVirtIOQueues > pContext->IODevice->maxQueues)
{
ULONG IODeviceSize = VirtIODeviceSizeRequired(nVirtIOQueues);
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = (VirtIODevice *)NdisAllocateMemoryWithTagPriority(
pContext->MiniportHandle,
IODeviceSize,
PARANDIS_MEMORY_TAG,
NormalPoolPriority);
if (pContext->IODevice == nullptr)
{
DPrintf(0, ("[%s] - IODevice allocation failed\n", __FUNCTION__));
return NDIS_STATUS_RESOURCES;
}
VirtIODeviceInitialize(pContext->IODevice, pContext->AdapterResources.ulIOAddress, IODeviceSize);
VirtIODeviceSetMSIXUsed(pContext->IODevice, pContext->bUsingMSIX ? true : false);
DPrintf(0, ("[%s] %u queues' slots reallocated for size %lu\n", __FUNCTION__, pContext->IODevice->maxQueues, IODeviceSize));
}
new (&pContext->CXPath, PLACEMENT_NEW) CParaNdisCX();
pContext->bCXPathAllocated = TRUE;
if (!pContext->CXPath.Create(pContext, 2 * pContext->nHardwareQueues))
{
DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__));
pContext->bHasHardwareFilters = FALSE;
pContext->bCtrlMACAddrSupported = FALSE;
}
else
{
pContext->bCXPathCreated = TRUE;
}
pContext->pPathBundles = (CPUPathesBundle *)NdisAllocateMemoryWithTagPriority(pContext->MiniportHandle, pContext->nPathBundles * sizeof(*pContext->pPathBundles),
PARANDIS_MEMORY_TAG, NormalPoolPriority);
if (pContext->pPathBundles == nullptr)
{
DPrintf(0, ("[%s] Path bundles allocation failed\n", __FUNCTION__));
return status;
}
for (i = 0; i < pContext->nPathBundles; i++)
{
new (pContext->pPathBundles + i, PLACEMENT_NEW) CPUPathesBundle();
if (!pContext->pPathBundles[i].rxPath.Create(pContext, i * 2))
{
DPrintf(0, ("%s: CParaNdisRX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].rxCreated = true;
if (!pContext->pPathBundles[i].txPath.Create(pContext, i * 2 + 1))
{
DPrintf(0, ("%s: CParaNdisTX creation failed\n", __FUNCTION__));
return status;
}
pContext->pPathBundles[i].txCreated = true;
}
if (pContext->bCXPathCreated)
{
pContext->pPathBundles[0].cxPath = &pContext->CXPath;
}
status = NDIS_STATUS_SUCCESS;
return status;
}
static void ReadLinkState(PARANDIS_ADAPTER *pContext)
{
if (pContext->bLinkDetectSupported)
{
USHORT linkStatus = 0;
VirtIODeviceGet(pContext->IODevice, ETH_LENGTH_OF_ADDRESS, &linkStatus, sizeof(linkStatus));
pContext->bConnected = !!(linkStatus & VIRTIO_NET_S_LINK_UP);
}
else
{
pContext->bConnected = TRUE;
}
}
static void ParaNdis_RemoveDriverOKStatus(PPARANDIS_ADAPTER pContext )
{
VirtIODeviceRemoveStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
KeMemoryBarrier();
pContext->bDeviceInitialized = FALSE;
}
static VOID ParaNdis_AddDriverOKStatus(PPARANDIS_ADAPTER pContext)
{
pContext->bDeviceInitialized = TRUE;
KeMemoryBarrier();
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
}
/**********************************************************
Finishes initialization of context structure, calling also version dependent part
If this procedure failed, ParaNdis_CleanupContext must be called
Parameters:
context
Return value:
SUCCESS or some kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
DEBUG_ENTRY(0);
status = ParaNdis_FinishSpecificInitialization(pContext);
DPrintf(0, ("[%s] ParaNdis_FinishSpecificInitialization passed, status = %d\n", __FUNCTION__, status));
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_VirtIONetInit(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = ParaNdis_ConfigureMSIXVectors(pContext);
DPrintf(0, ("[%s] ParaNdis_VirtIONetInit passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS)
{
status = SetupDPCTarget(pContext);
DPrintf(0, ("[%s] SetupDPCTarget passed, status = %d\n", __FUNCTION__, status));
}
if (status == NDIS_STATUS_SUCCESS && pContext->nPathBundles > 1)
{
u16 nPathes = u16(pContext->nPathBundles);
BOOLEAN sendSuccess = pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MQ, VIRTIO_NET_CTRL_MQ_VQ_PAIR_SET, &nPathes, sizeof(nPathes), NULL, 0, 2);
if (!sendSuccess)
{
DPrintf(0, ("[%s] - Send MQ control message failed\n", __FUNCTION__));
status = NDIS_STATUS_DEVICE_FAILED;
}
}
pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1;
if (status == NDIS_STATUS_SUCCESS)
{
ReadLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
ParaNdis_AddDriverOKStatus(pContext);
ParaNdis_UpdateMAC(pContext);
}
DEBUG_EXIT_STATUS(0, status);
return status;
}
/**********************************************************
Releases VirtIO related resources - queues and buffers
Parameters:
context
Return value:
***********************************************************/
static void VirtIONetRelease(PARANDIS_ADAPTER *pContext)
{
BOOLEAN b;
ULONG i;
DEBUG_ENTRY(0);
/* list NetReceiveBuffersWaiting must be free */
for (i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
pRxNetDescriptor pBufferDescriptor;
while (NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pContext->ReceiveQueues + i)))
{
pBufferDescriptor->Queue->ReuseReceiveBuffer(FALSE, pBufferDescriptor);
}
}
do
{
b = pContext->m_upstreamPacketPending != 0;
if (b)
{
DPrintf(0, ("[%s] There are waiting buffers\n", __FUNCTION__));
PrintStatistics(pContext);
NdisMSleep(5000000);
}
} while (b);
RestoreMAC(pContext);
for (i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txCreated)
{
pContext->pPathBundles[i].txPath.Shutdown();
}
if (pContext->pPathBundles[i].rxCreated)
{
pContext->pPathBundles[i].rxPath.Shutdown();
/* this can be freed, queue shut down */
pContext->pPathBundles[i].rxPath.FreeRxDescriptorsFromList();
}
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
PrintStatistics(pContext);
}
static void PreventDPCServicing(PARANDIS_ADAPTER *pContext)
{
LONG inside;
pContext->bEnableInterruptHandlingDPC = FALSE;
KeMemoryBarrier();
do
{
inside = InterlockedIncrement(&pContext->counterDPCInside);
InterlockedDecrement(&pContext->counterDPCInside);
if (inside > 1)
{
DPrintf(0, ("[%s] waiting!\n", __FUNCTION__));
NdisMSleep(20000);
}
} while (inside > 1);
}
/**********************************************************
Frees all the resources allocated when the context initialized,
calling also version-dependent part
Parameters:
context
***********************************************************/
VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext)
{
/* disable any interrupt generation */
if (pContext->IODevice->addr)
{
if (pContext->bDeviceInitialized)
{
ParaNdis_RemoveDriverOKStatus(pContext);
}
}
PreventDPCServicing(pContext);
/****************************************
ensure all the incoming packets returned,
free all the buffers and their descriptors
*****************************************/
if (pContext->IODevice->addr)
{
ParaNdis_ResetVirtIONetDevice(pContext);
}
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
VirtIONetRelease(pContext);
ParaNdis_FinalizeCleanup(pContext);
if (pContext->ReceiveQueuesInitialized)
{
ULONG i;
for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
NdisFreeSpinLock(&pContext->ReceiveQueues[i].Lock);
}
}
pContext->m_PauseLock.~CNdisRWLock();
#if PARANDIS_SUPPORT_RSS
if (pContext->bRSSInitialized)
{
ParaNdis6_RSSCleanupConfiguration(&pContext->RSSParameters);
}
pContext->RSSParameters.rwLock.~CNdisRWLock();
#endif
if (pContext->bCXPathAllocated)
{
pContext->CXPath.~CParaNdisCX();
pContext->bCXPathAllocated = false;
}
if (pContext->pPathBundles != NULL)
{
USHORT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].~CPUPathesBundle();
}
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->pPathBundles, PARANDIS_MEMORY_TAG);
pContext->pPathBundles = nullptr;
}
if (pContext->RSS2QueueMap)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->RSS2QueueMap, PARANDIS_MEMORY_TAG);
pContext->RSS2QueueMap = nullptr;
pContext->RSS2QueueLength = 0;
}
if (pContext->IODevice)
{
NdisFreeMemoryWithTagPriority(pContext->MiniportHandle, pContext->IODevice, PARANDIS_MEMORY_TAG);
pContext->IODevice = nullptr;
}
if (pContext->AdapterResources.ulIOAddress)
{
NdisMDeregisterIoPortRange(
pContext->MiniportHandle,
pContext->AdapterResources.ulIOAddress,
pContext->AdapterResources.IOLength,
pContext->pIoPortOffset);
pContext->AdapterResources.ulIOAddress = 0;
}
}
/**********************************************************
System shutdown handler (shutdown, restart, bugcheck)
Parameters:
context
***********************************************************/
VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0); // this is only for kdbg :)
ParaNdis_ResetVirtIONetDevice(pContext);
}
static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo)
{
ULONG i;
if (pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
if ((pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx) && !pPacketInfo->hasVlanHeader)
return FALSE;
if (IsVlanSupported(pContext) && pPacketInfo->hasVlanHeader)
{
if (pContext->VlanId && pContext->VlanId != pPacketInfo->Vlan.VlanId)
{
return FALSE;
}
}
if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS)
return TRUE;
if(pPacketInfo->isUnicast)
{
ULONG Res;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED))
return FALSE;
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, pContext->CurrentMacAddress, &Res);
return !Res;
}
if(pPacketInfo->isBroadcast)
return (pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST);
// Multi-cast
if(pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST)
return TRUE;
if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST))
return FALSE;
for (i = 0; i < pContext->MulticastData.nofMulticastEntries; i++)
{
ULONG Res;
PUCHAR CurrMcastAddr = &pContext->MulticastData.MulticastList[i*ETH_LENGTH_OF_ADDRESS];
ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, CurrMcastAddr, &Res);
if(!Res)
return TRUE;
}
return FALSE;
}
BOOLEAN ParaNdis_PerformPacketAnalyzis(
#if PARANDIS_SUPPORT_RSS
PPARANDIS_RSS_PARAMS RSSParameters,
#endif
PNET_PACKET_INFO PacketInfo,
PVOID HeadersBuffer,
ULONG DataLength)
{
if(!ParaNdis_AnalyzeReceivedPacket(HeadersBuffer, DataLength, PacketInfo))
return FALSE;
#if PARANDIS_SUPPORT_RSS
if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED)
{
ParaNdis6_RSSAnalyzeReceivedPacket(RSSParameters, HeadersBuffer, PacketInfo);
}
#endif
return TRUE;
}
VOID ParaNdis_ProcessorNumberToGroupAffinity(PGROUP_AFFINITY Affinity, const PPROCESSOR_NUMBER Processor)
{
Affinity->Group = Processor->Group;
Affinity->Mask = 1;
Affinity->Mask <<= Processor->Number;
}
CCHAR ParaNdis_GetScalingDataForPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo, PPROCESSOR_NUMBER pTargetProcessor)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetScalingDataForPacket(&pContext->RSSParameters, pPacketInfo, pTargetProcessor);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(pPacketInfo);
UNREFERENCED_PARAMETER(pTargetProcessor);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
static __inline
CCHAR GetReceiveQueueForCurrentCPU(PARANDIS_ADAPTER *pContext)
{
#if PARANDIS_SUPPORT_RSS
return ParaNdis6_RSSGetCurrentCpuReceiveQueue(&pContext->RSSParameters);
#else
UNREFERENCED_PARAMETER(pContext);
return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED;
#endif
}
VOID ParaNdis_QueueRSSDpc(PARANDIS_ADAPTER *pContext, ULONG MessageIndex, PGROUP_AFFINITY pTargetAffinity)
{
#if PARANDIS_SUPPORT_RSS
NdisMQueueDpcEx(pContext->InterruptHandle, MessageIndex, pTargetAffinity, NULL);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(MessageIndex);
UNREFERENCED_PARAMETER(pTargetAffinity);
ASSERT(FALSE);
#endif
}
VOID ParaNdis_ReceiveQueueAddBuffer(PPARANDIS_RECEIVE_QUEUE pQueue, pRxNetDescriptor pBuffer)
{
NdisInterlockedInsertTailList( &pQueue->BuffersList,
&pBuffer->ReceiveQueueListEntry,
&pQueue->Lock);
}
VOID ParaMdis_TestPausing(PARANDIS_ADAPTER *pContext)
{
ONPAUSECOMPLETEPROC callback = nullptr;
if (pContext->m_upstreamPacketPending == 0)
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
if (pContext->m_upstreamPacketPending == 0 && (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc))
{
callback = pContext->ReceivePauseCompletionProc;
pContext->ReceiveState = srsDisabled;
pContext->ReceivePauseCompletionProc = NULL;
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
}
}
if (callback) callback(pContext);
}
static __inline
pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue)
{
PLIST_ENTRY pListEntry = NdisInterlockedRemoveHeadList(&pQueue->BuffersList, &pQueue->Lock);
return pListEntry ? CONTAINING_RECORD(pListEntry, RxNetDescriptor, ReceiveQueueListEntry) : NULL;
}
static __inline
BOOLEAN ReceiveQueueHasBuffers(PPARANDIS_RECEIVE_QUEUE pQueue)
{
BOOLEAN res;
NdisAcquireSpinLock(&pQueue->Lock);
res = !IsListEmpty(&pQueue->BuffersList);
NdisReleaseSpinLock(&pQueue->Lock);
return res;
}
static VOID
UpdateReceiveSuccessStatistics(PPARANDIS_ADAPTER pContext,
PNET_PACKET_INFO pPacketInfo,
UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifHCInOctets += pPacketInfo->dataLength;
if(pPacketInfo->isUnicast)
{
pContext->Statistics.ifHCInUcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInUcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isBroadcast)
{
pContext->Statistics.ifHCInBroadcastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInBroadcastOctets += pPacketInfo->dataLength;
}
else if (pPacketInfo->isMulticast)
{
pContext->Statistics.ifHCInMulticastPkts += nCoalescedSegmentsCount;
pContext->Statistics.ifHCInMulticastOctets += pPacketInfo->dataLength;
}
else
{
ASSERT(FALSE);
}
}
static __inline VOID
UpdateReceiveFailStatistics(PPARANDIS_ADAPTER pContext, UINT nCoalescedSegmentsCount)
{
pContext->Statistics.ifInErrors++;
pContext->Statistics.ifInDiscards += nCoalescedSegmentsCount;
}
static BOOLEAN ProcessReceiveQueue(PARANDIS_ADAPTER *pContext,
PULONG pnPacketsToIndicateLeft,
CCHAR nQueueIndex,
PNET_BUFFER_LIST *indicate,
PNET_BUFFER_LIST *indicateTail,
ULONG *nIndicate)
{
pRxNetDescriptor pBufferDescriptor;
PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex];
if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1)
{
while( (*pnPacketsToIndicateLeft > 0) &&
(NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) )
{
PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo;
if( !pContext->bSurprizeRemoved &&
pContext->ReceiveState == srsEnabled &&
pContext->bConnected &&
ShallPassPacket(pContext, pPacketInfo))
{
UINT nCoalescedSegmentsCount;
PNET_BUFFER_LIST packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor, &nCoalescedSegmentsCount);
if(packet != NULL)
{
UpdateReceiveSuccessStatistics(pContext, pPacketInfo, nCoalescedSegmentsCount);
if (*indicate == nullptr)
{
*indicate = *indicateTail = packet;
}
else
{
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = packet;
*indicateTail = packet;
}
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = NULL;
(*pnPacketsToIndicateLeft)--;
(*nIndicate)++;
}
else
{
UpdateReceiveFailStatistics(pContext, nCoalescedSegmentsCount);
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
else
{
pContext->extraStatistics.framesFilteredOut++;
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
}
NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount);
return ReceiveQueueHasBuffers(pTargetReceiveQueue);
}
static
BOOLEAN RxDPCWorkBody(PARANDIS_ADAPTER *pContext, CPUPathesBundle *pathBundle, ULONG nPacketsToIndicate)
{
BOOLEAN res = FALSE;
BOOLEAN bMoreDataInRing;
PNET_BUFFER_LIST indicate, indicateTail;
ULONG nIndicate;
CCHAR CurrCpuReceiveQueue = GetReceiveQueueForCurrentCPU(pContext);
do
{
indicate = nullptr;
indicateTail = nullptr;
nIndicate = 0;
{
CNdisDispatchReadAutoLock tLock(pContext->m_PauseLock);
pathBundle->rxPath.ProcessRxRing(CurrCpuReceiveQueue);
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED,
&indicate, &indicateTail, &nIndicate);
if(CurrCpuReceiveQueue != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED)
{
res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, CurrCpuReceiveQueue,
&indicate, &indicateTail, &nIndicate);
}
bMoreDataInRing = pathBundle->rxPath.RestartQueue();
}
if (nIndicate)
{
NdisMIndicateReceiveNetBufferLists(pContext->MiniportHandle,
indicate,
0,
nIndicate,
0);
}
ParaMdis_TestPausing(pContext);
} while (bMoreDataInRing);
return res;
}
bool ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate)
{
bool stillRequiresProcessing = false;
UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC);
DEBUG_ENTRY(5);
InterlockedIncrement(&pContext->counterDPCInside);
CPUPathesBundle *pathBundle = nullptr;
if (pContext->nPathBundles == 1)
{
pathBundle = pContext->pPathBundles;
}
else
{
ULONG procNumber = KeGetCurrentProcessorNumber();
if (procNumber < pContext->nPathBundles)
{
pathBundle = pContext->pPathBundles + procNumber;
}
}
if (pathBundle == nullptr)
{
return false;
}
if (pContext->bEnableInterruptHandlingDPC)
{
bool bDoKick = false;
InterlockedExchange(&pContext->bDPCInactive, 0);
if (RxDPCWorkBody(pContext, pathBundle, numOfPacketsToIndicate))
{
stillRequiresProcessing = true;
}
if (pContext->CXPath.WasInterruptReported() && pContext->bLinkDetectSupported)
{
ReadLinkState(pContext);
ParaNdis_SynchronizeLinkState(pContext);
pContext->CXPath.ClearInterruptReport();
}
if (!stillRequiresProcessing)
{
bDoKick = pathBundle->txPath.DoPendingTasks(true);
if (pathBundle->txPath.RestartQueue(bDoKick))
{
stillRequiresProcessing = true;
}
}
}
InterlockedDecrement(&pContext->counterDPCInside);
return stillRequiresProcessing;
}
VOID ParaNdis_ResetRxClassification(PARANDIS_ADAPTER *pContext)
{
ULONG i;
PPARANDIS_RECEIVE_QUEUE pUnclassified = &pContext->ReceiveQueues[PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED];
NdisAcquireSpinLock(&pUnclassified->Lock);
for(i = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED + 1; i < ARRAYSIZE(pContext->ReceiveQueues); i++)
{
PPARANDIS_RECEIVE_QUEUE pCurrQueue = &pContext->ReceiveQueues[i];
NdisAcquireSpinLock(&pCurrQueue->Lock);
while(!IsListEmpty(&pCurrQueue->BuffersList))
{
PLIST_ENTRY pListEntry = RemoveHeadList(&pCurrQueue->BuffersList);
InsertTailList(&pUnclassified->BuffersList, pListEntry);
}
NdisReleaseSpinLock(&pCurrQueue->Lock);
}
NdisReleaseSpinLock(&pUnclassified->Lock);
}
/**********************************************************
Periodically called procedure, checking dpc activity
If DPC are not running, it does exactly the same that the DPC
Parameters:
context
***********************************************************/
static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext)
{
BOOLEAN bStopped;
BOOLEAN bReportHang = FALSE;
bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE);
if (bStopped)
{
pContext->nDetectedInactivity++;
}
else
{
pContext->nDetectedInactivity = 0;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
if (pContext->pPathBundles[i].txPath.HasHWBuffersIsUse())
{
if (pContext->nDetectedStoppedTx++ > 1)
{
DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!\n", __FUNCTION__, pContext->pPathBundles[i].txPath.GetFreeHWBuffers()));
//bReportHang = TRUE;
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 0);
#endif
break;
}
}
}
if (pContext->Limits.nPrintDiagnostic &&
++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic)
{
pContext->Counters.nPrintDiagnostic = 0;
// todo - collect more and put out optionally
PrintStatistics(pContext);
}
if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn)
{
pContext->Counters.nRxInactivity++;
if (pContext->Counters.nRxInactivity >= 10)
{
#if defined(CRASH_ON_NO_RX)
ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1;
proc(pContext);
#endif
}
}
else
{
pContext->Counters.nRxInactivity = 0;
pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets;
}
return bReportHang;
}
/**********************************************************
Common implementation of periodic poll
Parameters:
context
Return:
TRUE, if reset required
***********************************************************/
BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext)
{
static int nHangOn = 0;
BOOLEAN b = nHangOn >= 3 && nHangOn < 6;
DEBUG_ENTRY(3);
b |= CheckRunningDpc(pContext);
//uncomment to cause 3 consecutive resets
//nHangOn++;
DEBUG_EXIT_STATUS(b ? 0 : 6, b);
return b;
}
/////////////////////////////////////////////////////////////////////////////////////
//
// ReadVirtIODeviceRegister\WriteVirtIODeviceRegister
// NDIS specific implementation of the IO space read\write
//
/////////////////////////////////////////////////////////////////////////////////////
u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister)
{
ULONG ulValue;
NdisRawReadPortUlong(ulRegister, &ulValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
return ulValue;
}
void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, ulValue) );
NdisRawWritePortUlong(ulRegister, ulValue);
}
u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister)
{
u8 bValue;
NdisRawReadPortUchar(ulRegister, &bValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
return bValue;
}
void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue)
{
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, bValue) );
NdisRawWritePortUchar(ulRegister, bValue);
}
u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister)
{
u16 wValue;
NdisRawReadPortUshort(ulRegister, &wValue);
DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
return wValue;
}
void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue)
{
#if 1
NdisRawWritePortUshort(ulRegister, wValue);
#else
// test only to cause long TX waiting queue of NDIS packets
// to recognize it and request for reset via Hang handler
static int nCounterToFail = 0;
static const int StartFail = 200, StopFail = 600;
BOOLEAN bFail = FALSE;
DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
if ((ulRegister & 0x1F) == 0x10)
{
nCounterToFail++;
bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail;
}
if (!bFail) NdisRawWritePortUshort(ulRegister, wValue);
else
{
DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) );
}
#endif
}
/**********************************************************
Common handler of multicast address configuration
Parameters:
PVOID Buffer array of addresses from NDIS
ULONG BufferSize size of incoming buffer
PUINT pBytesRead update on success
PUINT pBytesNeeded update on wrong buffer size
Return value:
SUCCESS or kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_SetMulticastList(
PARANDIS_ADAPTER *pContext,
PVOID Buffer,
ULONG BufferSize,
PUINT pBytesRead,
PUINT pBytesNeeded)
{
NDIS_STATUS status;
ULONG length = BufferSize;
if (length > sizeof(pContext->MulticastData.MulticastList))
{
status = NDIS_STATUS_MULTICAST_FULL;
*pBytesNeeded = sizeof(pContext->MulticastData.MulticastList);
}
else if (length % ETH_LENGTH_OF_ADDRESS)
{
status = NDIS_STATUS_INVALID_LENGTH;
*pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS;
}
else
{
NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList));
if (length)
NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length);
pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS;
DPrintf(1, ("[%s] New multicast list of %d bytes\n", __FUNCTION__, length));
*pBytesRead = length;
status = NDIS_STATUS_SUCCESS;
}
return status;
}
/**********************************************************
Common handler of PnP events
Parameters:
Return value:
***********************************************************/
VOID ParaNdis_OnPnPEvent(
PARANDIS_ADAPTER *pContext,
NDIS_DEVICE_PNP_EVENT pEvent,
PVOID pInfo,
ULONG ulSize)
{
const char *pName = "";
UNREFERENCED_PARAMETER(pInfo);
UNREFERENCED_PARAMETER(ulSize);
DEBUG_ENTRY(0);
#undef MAKECASE
#define MAKECASE(x) case (x): pName = #x; break;
switch (pEvent)
{
MAKECASE(NdisDevicePnPEventQueryRemoved)
MAKECASE(NdisDevicePnPEventRemoved)
MAKECASE(NdisDevicePnPEventSurpriseRemoved)
MAKECASE(NdisDevicePnPEventQueryStopped)
MAKECASE(NdisDevicePnPEventStopped)
MAKECASE(NdisDevicePnPEventPowerProfileChanged)
MAKECASE(NdisDevicePnPEventFilterListChanged)
default:
break;
}
ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0);
DPrintf(0, ("[%s] (%s)\n", __FUNCTION__, pName));
if (pEvent == NdisDevicePnPEventSurpriseRemoved)
{
// on simulated surprise removal (under PnpTest) we need to reset the device
// to prevent any access of device queues to memory buffers
pContext->bSurprizeRemoved = TRUE;
ParaNdis_ResetVirtIONetDevice(pContext);
{
UINT i;
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Pause();
}
}
}
pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent;
if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0]))
pContext->nPnpEventIndex = 0;
}
static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext)
{
u8 val;
ULONG f = pContext->PacketFilter;
val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2);
//SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2);
val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2);
}
static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext)
{
u32 u32UniCastEntries = 0;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET,
&u32UniCastEntries,
sizeof(u32UniCastEntries),
&pContext->MulticastData,
sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS,
2);
}
static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK)
{
u16 val = vlanId & 0xfff;
UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK);
}
static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn)
{
ULONG i;
for (i = 0; i <= MAX_VLAN_ID; ++i)
SetSingleVlanFilter(pContext, i, bOn, 7);
}
/*
possible values of filter set (pContext->ulCurrentVlansFilterSet):
0 - all disabled
1..4095 - one selected enabled
4096 - all enabled
Note that only 0th vlan can't be enabled
*/
VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ULONG newFilterSet;
if (IsVlanSupported(pContext))
newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1);
else
newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0;
if (newFilterSet != pContext->ulCurrentVlansFilterSet)
{
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, FALSE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2);
pContext->ulCurrentVlansFilterSet = newFilterSet;
if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
SetAllVlanFilters(pContext, TRUE);
else if (pContext->ulCurrentVlansFilterSet)
SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2);
}
}
}
VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext)
{
if (pContext->bHasHardwareFilters)
{
ParaNdis_DeviceFiltersUpdateRxMode(pContext);
ParaNdis_DeviceFiltersUpdateAddresses(pContext);
ParaNdis_DeviceFiltersUpdateVlanId(pContext);
}
}
static VOID
ParaNdis_UpdateMAC(PARANDIS_ADAPTER *pContext)
{
if (pContext->bCtrlMACAddrSupported)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_ADDR_SET,
pContext->CurrentMacAddress,
ETH_LENGTH_OF_ADDRESS,
NULL, 0, 4);
}
}
#if PARANDIS_SUPPORT_RSC
VOID
ParaNdis_UpdateGuestOffloads(PARANDIS_ADAPTER *pContext, UINT64 Offloads)
{
if (pContext->RSC.bHasDynamicConfig)
{
pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_GUEST_OFFLOADS, VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET,
&Offloads,
sizeof(Offloads),
NULL, 0, 2);
}
}
#endif
VOID ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext)
{
UINT i;
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0);
ParaNdis_ResetVirtIONetDevice(pContext);
VirtIODeviceAddStatus(pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER);
/* GetHostFeature must be called with any mask once upon device initialization:
otherwise the device will not work properly */
VirtIODeviceReadHostFeatures(pContext->IODevice);
VirtIODeviceWriteGuestFeatures(pContext->IODevice, pContext->u32GuestFeatures);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Renew();
pContext->pPathBundles[i].rxPath.Renew();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Renew();
}
ParaNdis_RestoreDeviceConfigurationAfterReset(pContext);
ParaNdis_UpdateDeviceFilters(pContext);
ParaNdis_UpdateMAC(pContext);
InterlockedExchange(&pContext->ReuseBufferRegular, TRUE);
for (i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].rxPath.PopulateQueue();
}
ReadLinkState(pContext);
ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
ParaNdis_SynchronizeLinkState(pContext);
pContext->bEnableInterruptHandlingDPC = TRUE;
ParaNdis_AddDriverOKStatus(pContext);
// if bFastSuspendInProcess is set by Win8 power-off procedure,
// the ParaNdis_Resume enables Tx and RX
// otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart)
ParaNdis_Resume(pContext);
pContext->bFastSuspendInProcess = FALSE;
ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0);
}
VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext)
{
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0);
pContext->bConnected = FALSE;
// if bFastSuspendInProcess is set by Win8 power-off procedure
// the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis)
pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled;
ParaNdis_Suspend(pContext);
ParaNdis_RemoveDriverOKStatus(pContext);
if (pContext->bFastSuspendInProcess)
{
InterlockedExchange(&pContext->ReuseBufferRegular, FALSE);
}
#if !NDIS_SUPPORT_NDIS620
// WLK tests for Windows 2008 require media disconnect indication
// on power off. HCK tests for newer versions require media state unknown
// indication only and fail on disconnect indication
ParaNdis_SetLinkState(pContext, MediaConnectStateDisconnected);
#endif
ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
ParaNdis_SetLinkState(pContext, MediaConnectStateUnknown);
PreventDPCServicing(pContext);
/*******************************************************************
shutdown queues to have all the receive buffers under our control
all the transmit buffers move to list of free buffers
********************************************************************/
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.Shutdown();
pContext->pPathBundles[i].rxPath.Shutdown();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.Shutdown();
}
ParaNdis_ResetVirtIONetDevice(pContext);
ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0);
}
void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext)
{
if (pContext->AdapterResources.ulIOAddress)
{
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
WriteVirtIODeviceByte(pContext->IODevice->addr + VIRTIO_PCI_ISR, 1);
#endif
}
}
tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res, resIp;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
resIp.value = 0;
//VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS
//VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1581_0 |
crossvul-cpp_data_good_2181_0 | /**
* Copyright (C) 2010 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/commands/authentication_commands.h"
#include <boost/scoped_ptr.hpp>
#include <string>
#include <vector>
#include "mongo/base/status.h"
#include "mongo/bson/mutable/algorithm.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/client/sasl_client_authenticate.h"
#include "mongo/db/audit.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_manager_global.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/mongo_authentication_session.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/auth/security_key.h"
#include "mongo/db/client_basic.h"
#include "mongo/db/commands.h"
#include "mongo/db/jsobj.h"
#include "mongo/platform/random.h"
#include "mongo/util/concurrency/mutex.h"
#include "mongo/util/md5.hpp"
#include "mongo/util/net/ssl_manager.h"
namespace mongo {
static bool _isCRAuthDisabled;
static bool _isX509AuthDisabled;
static const char _nonceAuthenticationDisabledMessage[] =
"Challenge-response authentication using getnonce and authenticate commands is disabled.";
static const char _x509AuthenticationDisabledMessage[] =
"x.509 authentication is disabled.";
void CmdAuthenticate::disableAuthMechanism(std::string authMechanism) {
if (authMechanism == "MONGODB-CR") {
_isCRAuthDisabled = true;
}
if (authMechanism == "MONGODB-X509") {
_isX509AuthDisabled = true;
}
}
/* authentication
system.users contains
{ user : <username>, pwd : <pwd_digest>, ... }
getnonce sends nonce to client
client then sends { authenticate:1, nonce64:<nonce_str>, user:<username>, key:<key> }
where <key> is md5(<nonce_str><username><pwd_digest_str>) as a string
*/
class CmdGetNonce : public Command {
public:
CmdGetNonce() :
Command("getnonce"),
_randMutex("getnonce"),
_random(SecureRandom::create()) {
}
virtual bool logTheOp() { return false; }
virtual bool slaveOk() const {
return true;
}
void help(stringstream& h) const { h << "internal"; }
virtual bool isWriteCommandForConfigServer() const { return false; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
bool run(const string&, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
nonce64 n = getNextNonce();
stringstream ss;
ss << hex << n;
result.append("nonce", ss.str() );
ClientBasic::getCurrent()->resetAuthenticationSession(
new MongoAuthenticationSession(n));
return true;
}
private:
nonce64 getNextNonce() {
SimpleMutex::scoped_lock lk(_randMutex);
return _random->nextInt64();
}
SimpleMutex _randMutex; // Synchronizes accesses to _random.
boost::scoped_ptr<SecureRandom> _random;
} cmdGetNonce;
void CmdAuthenticate::redactForLogging(mutablebson::Document* cmdObj) {
namespace mmb = mutablebson;
static const int numRedactedFields = 2;
static const char* redactedFields[numRedactedFields] = { "key", "nonce" };
for (int i = 0; i < numRedactedFields; ++i) {
for (mmb::Element element = mmb::findFirstChildNamed(cmdObj->root(), redactedFields[i]);
element.ok();
element = mmb::findElementNamed(element.rightSibling(), redactedFields[i])) {
element.setValueString("xxx");
}
}
}
bool CmdAuthenticate::run(const string& dbname,
BSONObj& cmdObj,
int,
string& errmsg,
BSONObjBuilder& result,
bool fromRepl) {
mutablebson::Document cmdToLog(cmdObj, mutablebson::Document::kInPlaceDisabled);
redactForLogging(&cmdToLog);
log() << " authenticate db: " << dbname << " " << cmdToLog << endl;
UserName user(cmdObj.getStringField("user"), dbname);
if (Command::testCommandsEnabled &&
user.getDB() == "admin" &&
user.getUser() == internalSecurity.user->getName().getUser()) {
// Allows authenticating as the internal user against the admin database. This is to
// support the auth passthrough test framework on mongos (since you can't use the local
// database on a mongos, so you can't auth as the internal user without this).
user = internalSecurity.user->getName();
}
std::string mechanism = cmdObj.getStringField("mechanism");
if (mechanism.empty()) {
mechanism = "MONGODB-CR";
}
Status status = _authenticate(mechanism, user, cmdObj);
audit::logAuthentication(ClientBasic::getCurrent(),
mechanism,
user,
status.code());
if (!status.isOK()) {
log() << "Failed to authenticate " << user << " with mechanism " << mechanism << ": " <<
status;
if (status.code() == ErrorCodes::AuthenticationFailed) {
// Statuses with code AuthenticationFailed may contain messages we do not wish to
// reveal to the user, so we return a status with the message "auth failed".
appendCommandStatus(result,
Status(ErrorCodes::AuthenticationFailed, "auth failed"));
}
else {
appendCommandStatus(result, status);
}
return false;
}
result.append("dbname", user.getDB());
result.append("user", user.getUser());
return true;
}
Status CmdAuthenticate::_authenticate(const std::string& mechanism,
const UserName& user,
const BSONObj& cmdObj) {
if (mechanism == "MONGODB-CR") {
return _authenticateCR(user, cmdObj);
}
#ifdef MONGO_SSL
if (mechanism == "MONGODB-X509") {
return _authenticateX509(user, cmdObj);
}
#endif
return Status(ErrorCodes::BadValue, "Unsupported mechanism: " + mechanism);
}
Status CmdAuthenticate::_authenticateCR(const UserName& user, const BSONObj& cmdObj) {
if (user == internalSecurity.user->getName() &&
serverGlobalParams.clusterAuthMode.load() ==
ServerGlobalParams::ClusterAuthMode_x509) {
return Status(ErrorCodes::AuthenticationFailed,
"Mechanism x509 is required for internal cluster authentication");
}
if (_isCRAuthDisabled) {
// SERVER-8461, MONGODB-CR must be enabled for authenticating the internal user, so that
// cluster members may communicate with each other.
if (user != internalSecurity.user->getName()) {
return Status(ErrorCodes::BadValue, _nonceAuthenticationDisabledMessage);
}
}
string key = cmdObj.getStringField("key");
string received_nonce = cmdObj.getStringField("nonce");
if( user.getUser().empty() || key.empty() || received_nonce.empty() ) {
sleepmillis(10);
return Status(ErrorCodes::ProtocolError,
"field missing/wrong type in received authenticate command");
}
stringstream digestBuilder;
{
ClientBasic *client = ClientBasic::getCurrent();
boost::scoped_ptr<AuthenticationSession> session;
client->swapAuthenticationSession(session);
if (!session || session->getType() != AuthenticationSession::SESSION_TYPE_MONGO) {
sleepmillis(30);
return Status(ErrorCodes::ProtocolError, "No pending nonce");
}
else {
nonce64 nonce = static_cast<MongoAuthenticationSession*>(session.get())->getNonce();
digestBuilder << hex << nonce;
if (digestBuilder.str() != received_nonce) {
sleepmillis(30);
return Status(ErrorCodes::AuthenticationFailed, "Received wrong nonce.");
}
}
}
User* userObj;
Status status = getGlobalAuthorizationManager()->acquireUser(user, &userObj);
if (!status.isOK()) {
// Failure to find the privilege document indicates no-such-user, a fact that we do not
// wish to reveal to the client. So, we return AuthenticationFailed rather than passing
// through the returned status.
return Status(ErrorCodes::AuthenticationFailed, status.toString());
}
string pwd = userObj->getCredentials().password;
getGlobalAuthorizationManager()->releaseUser(userObj);
md5digest d;
{
digestBuilder << user.getUser() << pwd;
string done = digestBuilder.str();
md5_state_t st;
md5_init(&st);
md5_append(&st, (const md5_byte_t *) done.c_str(), done.size());
md5_finish(&st, d);
}
string computed = digestToString( d );
if ( key != computed ) {
return Status(ErrorCodes::AuthenticationFailed, "key mismatch");
}
AuthorizationSession* authorizationSession =
ClientBasic::getCurrent()->getAuthorizationSession();
status = authorizationSession->addAndAuthorizeUser(user);
if (!status.isOK()) {
return status;
}
return Status::OK();
}
#ifdef MONGO_SSL
Status CmdAuthenticate::_authenticateX509(const UserName& user, const BSONObj& cmdObj) {
if (!getSSLManager()) {
return Status(ErrorCodes::ProtocolError,
"SSL support is required for the MONGODB-X509 mechanism.");
}
if(user.getDB() != "$external") {
return Status(ErrorCodes::ProtocolError,
"X.509 authentication must always use the $external database.");
}
ClientBasic *client = ClientBasic::getCurrent();
AuthorizationSession* authorizationSession = client->getAuthorizationSession();
std::string subjectName = client->port()->getX509SubjectName();
if (user.getUser() != subjectName) {
return Status(ErrorCodes::AuthenticationFailed,
"There is no x.509 client certificate matching the user.");
}
else {
std::string srvSubjectName = getSSLManager()->getServerSubjectName();
size_t srvClusterIdPos = srvSubjectName.find(",OU=");
size_t peerClusterIdPos = subjectName.find(",OU=");
std::string srvClusterId = srvClusterIdPos != std::string::npos ?
srvSubjectName.substr(srvClusterIdPos) : "";
std::string peerClusterId = peerClusterIdPos != std::string::npos ?
subjectName.substr(peerClusterIdPos) : "";
// Handle internal cluster member auth, only applies to server-server connections
int clusterAuthMode = serverGlobalParams.clusterAuthMode.load();
if (srvClusterId == peerClusterId && !srvClusterId.empty()) {
if (clusterAuthMode == ServerGlobalParams::ClusterAuthMode_undefined ||
clusterAuthMode == ServerGlobalParams::ClusterAuthMode_keyFile) {
return Status(ErrorCodes::AuthenticationFailed, "The provided certificate "
"can only be used for cluster authentication, not client "
"authentication. The current configuration does not allow "
"x.509 cluster authentication, check the --clusterAuthMode flag");
}
authorizationSession->grantInternalAuthorization();
}
// Handle normal client authentication, only applies to client-server connections
else {
if (_isX509AuthDisabled) {
return Status(ErrorCodes::BadValue,
_x509AuthenticationDisabledMessage);
}
Status status = authorizationSession->addAndAuthorizeUser(user);
if (!status.isOK()) {
return status;
}
}
return Status::OK();
}
}
#endif
CmdAuthenticate cmdAuthenticate;
class CmdLogout : public Command {
public:
virtual bool logTheOp() {
return false;
}
virtual bool slaveOk() const {
return true;
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
void help(stringstream& h) const { h << "de-authenticate"; }
virtual bool isWriteCommandForConfigServer() const { return false; }
CmdLogout() : Command("logout") {}
bool run(const string& dbname,
BSONObj& cmdObj,
int options,
string& errmsg,
BSONObjBuilder& result,
bool fromRepl) {
AuthorizationSession* authSession =
ClientBasic::getCurrent()->getAuthorizationSession();
authSession->logoutDatabase(dbname);
return true;
}
} cmdLogout;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_2181_0 |
crossvul-cpp_data_bad_847_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/mbstring/ext_mbstring.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/ini-setting.h"
#include "hphp/runtime/base/request-event-handler.h"
#include "hphp/runtime/base/string-buffer.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/runtime/base/zend-url.h"
#include "hphp/runtime/ext/mbstring/php_unicode.h"
#include "hphp/runtime/ext/mbstring/unicode_data.h"
#include "hphp/runtime/ext/std/ext_std_output.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "hphp/util/rds-local.h"
#include <map>
extern "C" {
#include <mbfl/mbfl_convert.h>
#include <mbfl/mbfilter.h>
#include <mbfl/mbfilter_pass.h>
#include <oniguruma.h>
}
#define php_mb_re_pattern_buffer re_pattern_buffer
#define php_mb_regex_t regex_t
#define php_mb_re_registers re_registers
extern void mbfl_memory_device_unput(mbfl_memory_device *device);
#define PARSE_POST 0
#define PARSE_GET 1
#define PARSE_COOKIE 2
#define PARSE_STRING 3
#define PARSE_ENV 4
#define PARSE_SERVER 5
#define PARSE_SESSION 6
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// statics
#define PHP_MBSTR_STACK_BLOCK_SIZE 32
typedef struct _php_mb_nls_ident_list {
mbfl_no_language lang;
mbfl_no_encoding* list;
int list_size;
} php_mb_nls_ident_list;
static mbfl_no_encoding php_mb_default_identify_list_ja[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_jis,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_jp,
mbfl_no_encoding_sjis
};
static mbfl_no_encoding php_mb_default_identify_list_cn[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_cn,
mbfl_no_encoding_cp936
};
static mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_tw,
mbfl_no_encoding_big5
};
static mbfl_no_encoding php_mb_default_identify_list_kr[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_kr,
mbfl_no_encoding_uhc
};
static mbfl_no_encoding php_mb_default_identify_list_ru[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_koi8r,
mbfl_no_encoding_cp1251,
mbfl_no_encoding_cp866
};
static mbfl_no_encoding php_mb_default_identify_list_hy[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_armscii8
};
static mbfl_no_encoding php_mb_default_identify_list_tr[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_8859_9
};
static mbfl_no_encoding php_mb_default_identify_list_neut[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8
};
static php_mb_nls_ident_list php_mb_default_identify_list[] = {
{ mbfl_no_language_japanese, php_mb_default_identify_list_ja,
sizeof(php_mb_default_identify_list_ja) /
sizeof(php_mb_default_identify_list_ja[0]) },
{ mbfl_no_language_korean, php_mb_default_identify_list_kr,
sizeof(php_mb_default_identify_list_kr) /
sizeof(php_mb_default_identify_list_kr[0]) },
{ mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk,
sizeof(php_mb_default_identify_list_tw_hk) /
sizeof(php_mb_default_identify_list_tw_hk[0]) },
{ mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn,
sizeof(php_mb_default_identify_list_cn) /
sizeof(php_mb_default_identify_list_cn[0]) },
{ mbfl_no_language_russian, php_mb_default_identify_list_ru,
sizeof(php_mb_default_identify_list_ru) /
sizeof(php_mb_default_identify_list_ru[0]) },
{ mbfl_no_language_armenian, php_mb_default_identify_list_hy,
sizeof(php_mb_default_identify_list_hy) /
sizeof(php_mb_default_identify_list_hy[0]) },
{ mbfl_no_language_turkish, php_mb_default_identify_list_tr,
sizeof(php_mb_default_identify_list_tr) /
sizeof(php_mb_default_identify_list_tr[0]) },
{ mbfl_no_language_neutral, php_mb_default_identify_list_neut,
sizeof(php_mb_default_identify_list_neut) /
sizeof(php_mb_default_identify_list_neut[0]) }
};
///////////////////////////////////////////////////////////////////////////////
// globals
typedef std::map<std::string, php_mb_regex_t *> RegexCache;
struct MBGlobals final : RequestEventHandler {
mbfl_no_language language;
mbfl_no_language current_language;
mbfl_encoding *internal_encoding;
mbfl_encoding *current_internal_encoding;
mbfl_encoding *http_output_encoding;
mbfl_encoding *current_http_output_encoding;
mbfl_encoding *http_input_identify;
mbfl_encoding *http_input_identify_get;
mbfl_encoding *http_input_identify_post;
mbfl_encoding *http_input_identify_cookie;
mbfl_encoding *http_input_identify_string;
mbfl_encoding **http_input_list;
int http_input_list_size;
mbfl_encoding **detect_order_list;
int detect_order_list_size;
mbfl_encoding **current_detect_order_list;
int current_detect_order_list_size;
mbfl_no_encoding *default_detect_order_list;
int default_detect_order_list_size;
int filter_illegal_mode;
int filter_illegal_substchar;
int current_filter_illegal_mode;
int current_filter_illegal_substchar;
bool encoding_translation;
long strict_detection;
long illegalchars;
mbfl_buffer_converter *outconv;
OnigEncoding default_mbctype;
OnigEncoding current_mbctype;
RegexCache ht_rc;
std::string search_str;
unsigned int search_pos;
php_mb_regex_t *search_re;
OnigRegion *search_regs;
OnigOptionType regex_default_options;
OnigSyntaxType *regex_default_syntax;
MBGlobals() :
language(mbfl_no_language_uni),
current_language(mbfl_no_language_uni),
internal_encoding((mbfl_encoding*) mbfl_no2encoding(mbfl_no_encoding_utf8)),
current_internal_encoding(internal_encoding),
http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass),
current_http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass),
http_input_identify(nullptr),
http_input_identify_get(nullptr),
http_input_identify_post(nullptr),
http_input_identify_cookie(nullptr),
http_input_identify_string(nullptr),
http_input_list(nullptr),
http_input_list_size(0),
detect_order_list(nullptr),
detect_order_list_size(0),
current_detect_order_list(nullptr),
current_detect_order_list_size(0),
default_detect_order_list
((mbfl_no_encoding *)php_mb_default_identify_list_neut),
default_detect_order_list_size
(sizeof(php_mb_default_identify_list_neut) /
sizeof(php_mb_default_identify_list_neut[0])),
filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR),
filter_illegal_substchar(0x3f), /* '?' */
current_filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR),
current_filter_illegal_substchar(0x3f), /* '?' */
encoding_translation(0),
strict_detection(0),
illegalchars(0),
outconv(nullptr),
default_mbctype(ONIG_ENCODING_UTF8),
current_mbctype(ONIG_ENCODING_UTF8),
search_pos(0),
search_re((php_mb_regex_t*)nullptr),
search_regs((OnigRegion*)nullptr),
regex_default_options(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE),
regex_default_syntax(ONIG_SYNTAX_RUBY) {
}
void requestInit() override {
current_language = language;
current_internal_encoding = internal_encoding;
current_http_output_encoding = http_output_encoding;
current_filter_illegal_mode = filter_illegal_mode;
current_filter_illegal_substchar = filter_illegal_substchar;
if (!encoding_translation) {
illegalchars = 0;
}
mbfl_encoding **entry = nullptr;
int n = 0;
if (current_detect_order_list) {
return;
}
if (detect_order_list && detect_order_list_size > 0) {
n = detect_order_list_size;
entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*));
std::copy(detect_order_list,
detect_order_list + (n * sizeof(mbfl_encoding*)), entry);
} else {
mbfl_no_encoding *src = default_detect_order_list;
n = default_detect_order_list_size;
entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*));
for (int i = 0; i < n; i++) {
entry[i] = (mbfl_encoding*) mbfl_no2encoding(src[i]);
}
}
current_detect_order_list = entry;
current_detect_order_list_size = n;
}
void requestShutdown() override {
if (current_detect_order_list != nullptr) {
req::free(current_detect_order_list);
current_detect_order_list = nullptr;
current_detect_order_list_size = 0;
}
if (outconv != nullptr) {
illegalchars += mbfl_buffer_illegalchars(outconv);
mbfl_buffer_converter_delete(outconv);
outconv = nullptr;
}
/* clear http input identification. */
http_input_identify = nullptr;
http_input_identify_post = nullptr;
http_input_identify_get = nullptr;
http_input_identify_cookie = nullptr;
http_input_identify_string = nullptr;
current_mbctype = default_mbctype;
search_str.clear();
search_pos = 0;
if (search_regs != nullptr) {
onig_region_free(search_regs, 1);
search_regs = (OnigRegion *)nullptr;
}
for (RegexCache::const_iterator it = ht_rc.begin(); it != ht_rc.end();
++it) {
onig_free(it->second);
}
ht_rc.clear();
}
};
IMPLEMENT_STATIC_REQUEST_LOCAL(MBGlobals, s_mb_globals);
#define MBSTRG(name) s_mb_globals->name
///////////////////////////////////////////////////////////////////////////////
// unicode functions
/*
* A simple array of 32-bit masks for lookup.
*/
static unsigned long masks32[32] = {
0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020,
0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800,
0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000,
0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000,
0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000,
0x40000000, 0x80000000
};
static int prop_lookup(unsigned long code, unsigned long n) {
long l, r, m;
/*
* There is an extra node on the end of the offsets to allow this routine
* to work right. If the index is 0xffff, then there are no nodes for the
* property.
*/
if ((l = _ucprop_offsets[n]) == 0xffff)
return 0;
/*
* Locate the next offset that is not 0xffff. The sentinel at the end of
* the array is the max index value.
*/
for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++)
;
r = _ucprop_offsets[n + m] - 1;
while (l <= r) {
/*
* Determine a "mid" point and adjust to make sure the mid point is at
* the beginning of a range pair.
*/
m = (l + r) >> 1;
m -= (m & 1);
if (code > _ucprop_ranges[m + 1])
l = m + 2;
else if (code < _ucprop_ranges[m])
r = m - 2;
else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1])
return 1;
}
return 0;
}
static int php_unicode_is_prop(unsigned long code, unsigned long mask1,
unsigned long mask2) {
unsigned long i;
if (mask1 == 0 && mask2 == 0)
return 0;
for (i = 0; mask1 && i < 32; i++) {
if ((mask1 & masks32[i]) && prop_lookup(code, i))
return 1;
}
for (i = 32; mask2 && i < _ucprop_size; i++) {
if ((mask2 & masks32[i & 31]) && prop_lookup(code, i))
return 1;
}
return 0;
}
static unsigned long case_lookup(unsigned long code, long l, long r,
int field) {
long m;
/*
* Do the binary search.
*/
while (l <= r) {
/*
* Determine a "mid" point and adjust to make sure the mid point is at
* the beginning of a case mapping triple.
*/
m = (l + r) >> 1;
m -= (m % 3);
if (code > _uccase_map[m])
l = m + 3;
else if (code < _uccase_map[m])
r = m - 3;
else if (code == _uccase_map[m])
return _uccase_map[m + field];
}
return code;
}
static unsigned long php_turkish_toupper(unsigned long code, long l, long r,
int field) {
if (code == 0x0069L) {
return 0x0130L;
}
return case_lookup(code, l, r, field);
}
static unsigned long php_turkish_tolower(unsigned long code, long l, long r,
int field) {
if (code == 0x0049L) {
return 0x0131L;
}
return case_lookup(code, l, r, field);
}
static unsigned long php_unicode_toupper(unsigned long code,
enum mbfl_no_encoding enc) {
int field;
long l, r;
if (php_unicode_is_upper(code))
return code;
if (php_unicode_is_lower(code)) {
/*
* The character is lower case.
*/
field = 2;
l = _uccase_len[0];
r = (l + _uccase_len[1]) - 3;
if (enc == mbfl_no_encoding_8859_9) {
return php_turkish_toupper(code, l, r, field);
}
} else {
/*
* The character is title case.
*/
field = 1;
l = _uccase_len[0] + _uccase_len[1];
r = _uccase_size - 3;
}
return case_lookup(code, l, r, field);
}
static unsigned long php_unicode_tolower(unsigned long code,
enum mbfl_no_encoding enc) {
int field;
long l, r;
if (php_unicode_is_lower(code))
return code;
if (php_unicode_is_upper(code)) {
/*
* The character is upper case.
*/
field = 1;
l = 0;
r = _uccase_len[0] - 3;
if (enc == mbfl_no_encoding_8859_9) {
return php_turkish_tolower(code, l, r, field);
}
} else {
/*
* The character is title case.
*/
field = 2;
l = _uccase_len[0] + _uccase_len[1];
r = _uccase_size - 3;
}
return case_lookup(code, l, r, field);
}
static unsigned long
php_unicode_totitle(unsigned long code, enum mbfl_no_encoding /*enc*/) {
int field;
long l, r;
if (php_unicode_is_title(code))
return code;
/*
* The offset will always be the same for converting to title case.
*/
field = 2;
if (php_unicode_is_upper(code)) {
/*
* The character is upper case.
*/
l = 0;
r = _uccase_len[0] - 3;
} else {
/*
* The character is lower case.
*/
l = _uccase_len[0];
r = (l + _uccase_len[1]) - 3;
}
return case_lookup(code, l, r, field);
}
#define BE_ARY_TO_UINT32(ptr) (\
((unsigned char*)(ptr))[0]<<24 |\
((unsigned char*)(ptr))[1]<<16 |\
((unsigned char*)(ptr))[2]<< 8 |\
((unsigned char*)(ptr))[3] )
#define UINT32_TO_BE_ARY(ptr,val) { \
unsigned int v = val; \
((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\
((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\
((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\
((unsigned char*)(ptr))[3] = (v ) & 0xff;\
}
/**
* Return 0 if input contains any illegal encoding, otherwise 1.
* Even if any illegal encoding is detected the result may contain a list
* of parsed encodings.
*/
static int php_mb_parse_encoding_list(const char* value, int value_length,
mbfl_encoding*** return_list,
int* return_size, int /*persistent*/) {
int n, l, size, bauto, ret = 1;
char *p, *p1, *p2, *endp, *tmpstr;
mbfl_encoding *encoding;
mbfl_no_encoding *src;
mbfl_encoding **entry, **list;
list = nullptr;
if (value == nullptr || value_length <= 0) {
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
return 0;
} else {
mbfl_no_encoding *identify_list;
int identify_list_size;
identify_list = MBSTRG(default_detect_order_list);
identify_list_size = MBSTRG(default_detect_order_list_size);
/* copy the value string for work */
if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) {
tmpstr = req::strndup(value + 1, value_length - 2);
} else {
tmpstr = req::strndup(value, value_length);
}
value_length = tmpstr ? strlen(tmpstr) : 0;
if (!value_length) {
req::free(tmpstr);
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
return 0;
}
/* count the number of listed encoding names */
endp = tmpstr + value_length;
n = 1;
p1 = tmpstr;
while ((p2 = (char*)string_memnstr(p1, ",", 1, endp)) != nullptr) {
p1 = p2 + 1;
n++;
}
size = n + identify_list_size;
/* make list */
list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*));
if (list != nullptr) {
entry = list;
n = 0;
bauto = 0;
p1 = tmpstr;
do {
p2 = p = (char*)string_memnstr(p1, ",", 1, endp);
if (p == nullptr) {
p = endp;
}
*p = '\0';
/* trim spaces */
while (p1 < p && (*p1 == ' ' || *p1 == '\t')) {
p1++;
}
p--;
while (p > p1 && (*p == ' ' || *p == '\t')) {
*p = '\0';
p--;
}
/* convert to the encoding number and check encoding */
if (strcasecmp(p1, "auto") == 0) {
if (!bauto) {
bauto = 1;
l = identify_list_size;
src = identify_list;
for (int i = 0; i < l; i++) {
*entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++);
n++;
}
}
} else {
encoding = (mbfl_encoding*) mbfl_name2encoding(p1);
if (encoding != nullptr) {
*entry++ = encoding;
n++;
} else {
ret = 0;
}
}
p1 = p2 + 1;
} while (n < size && p2 != nullptr);
if (n > 0) {
if (return_list) {
*return_list = list;
} else {
req::free(list);
}
} else {
req::free(list);
if (return_list) {
*return_list = nullptr;
}
ret = 0;
}
if (return_size) {
*return_size = n;
}
} else {
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
ret = 0;
}
req::free(tmpstr);
}
return ret;
}
static char *php_mb_convert_encoding(const char *input, size_t length,
const char *_to_encoding,
const char *_from_encodings,
unsigned int *output_len) {
mbfl_string string, result, *ret;
mbfl_encoding *from_encoding, *to_encoding;
mbfl_buffer_converter *convd;
int size;
mbfl_encoding **list;
char *output = nullptr;
if (output_len) {
*output_len = 0;
}
if (!input) {
return nullptr;
}
/* new encoding */
if (_to_encoding && strlen(_to_encoding)) {
to_encoding = (mbfl_encoding*) mbfl_name2encoding(_to_encoding);
if (to_encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", _to_encoding);
return nullptr;
}
} else {
to_encoding = MBSTRG(current_internal_encoding);
}
/* initialize string */
mbfl_string_init(&string);
mbfl_string_init(&result);
from_encoding = MBSTRG(current_internal_encoding);
string.no_encoding = from_encoding->no_encoding;
string.no_language = MBSTRG(current_language);
string.val = (unsigned char *)input;
string.len = length;
/* pre-conversion encoding */
if (_from_encodings) {
list = nullptr;
size = 0;
php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings),
&list, &size, 0);
if (size == 1) {
from_encoding = *list;
string.no_encoding = from_encoding->no_encoding;
} else if (size > 1) {
/* auto detect */
from_encoding = (mbfl_encoding*) mbfl_identify_encoding2(&string,
(const mbfl_encoding**) list,
size, MBSTRG(strict_detection));
if (from_encoding != nullptr) {
string.no_encoding = from_encoding->no_encoding;
} else {
raise_warning("Unable to detect character encoding");
from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
to_encoding = from_encoding;
string.no_encoding = from_encoding->no_encoding;
}
} else {
raise_warning("Illegal character encoding specified");
}
if (list != nullptr) {
req::free(list);
}
}
/* initialize converter */
convd = mbfl_buffer_converter_new2(from_encoding, to_encoding, string.len);
if (convd == nullptr) {
raise_warning("Unable to create character encoding converter");
return nullptr;
}
mbfl_buffer_converter_illegal_mode
(convd, MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(convd, MBSTRG(current_filter_illegal_substchar));
/* do it */
ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
if (ret) {
if (output_len) {
*output_len = ret->len;
}
output = (char *)ret->val;
}
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
return output;
}
static char *php_unicode_convert_case(int case_mode, const char *srcstr,
size_t srclen, unsigned int *ret_len,
const char *src_encoding) {
char *unicode, *newstr;
unsigned int unicode_len;
unsigned char *unicode_ptr;
size_t i;
enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding);
unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding,
&unicode_len);
if (unicode == nullptr)
return nullptr;
unicode_ptr = (unsigned char *)unicode;
switch(case_mode) {
case PHP_UNICODE_CASE_UPPER:
for (i = 0; i < unicode_len; i+=4) {
UINT32_TO_BE_ARY(&unicode_ptr[i],
php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
}
break;
case PHP_UNICODE_CASE_LOWER:
for (i = 0; i < unicode_len; i+=4) {
UINT32_TO_BE_ARY(&unicode_ptr[i],
php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
}
break;
case PHP_UNICODE_CASE_TITLE:
{
int mode = 0;
for (i = 0; i < unicode_len; i+=4) {
int res = php_unicode_is_prop
(BE_ARY_TO_UINT32(&unicode_ptr[i]),
UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0);
if (mode) {
if (res) {
UINT32_TO_BE_ARY
(&unicode_ptr[i],
php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
} else {
mode = 0;
}
} else {
if (res) {
mode = 1;
UINT32_TO_BE_ARY
(&unicode_ptr[i],
php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
}
}
}
}
break;
}
newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding,
"UCS-4BE", ret_len);
free(unicode);
return newstr;
}
///////////////////////////////////////////////////////////////////////////////
// helpers
/**
* Return 0 if input contains any illegal encoding, otherwise 1.
* Even if any illegal encoding is detected the result may contain a list
* of parsed encodings.
*/
static int
php_mb_parse_encoding_array(const Array& array, mbfl_encoding*** return_list,
int* return_size, int /*persistent*/) {
int n, l, size, bauto,ret = 1;
mbfl_encoding *encoding;
mbfl_no_encoding *src;
mbfl_encoding **list, **entry;
list = nullptr;
mbfl_no_encoding *identify_list = MBSTRG(default_detect_order_list);
int identify_list_size = MBSTRG(default_detect_order_list_size);
size = array.size() + identify_list_size;
list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*));
if (list != nullptr) {
entry = list;
bauto = 0;
n = 0;
for (ArrayIter iter(array); iter; ++iter) {
auto const hash_entry = iter.second().toString();
if (strcasecmp(hash_entry.data(), "auto") == 0) {
if (!bauto) {
bauto = 1;
l = identify_list_size;
src = identify_list;
for (int j = 0; j < l; j++) {
*entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++);
n++;
}
}
} else {
encoding = (mbfl_encoding*) mbfl_name2encoding(hash_entry.data());
if (encoding != nullptr) {
*entry++ = encoding;
n++;
} else {
ret = 0;
}
}
}
if (n > 0) {
if (return_list) {
*return_list = list;
} else {
req::free(list);
}
} else {
req::free(list);
if (return_list) {
*return_list = nullptr;
}
ret = 0;
}
if (return_size) {
*return_size = n;
}
} else {
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
ret = 0;
}
return ret;
}
static bool php_mb_parse_encoding(const Variant& encoding,
mbfl_encoding ***return_list,
int *return_size, bool persistent) {
bool ret;
if (encoding.isArray()) {
ret = php_mb_parse_encoding_array(encoding.toArray(),
return_list, return_size,
persistent ? 1 : 0);
} else {
String enc = encoding.toString();
ret = php_mb_parse_encoding_list(enc.data(), enc.size(),
return_list, return_size,
persistent ? 1 : 0);
}
if (!ret) {
if (return_list && *return_list) {
free(*return_list);
*return_list = nullptr;
}
return_size = 0;
}
return ret;
}
static int php_mb_nls_get_default_detect_order_list(mbfl_no_language lang,
mbfl_no_encoding **plist,
int* plist_size) {
size_t i;
*plist = (mbfl_no_encoding *) php_mb_default_identify_list_neut;
*plist_size = sizeof(php_mb_default_identify_list_neut) /
sizeof(php_mb_default_identify_list_neut[0]);
for (i = 0; i < sizeof(php_mb_default_identify_list) /
sizeof(php_mb_default_identify_list[0]); i++) {
if (php_mb_default_identify_list[i].lang == lang) {
*plist = php_mb_default_identify_list[i].list;
*plist_size = php_mb_default_identify_list[i].list_size;
return 1;
}
}
return 0;
}
static size_t php_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc) {
if (enc != nullptr) {
if (enc->flag & MBFL_ENCTYPE_MBCS) {
if (enc->mblen_table != nullptr) {
if (s != nullptr) return enc->mblen_table[*(unsigned char *)s];
}
} else if (enc->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) {
return 2;
} else if (enc->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) {
return 4;
}
}
return 1;
}
static int php_mb_stripos(int mode,
const char *old_haystack, int old_haystack_len,
const char *old_needle, int old_needle_len,
long offset, const char *from_encoding) {
int n;
mbfl_string haystack, needle;
n = -1;
mbfl_string_init(&haystack);
mbfl_string_init(&needle);
haystack.no_language = MBSTRG(current_language);
haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
needle.no_language = MBSTRG(current_language);
needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
do {
haystack.val = (unsigned char *)php_unicode_convert_case
(PHP_UNICODE_CASE_UPPER, old_haystack, (size_t)old_haystack_len,
&haystack.len, from_encoding);
if (!haystack.val) {
break;
}
if (haystack.len <= 0) {
break;
}
needle.val = (unsigned char *)php_unicode_convert_case
(PHP_UNICODE_CASE_UPPER, old_needle, (size_t)old_needle_len,
&needle.len, from_encoding);
if (!needle.val) {
break;
}
if (needle.len <= 0) {
break;
}
haystack.no_encoding = needle.no_encoding =
mbfl_name2no_encoding(from_encoding);
if (haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", from_encoding);
break;
}
int haystack_char_len = mbfl_strlen(&haystack);
if (mode) {
if ((offset > 0 && offset > haystack_char_len) ||
(offset < 0 && -offset > haystack_char_len)) {
raise_warning("Offset is greater than the length of haystack string");
break;
}
} else {
if (offset < 0 || offset > haystack_char_len) {
raise_warning("Offset not contained in string.");
break;
}
}
n = mbfl_strpos(&haystack, &needle, offset, mode);
} while(0);
if (haystack.val) {
free(haystack.val);
}
if (needle.val) {
free(needle.val);
}
return n;
}
///////////////////////////////////////////////////////////////////////////////
static String convertArg(const Variant& arg) {
return arg.isNull() ? null_string : arg.toString();
}
Array HHVM_FUNCTION(mb_list_encodings) {
Array ret;
int i = 0;
const mbfl_encoding **encodings = mbfl_get_supported_encodings();
const mbfl_encoding *encoding;
while ((encoding = encodings[i++]) != nullptr) {
ret.append(String(encoding->name, CopyString));
}
return ret;
}
Variant HHVM_FUNCTION(mb_encoding_aliases, const String& name) {
const mbfl_encoding *encoding;
int i = 0;
encoding = mbfl_name2encoding(name.data());
if (!encoding) {
raise_warning("mb_encoding_aliases(): Unknown encoding \"%s\"",
name.data());
return false;
}
Array ret = Array::Create();
if (encoding->aliases != nullptr) {
while ((*encoding->aliases)[i] != nullptr) {
ret.append((*encoding->aliases)[i]);
i++;
}
}
return ret;
}
Variant HHVM_FUNCTION(mb_list_encodings_alias_names,
const Variant& opt_name) {
const String name = convertArg(opt_name);
const mbfl_encoding **encodings;
const mbfl_encoding *encoding;
mbfl_no_encoding no_encoding;
int i, j;
Array ret;
if (name.isNull()) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
Array row;
if (encoding->aliases != nullptr) {
j = 0;
while ((*encoding->aliases)[j] != nullptr) {
row.append(String((*encoding->aliases)[j], CopyString));
j++;
}
}
ret.set(String(encoding->name, CopyString), row);
}
} else {
no_encoding = mbfl_name2no_encoding(name.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", name.data());
return false;
}
char *encodingName = (char *)mbfl_no_encoding2name(no_encoding);
if (encodingName != nullptr) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
if (strcmp(encoding->name, encodingName) != 0) continue;
if (encoding->aliases != nullptr) {
j = 0;
while ((*encoding->aliases)[j] != nullptr) {
ret.append(String((*encoding->aliases)[j], CopyString));
j++;
}
}
break;
}
} else {
return false;
}
}
return ret;
}
Variant HHVM_FUNCTION(mb_list_mime_names,
const Variant& opt_name) {
const String name = convertArg(opt_name);
const mbfl_encoding **encodings;
const mbfl_encoding *encoding;
mbfl_no_encoding no_encoding;
int i;
Array ret;
if (name.isNull()) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
if (encoding->mime_name != nullptr) {
ret.set(String(encoding->name, CopyString),
String(encoding->mime_name, CopyString));
} else{
ret.set(String(encoding->name, CopyString), "");
}
}
} else {
no_encoding = mbfl_name2no_encoding(name.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", name.data());
return false;
}
char *encodingName = (char *)mbfl_no_encoding2name(no_encoding);
if (encodingName != nullptr) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
if (strcmp(encoding->name, encodingName) != 0) continue;
if (encoding->mime_name != nullptr) {
return String(encoding->mime_name, CopyString);
}
break;
}
return empty_string_variant();
} else {
return false;
}
}
return ret;
}
bool HHVM_FUNCTION(mb_check_encoding,
const Variant& opt_var,
const Variant& opt_encoding) {
const String var = convertArg(opt_var);
const String encoding = convertArg(opt_encoding);
mbfl_buffer_converter *convd;
mbfl_no_encoding no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbfl_string string, result, *ret = nullptr;
long illegalchars = 0;
if (var.isNull()) {
return MBSTRG(illegalchars) == 0;
}
if (!encoding.isNull()) {
no_encoding = mbfl_name2no_encoding(encoding.data());
if (no_encoding == mbfl_no_encoding_invalid ||
no_encoding == mbfl_no_encoding_pass) {
raise_warning("Invalid encoding \"%s\"", encoding.data());
return false;
}
}
convd = mbfl_buffer_converter_new(no_encoding, no_encoding, 0);
if (convd == nullptr) {
raise_warning("Unable to create converter");
return false;
}
mbfl_buffer_converter_illegal_mode
(convd, MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE);
mbfl_buffer_converter_illegal_substchar
(convd, 0);
/* initialize string */
mbfl_string_init_set(&string, mbfl_no_language_neutral, no_encoding);
mbfl_string_init(&result);
string.val = (unsigned char *)var.data();
string.len = var.size();
ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
illegalchars = mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
if (ret != nullptr) {
MBSTRG(illegalchars) += illegalchars;
if (illegalchars == 0 && string.len == ret->len &&
memcmp((const char *)string.val, (const char *)ret->val,
string.len) == 0) {
mbfl_string_clear(&result);
return true;
} else {
mbfl_string_clear(&result);
return false;
}
} else {
return false;
}
}
Variant HHVM_FUNCTION(mb_convert_case,
const String& str,
int mode,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
const char *enc = nullptr;
if (encoding.empty()) {
enc = MBSTRG(current_internal_encoding)->mime_name;
} else {
enc = encoding.data();
}
unsigned int ret_len;
char *newstr = php_unicode_convert_case(mode, str.data(), str.size(),
&ret_len, enc);
if (newstr) {
return String(newstr, ret_len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_convert_encoding,
const String& str,
const String& to_encoding,
const Variant& from_encoding /* = uninit_variant */) {
String encoding = from_encoding.toString();
if (from_encoding.isArray()) {
StringBuffer _from_encodings;
Array encs = from_encoding.toArray();
for (ArrayIter iter(encs); iter; ++iter) {
if (!_from_encodings.empty()) {
_from_encodings.append(",");
}
_from_encodings.append(iter.second().toString());
}
encoding = _from_encodings.detach();
}
unsigned int size;
char *ret = php_mb_convert_encoding(str.data(), str.size(),
to_encoding.data(),
(!encoding.empty() ?
encoding.data() : nullptr),
&size);
if (ret != nullptr) {
return String(ret, size, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_convert_kana,
const String& str,
const Variant& opt_option,
const Variant& opt_encoding) {
const String option = convertArg(opt_option);
const String encoding = convertArg(opt_encoding);
mbfl_string string, result, *ret;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
int opt = 0x900;
if (!option.empty()) {
const char *p = option.data();
int n = option.size();
int i = 0;
opt = 0;
while (i < n) {
i++;
switch (*p++) {
case 'A': opt |= 0x1; break;
case 'a': opt |= 0x10; break;
case 'R': opt |= 0x2; break;
case 'r': opt |= 0x20; break;
case 'N': opt |= 0x4; break;
case 'n': opt |= 0x40; break;
case 'S': opt |= 0x8; break;
case 's': opt |= 0x80; break;
case 'K': opt |= 0x100; break;
case 'k': opt |= 0x1000; break;
case 'H': opt |= 0x200; break;
case 'h': opt |= 0x2000; break;
case 'V': opt |= 0x800; break;
case 'C': opt |= 0x10000; break;
case 'c': opt |= 0x20000; break;
case 'M': opt |= 0x100000; break;
case 'm': opt |= 0x200000; break;
}
}
}
/* encoding */
if (!encoding.empty()) {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
ret = mbfl_ja_jp_hantozen(&string, &result, opt);
if (ret != nullptr) {
if (ret->len > StringData::MaxSize) {
raise_warning("String too long, max is %d", StringData::MaxSize);
return false;
}
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
static bool php_mbfl_encoding_detect(const Variant& var,
mbfl_encoding_detector *identd,
mbfl_string *string) {
if (var.isArray() || var.is(KindOfObject)) {
Array items = var.toArray();
for (ArrayIter iter(items); iter; ++iter) {
if (php_mbfl_encoding_detect(iter.second(), identd, string)) {
return true;
}
}
} else if (var.isString()) {
String svar = var.toString();
string->val = (unsigned char *)svar.data();
string->len = svar.size();
if (mbfl_encoding_detector_feed(identd, string)) {
return true;
}
}
return false;
}
static Variant php_mbfl_convert(const Variant& var,
mbfl_buffer_converter *convd,
mbfl_string *string,
mbfl_string *result) {
if (var.isArray()) {
Array ret = empty_array();
Array items = var.toArray();
for (ArrayIter iter(items); iter; ++iter) {
ret.set(iter.first(),
php_mbfl_convert(iter.second(), convd, string, result));
}
return ret;
}
if (var.is(KindOfObject)) {
Object obj = var.toObject();
Array items = var.toArray();
for (ArrayIter iter(items); iter; ++iter) {
obj->o_set(iter.first().toString(),
php_mbfl_convert(iter.second(), convd, string, result));
}
return var; // which still has obj
}
if (var.isString()) {
String svar = var.toString();
string->val = (unsigned char *)svar.data();
string->len = svar.size();
mbfl_string *ret =
mbfl_buffer_converter_feed_result(convd, string, result);
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return var;
}
Variant HHVM_FUNCTION(mb_convert_variables,
const String& to_encoding,
const Variant& from_encoding,
Variant& vars,
const Array& args /* = null_array */) {
mbfl_string string, result;
mbfl_encoding *_from_encoding, *_to_encoding;
mbfl_encoding_detector *identd;
mbfl_buffer_converter *convd;
int elistsz;
mbfl_encoding **elist;
char *name;
/* new encoding */
_to_encoding = (mbfl_encoding*) mbfl_name2encoding(to_encoding.data());
if (_to_encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", to_encoding.data());
return false;
}
/* initialize string */
mbfl_string_init(&string);
mbfl_string_init(&result);
_from_encoding = MBSTRG(current_internal_encoding);
string.no_encoding = _from_encoding->no_encoding;
string.no_language = MBSTRG(current_language);
/* pre-conversion encoding */
elist = nullptr;
elistsz = 0;
php_mb_parse_encoding(from_encoding, &elist, &elistsz, false);
if (elistsz <= 0) {
_from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
} else if (elistsz == 1) {
_from_encoding = *elist;
} else {
/* auto detect */
_from_encoding = nullptr;
identd = mbfl_encoding_detector_new2((const mbfl_encoding**) elist, elistsz,
MBSTRG(strict_detection));
if (identd != nullptr) {
for (int n = -1; n < args.size(); n++) {
if (php_mbfl_encoding_detect(n < 0 ? vars : args[n],
identd, &string)) {
break;
}
}
_from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd);
mbfl_encoding_detector_delete(identd);
}
if (_from_encoding == nullptr) {
raise_warning("Unable to detect encoding");
_from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
}
}
if (elist != nullptr) {
req::free(elist);
}
/* create converter */
convd = nullptr;
if (_from_encoding != &mbfl_encoding_pass) {
convd = mbfl_buffer_converter_new2(_from_encoding, _to_encoding, 0);
if (convd == nullptr) {
raise_warning("Unable to create converter");
return false;
}
mbfl_buffer_converter_illegal_mode
(convd, MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(convd, MBSTRG(current_filter_illegal_substchar));
}
/* convert */
if (convd != nullptr) {
vars = php_mbfl_convert(vars, convd, &string, &result);
for (int n = 0; n < args.size(); n++) {
const_cast<Array&>(args).set(n, php_mbfl_convert(args[n], convd,
&string, &result));
}
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
}
if (_from_encoding != nullptr) {
name = (char*) _from_encoding->name;
if (name != nullptr) {
return String(name, CopyString);
}
}
return false;
}
Variant HHVM_FUNCTION(mb_decode_mimeheader,
const String& str) {
mbfl_string string, result, *ret;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
mbfl_string_init(&result);
ret = mbfl_mime_header_decode(&string, &result,
MBSTRG(current_internal_encoding)->no_encoding);
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
static Variant php_mb_numericentity_exec(const String& str,
const Variant& convmap,
const String& encoding,
bool is_hex, int type) {
int mapsize=0;
mbfl_string string, result, *ret;
mbfl_no_encoding no_encoding;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
if (type == 0 && is_hex) {
type = 2; /* output in hex format */
}
/* encoding */
if (!encoding.empty()) {
no_encoding = mbfl_name2no_encoding(encoding.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
} else {
string.no_encoding = no_encoding;
}
}
/* conversion map */
int *iconvmap = nullptr;
if (convmap.isArray()) {
Array convs = convmap.toArray();
mapsize = convs.size();
if (mapsize > 0) {
iconvmap = (int*)req::malloc_noptrs(mapsize * sizeof(int));
int *mapelm = iconvmap;
for (ArrayIter iter(convs); iter; ++iter) {
*mapelm++ = iter.second().toInt32();
}
}
}
if (iconvmap == nullptr) {
return false;
}
mapsize /= 4;
ret = mbfl_html_numeric_entity(&string, &result, iconvmap, mapsize, type);
req::free(iconvmap);
if (ret != nullptr) {
if (ret->len > StringData::MaxSize) {
raise_warning("String too long, max is %d", StringData::MaxSize);
return false;
}
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_decode_numericentity,
const String& str,
const Variant& convmap,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
return php_mb_numericentity_exec(str, convmap, encoding, false, 1);
}
Variant HHVM_FUNCTION(mb_detect_encoding,
const String& str,
const Variant& encoding_list /* = uninit_variant */,
const Variant& strict /* = uninit_variant */) {
mbfl_string string;
mbfl_encoding *ret;
mbfl_encoding **elist, **list;
int size;
/* make encoding list */
list = nullptr;
size = 0;
php_mb_parse_encoding(encoding_list, &list, &size, false);
if (size > 0 && list != nullptr) {
elist = list;
} else {
elist = MBSTRG(current_detect_order_list);
size = MBSTRG(current_detect_order_list_size);
}
long nstrict = 0;
if (!strict.isNull()) {
nstrict = strict.toInt64();
} else {
nstrict = MBSTRG(strict_detection);
}
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.val = (unsigned char *)str.data();
string.len = str.size();
ret = (mbfl_encoding*) mbfl_identify_encoding2(&string,
(const mbfl_encoding**) elist,
size, nstrict);
req::free(list);
if (ret != nullptr) {
return String(ret->name, CopyString);
}
return false;
}
Variant HHVM_FUNCTION(mb_detect_order,
const Variant& encoding_list /* = uninit_variant */) {
int n, size;
mbfl_encoding **list, **entry;
if (encoding_list.isNull()) {
Array ret;
entry = MBSTRG(current_detect_order_list);
n = MBSTRG(current_detect_order_list_size);
while (n > 0) {
char *name = (char*) (*entry)->name;
if (name) {
ret.append(String(name, CopyString));
}
entry++;
n--;
}
return ret;
}
list = nullptr;
size = 0;
if (!php_mb_parse_encoding(encoding_list, &list, &size, false) ||
list == nullptr) {
return false;
}
if (MBSTRG(current_detect_order_list)) {
req::free(MBSTRG(current_detect_order_list));
}
MBSTRG(current_detect_order_list) = list;
MBSTRG(current_detect_order_list_size) = size;
return true;
}
Variant HHVM_FUNCTION(mb_encode_mimeheader,
const String& str,
const Variant& opt_charset,
const Variant& opt_transfer_encoding,
const String& linefeed /* = "\r\n" */,
int indent /* = 0 */) {
const String charset = convertArg(opt_charset);
const String transfer_encoding = convertArg(opt_transfer_encoding);
mbfl_no_encoding charsetenc, transenc;
mbfl_string string, result, *ret;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
charsetenc = mbfl_no_encoding_pass;
transenc = mbfl_no_encoding_base64;
if (!charset.empty()) {
charsetenc = mbfl_name2no_encoding(charset.data());
if (charsetenc == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", charset.data());
return false;
}
} else {
const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language));
if (lang != nullptr) {
charsetenc = lang->mail_charset;
transenc = lang->mail_header_encoding;
}
}
if (!transfer_encoding.empty()) {
char ch = *transfer_encoding.data();
if (ch == 'B' || ch == 'b') {
transenc = mbfl_no_encoding_base64;
} else if (ch == 'Q' || ch == 'q') {
transenc = mbfl_no_encoding_qprint;
}
}
mbfl_string_init(&result);
ret = mbfl_mime_header_encode(&string, &result, charsetenc, transenc,
linefeed.data(), indent);
if (ret != nullptr) {
if (ret->len > StringData::MaxSize) {
raise_warning("String too long, max is %d", StringData::MaxSize);
return false;
}
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_encode_numericentity,
const String& str,
const Variant& convmap,
const Variant& opt_encoding /* = uninit_variant */,
bool is_hex /* = false */) {
const String encoding = convertArg(opt_encoding);
return php_mb_numericentity_exec(str, convmap, encoding, is_hex, 0);
}
const StaticString
s_internal_encoding("internal_encoding"),
s_http_input("http_input"),
s_http_output("http_output"),
s_mail_charset("mail_charset"),
s_mail_header_encoding("mail_header_encoding"),
s_mail_body_encoding("mail_body_encoding"),
s_illegal_chars("illegal_chars"),
s_encoding_translation("encoding_translation"),
s_On("On"),
s_Off("Off"),
s_language("language"),
s_detect_order("detect_order"),
s_substitute_character("substitute_character"),
s_strict_detection("strict_detection"),
s_none("none"),
s_long("long"),
s_entity("entity");
Variant HHVM_FUNCTION(mb_get_info,
const Variant& opt_type) {
const String type = convertArg(opt_type);
const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language));
mbfl_encoding **entry;
int n;
char *name;
if (type.empty() || strcasecmp(type.data(), "all") == 0) {
Array ret;
if (MBSTRG(current_internal_encoding) != nullptr &&
(name = (char *) MBSTRG(current_internal_encoding)->name) != nullptr) {
ret.set(s_internal_encoding, String(name, CopyString));
}
if (MBSTRG(http_input_identify) != nullptr &&
(name = (char *)MBSTRG(http_input_identify)->name) != nullptr) {
ret.set(s_http_input, String(name, CopyString));
}
if (MBSTRG(current_http_output_encoding) != nullptr &&
(name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) {
ret.set(s_http_output, String(name, CopyString));
}
if (lang != nullptr) {
if ((name = (char *)mbfl_no_encoding2name
(lang->mail_charset)) != nullptr) {
ret.set(s_mail_charset, String(name, CopyString));
}
if ((name = (char *)mbfl_no_encoding2name
(lang->mail_header_encoding)) != nullptr) {
ret.set(s_mail_header_encoding, String(name, CopyString));
}
if ((name = (char *)mbfl_no_encoding2name
(lang->mail_body_encoding)) != nullptr) {
ret.set(s_mail_body_encoding, String(name, CopyString));
}
}
ret.set(s_illegal_chars, MBSTRG(illegalchars));
ret.set(s_encoding_translation,
MBSTRG(encoding_translation) ? s_On : s_Off);
if ((name = (char *)mbfl_no_language2name
(MBSTRG(current_language))) != nullptr) {
ret.set(s_language, String(name, CopyString));
}
n = MBSTRG(current_detect_order_list_size);
entry = MBSTRG(current_detect_order_list);
if (n > 0) {
Array row;
while (n > 0) {
if ((name = (char *)(*entry)->name) != nullptr) {
row.append(String(name, CopyString));
}
entry++;
n--;
}
ret.set(s_detect_order, row);
}
switch (MBSTRG(current_filter_illegal_mode)) {
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE:
ret.set(s_substitute_character, s_none);
break;
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG:
ret.set(s_substitute_character, s_long);
break;
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY:
ret.set(s_substitute_character, s_entity);
break;
default:
ret.set(s_substitute_character,
MBSTRG(current_filter_illegal_substchar));
}
ret.set(s_strict_detection, MBSTRG(strict_detection) ? s_On : s_Off);
return ret;
} else if (strcasecmp(type.data(), "internal_encoding") == 0) {
if (MBSTRG(current_internal_encoding) != nullptr &&
(name = (char *)MBSTRG(current_internal_encoding)->name) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "http_input") == 0) {
if (MBSTRG(http_input_identify) != nullptr &&
(name = (char *)MBSTRG(http_input_identify)->name) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "http_output") == 0) {
if (MBSTRG(current_http_output_encoding) != nullptr &&
(name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "mail_charset") == 0) {
if (lang != nullptr &&
(name = (char *)mbfl_no_encoding2name
(lang->mail_charset)) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "mail_header_encoding") == 0) {
if (lang != nullptr &&
(name = (char *)mbfl_no_encoding2name
(lang->mail_header_encoding)) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "mail_body_encoding") == 0) {
if (lang != nullptr &&
(name = (char *)mbfl_no_encoding2name
(lang->mail_body_encoding)) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "illegal_chars") == 0) {
return MBSTRG(illegalchars);
} else if (strcasecmp(type.data(), "encoding_translation") == 0) {
return MBSTRG(encoding_translation) ? "On" : "Off";
} else if (strcasecmp(type.data(), "language") == 0) {
if ((name = (char *)mbfl_no_language2name
(MBSTRG(current_language))) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "detect_order") == 0) {
n = MBSTRG(current_detect_order_list_size);
entry = MBSTRG(current_detect_order_list);
if (n > 0) {
Array ret;
while (n > 0) {
name = (char *)(*entry)->name;
if (name) {
ret.append(String(name, CopyString));
}
entry++;
n--;
}
}
} else if (strcasecmp(type.data(), "substitute_character") == 0) {
if (MBSTRG(current_filter_illegal_mode) ==
MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) {
return s_none;
} else if (MBSTRG(current_filter_illegal_mode) ==
MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) {
return s_long;
} else if (MBSTRG(current_filter_illegal_mode) ==
MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) {
return s_entity;
} else {
return MBSTRG(current_filter_illegal_substchar);
}
} else if (strcasecmp(type.data(), "strict_detection") == 0) {
return MBSTRG(strict_detection) ? s_On : s_Off;
}
return false;
}
Variant HHVM_FUNCTION(mb_http_input,
const Variant& opt_type) {
const String type = convertArg(opt_type);
int n;
char *name;
mbfl_encoding **entry;
mbfl_encoding *result = nullptr;
if (type.empty()) {
result = MBSTRG(http_input_identify);
} else {
switch (*type.data()) {
case 'G': case 'g': result = MBSTRG(http_input_identify_get); break;
case 'P': case 'p': result = MBSTRG(http_input_identify_post); break;
case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break;
case 'S': case 's': result = MBSTRG(http_input_identify_string); break;
case 'I': case 'i':
{
Array ret;
entry = MBSTRG(http_input_list);
n = MBSTRG(http_input_list_size);
while (n > 0) {
name = (char *)(*entry)->name;
if (name) {
ret.append(String(name, CopyString));
}
entry++;
n--;
}
return ret;
}
case 'L': case 'l':
{
entry = MBSTRG(http_input_list);
n = MBSTRG(http_input_list_size);
StringBuffer list;
while (n > 0) {
name = (char *)(*entry)->name;
if (name) {
if (list.empty()) {
list.append(name);
} else {
list.append(',');
list.append(name);
}
}
entry++;
n--;
}
if (list.empty()) {
return false;
}
return list.detach();
}
default:
result = MBSTRG(http_input_identify);
break;
}
}
if (result != nullptr &&
(name = (char *)(result)->name) != nullptr) {
return String(name, CopyString);
}
return false;
}
Variant HHVM_FUNCTION(mb_http_output,
const Variant& opt_encoding) {
const String encoding_name = convertArg(opt_encoding);
if (encoding_name.empty()) {
char *name = (char *)(MBSTRG(current_http_output_encoding)->name);
if (name != nullptr) {
return String(name, CopyString);
}
return false;
}
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_name2encoding(encoding_name.data());
if (encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", encoding_name.data());
return false;
}
MBSTRG(current_http_output_encoding) = encoding;
return true;
}
Variant HHVM_FUNCTION(mb_internal_encoding,
const Variant& opt_encoding) {
const String encoding_name = convertArg(opt_encoding);
if (encoding_name.empty()) {
char *name = (char *)(MBSTRG(current_internal_encoding)->name);
if (name != nullptr) {
return String(name, CopyString);
}
return false;
}
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_name2encoding(encoding_name.data());
if (encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", encoding_name.data());
return false;
}
MBSTRG(current_internal_encoding) = encoding;
return true;
}
Variant HHVM_FUNCTION(mb_language,
const Variant& opt_language) {
const String language = convertArg(opt_language);
if (language.empty()) {
return String(mbfl_no_language2name(MBSTRG(current_language)), CopyString);
}
mbfl_no_language no_language = mbfl_name2no_language(language.data());
if (no_language == mbfl_no_language_invalid) {
raise_warning("Unknown language \"%s\"", language.data());
return false;
}
php_mb_nls_get_default_detect_order_list
(no_language, &MBSTRG(default_detect_order_list),
&MBSTRG(default_detect_order_list_size));
MBSTRG(current_language) = no_language;
return true;
}
String HHVM_FUNCTION(mb_output_handler,
const String& contents,
int status) {
mbfl_string string, result;
int last_feed;
mbfl_encoding *encoding = MBSTRG(current_http_output_encoding);
/* start phase only */
if (status & k_PHP_OUTPUT_HANDLER_START) {
/* delete the converter just in case. */
if (MBSTRG(outconv)) {
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
mbfl_buffer_converter_delete(MBSTRG(outconv));
MBSTRG(outconv) = nullptr;
}
if (encoding == nullptr) {
return contents;
}
/* analyze mime type */
String mimetype = g_context->getMimeType();
if (!mimetype.empty()) {
const char *charset = encoding->mime_name;
if (charset) {
g_context->setContentType(mimetype, charset);
}
/* activate the converter */
MBSTRG(outconv) = mbfl_buffer_converter_new2
(MBSTRG(current_internal_encoding), encoding, 0);
}
}
/* just return if the converter is not activated. */
if (MBSTRG(outconv) == nullptr) {
return contents;
}
/* flag */
last_feed = ((status & k_PHP_OUTPUT_HANDLER_END) != 0);
/* mode */
mbfl_buffer_converter_illegal_mode
(MBSTRG(outconv), MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar));
/* feed the string */
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)contents.data();
string.len = contents.size();
mbfl_buffer_converter_feed(MBSTRG(outconv), &string);
if (last_feed) {
mbfl_buffer_converter_flush(MBSTRG(outconv));
}
/* get the converter output, and return it */
mbfl_buffer_converter_result(MBSTRG(outconv), &result);
/* delete the converter if it is the last feed. */
if (last_feed) {
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
mbfl_buffer_converter_delete(MBSTRG(outconv));
MBSTRG(outconv) = nullptr;
}
return String(reinterpret_cast<char*>(result.val), result.len, AttachString);
}
typedef struct _php_mb_encoding_handler_info_t {
int data_type;
const char *separator;
unsigned int force_register_globals: 1;
unsigned int report_errors: 1;
enum mbfl_no_language to_language;
mbfl_encoding *to_encoding;
enum mbfl_no_language from_language;
int num_from_encodings;
mbfl_encoding **from_encodings;
} php_mb_encoding_handler_info_t;
static mbfl_encoding* _php_mb_encoding_handler_ex
(const php_mb_encoding_handler_info_t *info, Array& arg, char *res) {
char *var, *val;
const char *s1, *s2;
char *strtok_buf = nullptr, **val_list = nullptr;
int n, num, *len_list = nullptr;
unsigned int val_len;
mbfl_string string, resvar, resval;
mbfl_encoding *from_encoding = nullptr;
mbfl_encoding_detector *identd = nullptr;
mbfl_buffer_converter *convd = nullptr;
mbfl_string_init_set(&string, info->to_language,
info->to_encoding->no_encoding);
mbfl_string_init_set(&resvar, info->to_language,
info->to_encoding->no_encoding);
mbfl_string_init_set(&resval, info->to_language,
info->to_encoding->no_encoding);
if (!res || *res == '\0') {
goto out;
}
/* count the variables(separators) contained in the "res".
* separator may contain multiple separator chars.
*/
num = 1;
for (s1=res; *s1 != '\0'; s1++) {
for (s2=info->separator; *s2 != '\0'; s2++) {
if (*s1 == *s2) {
num++;
}
}
}
num *= 2; /* need space for variable name and value */
val_list = (char **)req::calloc_noptrs(num, sizeof(char *));
len_list = (int *)req::calloc_noptrs(num, sizeof(int));
/* split and decode the query */
n = 0;
strtok_buf = nullptr;
var = strtok_r(res, info->separator, &strtok_buf);
while (var) {
val = strchr(var, '=');
if (val) { /* have a value */
len_list[n] = url_decode_ex(var, val-var);
val_list[n] = var;
n++;
*val++ = '\0';
val_list[n] = val;
len_list[n] = url_decode_ex(val, strlen(val));
} else {
len_list[n] = url_decode_ex(var, strlen(var));
val_list[n] = var;
n++;
val_list[n] = const_cast<char*>("");
len_list[n] = 0;
}
n++;
var = strtok_r(nullptr, info->separator, &strtok_buf);
}
num = n; /* make sure to process initilized vars only */
/* initialize converter */
if (info->num_from_encodings <= 0) {
from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
} else if (info->num_from_encodings == 1) {
from_encoding = info->from_encodings[0];
} else {
/* auto detect */
from_encoding = nullptr;
identd = mbfl_encoding_detector_new
((enum mbfl_no_encoding *)info->from_encodings,
info->num_from_encodings, MBSTRG(strict_detection));
if (identd) {
n = 0;
while (n < num) {
string.val = (unsigned char *)val_list[n];
string.len = len_list[n];
if (mbfl_encoding_detector_feed(identd, &string)) {
break;
}
n++;
}
from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd);
mbfl_encoding_detector_delete(identd);
}
if (from_encoding == nullptr) {
if (info->report_errors) {
raise_warning("Unable to detect encoding");
}
from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
}
}
convd = nullptr;
if (from_encoding != (mbfl_encoding*) &mbfl_encoding_pass) {
convd = mbfl_buffer_converter_new2(from_encoding, info->to_encoding, 0);
if (convd != nullptr) {
mbfl_buffer_converter_illegal_mode
(convd, MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(convd, MBSTRG(current_filter_illegal_substchar));
} else {
if (info->report_errors) {
raise_warning("Unable to create converter");
}
goto out;
}
}
/* convert encoding */
string.no_encoding = from_encoding->no_encoding;
n = 0;
while (n < num) {
string.val = (unsigned char *)val_list[n];
string.len = len_list[n];
if (convd != nullptr &&
mbfl_buffer_converter_feed_result(convd, &string, &resvar) != nullptr) {
var = (char *)resvar.val;
} else {
var = val_list[n];
}
n++;
string.val = (unsigned char *)val_list[n];
string.len = len_list[n];
if (convd != nullptr &&
mbfl_buffer_converter_feed_result(convd, &string, &resval) != nullptr) {
val = (char *)resval.val;
val_len = resval.len;
} else {
val = val_list[n];
val_len = len_list[n];
}
n++;
if (val_len > 0) {
arg.set(String(var, CopyString), String(val, val_len, CopyString));
}
if (convd != nullptr) {
mbfl_string_clear(&resvar);
mbfl_string_clear(&resval);
}
}
out:
if (convd != nullptr) {
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
}
if (val_list != nullptr) {
req::free((void *)val_list);
}
if (len_list != nullptr) {
req::free((void *)len_list);
}
return from_encoding;
}
bool HHVM_FUNCTION(mb_parse_str,
const String& encoded_string,
Array& result) {
php_mb_encoding_handler_info_t info;
info.data_type = PARSE_STRING;
info.separator = "&";
info.force_register_globals = false;
info.report_errors = 1;
info.to_encoding = MBSTRG(current_internal_encoding);
info.to_language = MBSTRG(current_language);
info.from_encodings = MBSTRG(http_input_list);
info.num_from_encodings = MBSTRG(http_input_list_size);
info.from_language = MBSTRG(current_language);
char *encstr = req::strndup(encoded_string.data(), encoded_string.size());
result = Array::Create();
mbfl_encoding *detected =
_php_mb_encoding_handler_ex(&info, result, encstr);
req::free(encstr);
MBSTRG(http_input_identify) = detected;
return detected != nullptr;
}
Variant HHVM_FUNCTION(mb_preferred_mime_name,
const String& encoding) {
mbfl_no_encoding no_encoding = mbfl_name2no_encoding(encoding.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding);
if (preferred_name == nullptr || *preferred_name == '\0') {
raise_warning("No MIME preferred name corresponding to \"%s\"",
encoding.data());
return false;
}
return String(preferred_name, CopyString);
}
static Variant php_mb_substr(const String& str, int from,
const Variant& vlen,
const String& encoding, bool substr) {
mbfl_string string;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
if (!encoding.empty()) {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
int len = vlen.toInt64();
int size = 0;
if (substr) {
int size_tmp = -1;
if (vlen.isNull() || len == 0x7FFFFFFF) {
size_tmp = mbfl_strlen(&string);
len = size_tmp;
}
if (from < 0 || len < 0) {
size = size_tmp < 0 ? mbfl_strlen(&string) : size_tmp;
}
} else {
size = str.size();
if (vlen.isNull() || len == 0x7FFFFFFF) {
len = size;
}
}
/* if "from" position is negative, count start position from the end
* of the string
*/
if (from < 0) {
from = size + from;
if (from < 0) {
from = 0;
}
}
/* if "length" position is negative, set it to the length
* needed to stop that many chars from the end of the string
*/
if (len < 0) {
len = (size - from) + len;
if (len < 0) {
len = 0;
}
}
if (!substr && from > size) {
return false;
}
mbfl_string result;
mbfl_string *ret;
if (substr) {
ret = mbfl_substr(&string, &result, from, len);
} else {
ret = mbfl_strcut(&string, &result, from, len);
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_substr,
const String& str,
int start,
const Variant& length /*= uninit_null() */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
return php_mb_substr(str, start, length, encoding, true);
}
Variant HHVM_FUNCTION(mb_strcut,
const String& str,
int start,
const Variant& length /*= uninit_null() */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
return php_mb_substr(str, start, length, encoding, false);
}
Variant HHVM_FUNCTION(mb_strimwidth,
const String& str,
int start,
int width,
const Variant& opt_trimmarker,
const Variant& opt_encoding) {
const String trimmarker = convertArg(opt_trimmarker);
const String encoding = convertArg(opt_encoding);
mbfl_string string, result, marker, *ret;
mbfl_string_init(&string);
mbfl_string_init(&marker);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
marker.no_language = MBSTRG(current_language);
marker.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
marker.val = nullptr;
marker.len = 0;
if (!encoding.empty()) {
string.no_encoding = marker.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
string.val = (unsigned char *)str.data();
string.len = str.size();
if (start < 0 || start > str.size()) {
raise_warning("Start position is out of reange");
return false;
}
if (width < 0) {
raise_warning("Width is negative value");
return false;
}
marker.val = (unsigned char *)trimmarker.data();
marker.len = trimmarker.size();
ret = mbfl_strimwidth(&string, &marker, &result, start, width);
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_stripos,
const String& haystack,
const String& needle,
int offset /* = 0 */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
if (needle.empty()) {
raise_warning("Empty delimiter");
return false;
}
int n = php_mb_stripos(0, haystack.data(), haystack.size(),
needle.data(), needle.size(), offset, from_encoding);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_strripos,
const String& haystack,
const String& needle,
int offset /* = 0 */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
int n = php_mb_stripos(1, haystack.data(), haystack.size(),
needle.data(), needle.size(), offset, from_encoding);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_stristr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!mbs_needle.len) {
raise_warning("Empty delimiter.");
return false;
}
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(from_encoding);
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", from_encoding);
return false;
}
int n = php_mb_stripos(0, (const char*)mbs_haystack.val, mbs_haystack.len,
(const char *)mbs_needle.val, mbs_needle.len,
0, from_encoding);
if (n < 0) {
return false;
}
int mblen = mbfl_strlen(&mbs_haystack);
mbfl_string result, *ret = nullptr;
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strlen,
const String& str,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string string;
mbfl_string_init(&string);
string.val = (unsigned char *)str.data();
string.len = str.size();
string.no_language = MBSTRG(current_language);
if (encoding.empty()) {
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
} else {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
int n = mbfl_strlen(&string);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_strpos,
const String& haystack,
const String& needle,
int offset /* = 0 */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (offset < 0 || offset > mbfl_strlen(&mbs_haystack)) {
raise_warning("Offset not contained in string.");
return false;
}
if (mbs_needle.len == 0) {
raise_warning("Empty delimiter.");
return false;
}
int reverse = 0;
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, offset, reverse);
if (n >= 0) {
return n;
}
switch (-n) {
case 1:
break;
case 2:
raise_warning("Needle has not positive length.");
break;
case 4:
raise_warning("Unknown encoding or conversion error.");
break;
case 8:
raise_warning("Argument is empty.");
break;
default:
raise_warning("Unknown error in mb_strpos.");
break;
}
return false;
}
Variant HHVM_FUNCTION(mb_strrpos,
const String& haystack,
const String& needle,
const Variant& offset /* = 0LL */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
// This hack is so that if the caller puts the encoding in the offset field we
// attempt to detect it and use that as the encoding. Ick.
const char *enc_name = encoding.data();
long noffset = 0;
String soffset = offset.toString();
if (offset.isString()) {
enc_name = soffset.data();
int str_flg = 1;
if (enc_name != nullptr) {
switch (*enc_name) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case ' ': case '-': case '.':
break;
default :
str_flg = 0;
break;
}
}
if (str_flg) {
noffset = offset.toInt32();
enc_name = encoding.data();
}
} else {
noffset = offset.toInt32();
}
if (enc_name != nullptr && *enc_name) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(enc_name);
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", enc_name);
return false;
}
}
if (mbs_haystack.len <= 0) {
return false;
}
if (mbs_needle.len <= 0) {
return false;
}
if ((noffset > 0 && noffset > mbfl_strlen(&mbs_haystack)) ||
(noffset < 0 && -noffset > mbfl_strlen(&mbs_haystack))) {
raise_notice("Offset is greater than the length of haystack string");
return false;
}
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, noffset, 1);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_strrchr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (mbs_haystack.len <= 0) {
return false;
}
if (mbs_needle.len <= 0) {
return false;
}
mbfl_string result, *ret = nullptr;
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 1);
if (n >= 0) {
int mblen = mbfl_strlen(&mbs_haystack);
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strrichr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(from_encoding);
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", from_encoding);
return false;
}
int n = php_mb_stripos(1, (const char*)mbs_haystack.val, mbs_haystack.len,
(const char*)mbs_needle.val, mbs_needle.len,
0, from_encoding);
if (n < 0) {
return false;
}
mbfl_string result, *ret = nullptr;
int mblen = mbfl_strlen(&mbs_haystack);
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strstr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (mbs_needle.len <= 0) {
raise_warning("Empty delimiter.");
return false;
}
mbfl_string result, *ret = nullptr;
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 0);
if (n >= 0) {
int mblen = mbfl_strlen(&mbs_haystack);
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
const StaticString s_utf_8("utf-8");
/**
* Fast check for the most common form of the UTF-8 encoding identifier.
*/
ALWAYS_INLINE
static bool isUtf8(const Variant& encoding) {
return encoding.getStringDataOrNull() == s_utf_8.get();
}
/**
* Given a byte sequence, return
* 0 if it contains bytes >= 128 (thus non-ASCII), else
* -1 if it contains any upper-case character ('A'-'Z'), else
* 1 (and thus is a lower-case ASCII string).
*/
ALWAYS_INLINE
static int isUtf8AsciiLower(folly::StringPiece s) {
const auto bytelen = s.size();
bool caseOK = true;
for (uint32_t i = 0; i < bytelen; ++i) {
uint8_t byte = s[i];
if (byte >= 128) {
return 0;
} else if (byte <= 'Z' && byte >= 'A') {
caseOK = false;
}
}
return caseOK ? 1 : -1;
}
/**
* Return a string containing the lower-case of a given ASCII string.
*/
ALWAYS_INLINE
static StringData* asciiToLower(const StringData* s) {
const auto size = s->size();
auto ret = StringData::Make(s, CopyString);
auto output = ret->mutableData();
for (int i = 0; i < size; ++i) {
auto& c = output[i];
if (c <= 'Z' && c >= 'A') {
c |= 0x20;
}
}
ret->invalidateHash(); // We probably modified it.
return ret;
}
/* Like isUtf8AsciiLower, but with upper/lower swapped. */
ALWAYS_INLINE
static int isUtf8AsciiUpper(folly::StringPiece s) {
const auto bytelen = s.size();
bool caseOK = true;
for (uint32_t i = 0; i < bytelen; ++i) {
uint8_t byte = s[i];
if (byte >= 128) {
return 0;
} else if (byte >= 'a' && byte <= 'z') {
caseOK = false;
}
}
return caseOK ? 1 : -1;
}
/* Like asciiToLower, but with upper/lower swapped. */
ALWAYS_INLINE
static StringData* asciiToUpper(const StringData* s) {
const auto size = s->size();
auto ret = StringData::Make(s, CopyString);
auto output = ret->mutableData();
for (int i = 0; i < size; ++i) {
auto& c = output[i];
if (c >= 'a' && c <= 'z') {
c -= (char)0x20;
}
}
ret->invalidateHash(); // We probably modified it.
return ret;
}
Variant HHVM_FUNCTION(mb_strtolower,
const String& str,
const Variant& opt_encoding) {
/* Fast-case for empty static string without dereferencing any pointers. */
if (str.get() == staticEmptyString()) return empty_string_variant();
if (LIKELY(isUtf8(opt_encoding))) {
/* Fast-case for ASCII. */
if (auto sd = str.get()) {
auto sl = sd->slice();
auto r = isUtf8AsciiLower(sl);
if (r > 0) {
return str;
} else if (r < 0) {
return String::attach(asciiToLower(sd));
}
}
}
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
unsigned int ret_len;
char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_LOWER,
str.data(), str.size(),
&ret_len, from_encoding);
if (newstr) {
return String(newstr, ret_len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strtoupper,
const String& str,
const Variant& opt_encoding) {
/* Fast-case for empty static string without dereferencing any pointers. */
if (str.get() == staticEmptyString()) return empty_string_variant();
if (LIKELY(isUtf8(opt_encoding))) {
/* Fast-case for ASCII. */
if (auto sd = str.get()) {
auto sl = sd->slice();
auto r = isUtf8AsciiUpper(sl);
if (r > 0) {
return str;
} else if (r < 0) {
return String::attach(asciiToUpper(sd));
}
}
}
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
unsigned int ret_len;
char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_UPPER,
str.data(), str.size(),
&ret_len, from_encoding);
if (newstr) {
return String(newstr, ret_len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strwidth,
const String& str,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string string;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
if (!encoding.empty()) {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
int n = mbfl_strwidth(&string);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_substitute_character,
const Variant& substrchar /* = uninit_variant */) {
if (substrchar.isNull()) {
switch (MBSTRG(current_filter_illegal_mode)) {
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE:
return "none";
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG:
return "long";
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY:
return "entity";
default:
return MBSTRG(current_filter_illegal_substchar);
}
}
if (substrchar.isString()) {
String s = substrchar.toString();
if (strcasecmp("none", s.data()) == 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE;
return true;
}
if (strcasecmp("long", s.data()) == 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG;
return true;
}
if (strcasecmp("entity", s.data()) == 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY;
return true;
}
}
int64_t n = substrchar.toInt64();
if (n < 0xffff && n > 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
MBSTRG(current_filter_illegal_substchar) = n;
} else {
raise_warning("Unknown character.");
return false;
}
return true;
}
Variant HHVM_FUNCTION(mb_substr_count,
const String& haystack,
const String& needle,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (mbs_needle.len <= 0) {
raise_warning("Empty substring.");
return false;
}
int n = mbfl_substr_count(&mbs_haystack, &mbs_needle);
if (n >= 0) {
return n;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// regex helpers
typedef struct _php_mb_regex_enc_name_map_t {
const char *names;
OnigEncoding code;
} php_mb_regex_enc_name_map_t;
static php_mb_regex_enc_name_map_t enc_name_map[] ={
{
"EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0",
ONIG_ENCODING_EUC_JP
},
{
"UTF-8\0UTF8\0",
ONIG_ENCODING_UTF8
},
{
"UTF-16\0UTF-16BE\0",
ONIG_ENCODING_UTF16_BE
},
{
"UTF-16LE\0",
ONIG_ENCODING_UTF16_LE
},
{
"UCS-4\0UTF-32\0UTF-32BE\0",
ONIG_ENCODING_UTF32_BE
},
{
"UCS-4LE\0UTF-32LE\0",
ONIG_ENCODING_UTF32_LE
},
{
"SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0",
ONIG_ENCODING_SJIS
},
{
"BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0",
ONIG_ENCODING_BIG5
},
{
"EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0",
ONIG_ENCODING_EUC_CN
},
{
"EUC-TW\0EUCTW\0EUC_TW\0",
ONIG_ENCODING_EUC_TW
},
{
"EUC-KR\0EUCKR\0EUC_KR\0",
ONIG_ENCODING_EUC_KR
},
{
"KOI8R\0KOI8-R\0KOI-8R\0",
ONIG_ENCODING_KOI8_R
},
{
"ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0",
ONIG_ENCODING_ISO_8859_1
},
{
"ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0",
ONIG_ENCODING_ISO_8859_2
},
{
"ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0",
ONIG_ENCODING_ISO_8859_3
},
{
"ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0",
ONIG_ENCODING_ISO_8859_4
},
{
"ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0",
ONIG_ENCODING_ISO_8859_5
},
{
"ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0",
ONIG_ENCODING_ISO_8859_6
},
{
"ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0",
ONIG_ENCODING_ISO_8859_7
},
{
"ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0",
ONIG_ENCODING_ISO_8859_8
},
{
"ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0",
ONIG_ENCODING_ISO_8859_9
},
{
"ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0",
ONIG_ENCODING_ISO_8859_10
},
{
"ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0",
ONIG_ENCODING_ISO_8859_11
},
{
"ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0",
ONIG_ENCODING_ISO_8859_13
},
{
"ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0",
ONIG_ENCODING_ISO_8859_14
},
{
"ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0",
ONIG_ENCODING_ISO_8859_15
},
{
"ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0",
ONIG_ENCODING_ISO_8859_16
},
{
"ASCII\0US-ASCII\0US_ASCII\0ISO646\0",
ONIG_ENCODING_ASCII
},
{ nullptr, ONIG_ENCODING_UNDEF }
};
static OnigEncoding php_mb_regex_name2mbctype(const char *pname) {
const char *p;
php_mb_regex_enc_name_map_t *mapping;
if (pname == nullptr) {
return ONIG_ENCODING_UNDEF;
}
for (mapping = enc_name_map; mapping->names != nullptr; mapping++) {
for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) {
if (strcasecmp(p, pname) == 0) {
return mapping->code;
}
}
}
return ONIG_ENCODING_UNDEF;
}
static const char *php_mb_regex_mbctype2name(OnigEncoding mbctype) {
php_mb_regex_enc_name_map_t *mapping;
for (mapping = enc_name_map; mapping->names != nullptr; mapping++) {
if (mapping->code == mbctype) {
return mapping->names;
}
}
return nullptr;
}
/*
* regex cache
*/
static php_mb_regex_t *php_mbregex_compile_pattern(const String& pattern,
OnigOptionType options,
OnigEncoding enc,
OnigSyntaxType *syntax) {
int err_code = 0;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
php_mb_regex_t *rc = nullptr;
std::string spattern = std::string(pattern.data(), pattern.size());
RegexCache &cache = MBSTRG(ht_rc);
RegexCache::const_iterator it =
cache.find(spattern);
if (it != cache.end()) {
rc = it->second;
}
if (!rc || onig_get_options(rc) != options || onig_get_encoding(rc) != enc ||
onig_get_syntax(rc) != syntax) {
if (rc) {
onig_free(rc);
rc = nullptr;
}
if ((err_code = onig_new(&rc, (OnigUChar *)pattern.data(),
(OnigUChar *)(pattern.data() + pattern.size()),
options,enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
raise_warning("mbregex compile err: %s", err_str);
return nullptr;
}
MBSTRG(ht_rc)[spattern] = rc;
}
return rc;
}
static size_t _php_mb_regex_get_option_string(char *str, size_t len,
OnigOptionType option,
OnigSyntaxType *syntax) {
size_t len_left = len;
size_t len_req = 0;
char *p = str;
char c;
if ((option & ONIG_OPTION_IGNORECASE) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'i';
}
++len_req;
}
if ((option & ONIG_OPTION_EXTEND) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'x';
}
++len_req;
}
if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) ==
(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) {
if (len_left > 0) {
--len_left;
*(p++) = 'p';
}
++len_req;
} else {
if ((option & ONIG_OPTION_MULTILINE) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'm';
}
++len_req;
}
if ((option & ONIG_OPTION_SINGLELINE) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 's';
}
++len_req;
}
}
if ((option & ONIG_OPTION_FIND_LONGEST) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'l';
}
++len_req;
}
if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'n';
}
++len_req;
}
c = 0;
if (syntax == ONIG_SYNTAX_JAVA) {
c = 'j';
} else if (syntax == ONIG_SYNTAX_GNU_REGEX) {
c = 'u';
} else if (syntax == ONIG_SYNTAX_GREP) {
c = 'g';
} else if (syntax == ONIG_SYNTAX_EMACS) {
c = 'c';
} else if (syntax == ONIG_SYNTAX_RUBY) {
c = 'r';
} else if (syntax == ONIG_SYNTAX_PERL) {
c = 'z';
} else if (syntax == ONIG_SYNTAX_POSIX_BASIC) {
c = 'b';
} else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) {
c = 'd';
}
if (c != 0) {
if (len_left > 0) {
--len_left;
*(p++) = c;
}
++len_req;
}
if (len_left > 0) {
--len_left;
*(p++) = '\0';
}
++len_req;
if (len < len_req) {
return len_req;
}
return 0;
}
static void _php_mb_regex_init_options(const char *parg, int narg,
OnigOptionType *option,
OnigSyntaxType **syntax, int *eval) {
int n;
char c;
int optm = 0;
*syntax = ONIG_SYNTAX_RUBY;
if (parg != nullptr) {
n = 0;
while (n < narg) {
c = parg[n++];
switch (c) {
case 'i': optm |= ONIG_OPTION_IGNORECASE; break;
case 'x': optm |= ONIG_OPTION_EXTEND; break;
case 'm': optm |= ONIG_OPTION_MULTILINE; break;
case 's': optm |= ONIG_OPTION_SINGLELINE; break;
case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break;
case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break;
case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break;
case 'j': *syntax = ONIG_SYNTAX_JAVA; break;
case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break;
case 'g': *syntax = ONIG_SYNTAX_GREP; break;
case 'c': *syntax = ONIG_SYNTAX_EMACS; break;
case 'r': *syntax = ONIG_SYNTAX_RUBY; break;
case 'z': *syntax = ONIG_SYNTAX_PERL; break;
case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break;
case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break;
case 'e':
if (eval != nullptr) *eval = 1;
break;
default:
break;
}
}
if (option != nullptr) *option|=optm;
}
}
///////////////////////////////////////////////////////////////////////////////
// regex functions
bool HHVM_FUNCTION(mb_ereg_match,
const String& pattern,
const String& str,
const Variant& opt_option) {
const String option = convertArg(opt_option);
OnigSyntaxType *syntax;
OnigOptionType noption = 0;
if (!option.empty()) {
_php_mb_regex_init_options(option.data(), option.size(), &noption,
&syntax, nullptr);
} else {
noption |= MBSTRG(regex_default_options);
syntax = MBSTRG(regex_default_syntax);
}
php_mb_regex_t *re;
if ((re = php_mbregex_compile_pattern
(pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) {
return false;
}
/* match */
int err = onig_match(re, (OnigUChar *)str.data(),
(OnigUChar *)(str.data() + str.size()),
(OnigUChar *)str.data(), nullptr, 0);
return err >= 0;
}
static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern,
const String& replacement,
const String& str,
const String& option,
OnigOptionType options) {
const char *p;
php_mb_regex_t *re;
OnigSyntaxType *syntax;
OnigRegion *regs = nullptr;
StringBuffer out_buf;
int i, err, eval, n;
OnigUChar *pos;
OnigUChar *string_lim;
char pat_buf[2];
const mbfl_encoding *enc;
{
const char *current_enc_name;
current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype));
if (current_enc_name == nullptr ||
(enc = mbfl_name2encoding(current_enc_name)) == nullptr) {
raise_warning("Unknown error");
return false;
}
}
eval = 0;
{
if (!option.empty()) {
_php_mb_regex_init_options(option.data(), option.size(),
&options, &syntax, &eval);
} else {
options |= MBSTRG(regex_default_options);
syntax = MBSTRG(regex_default_syntax);
}
}
String spattern;
if (pattern.isString()) {
spattern = pattern.toString();
} else {
/* FIXME: this code is not multibyte aware! */
pat_buf[0] = pattern.toByte();
pat_buf[1] = '\0';
spattern = String(pat_buf, 1, CopyString);
}
/* create regex pattern buffer */
re = php_mbregex_compile_pattern(spattern, options,
MBSTRG(current_mbctype), syntax);
if (re == nullptr) {
return false;
}
if (eval) {
throw_not_supported("ereg_replace", "dynamic coding");
}
/* do the actual work */
err = 0;
pos = (OnigUChar*)str.data();
string_lim = (OnigUChar*)(str.data() + str.size());
regs = onig_region_new();
while (err >= 0) {
err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim,
pos, (OnigUChar *)string_lim, regs, 0);
if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
raise_warning("mbregex search failure: %s", err_str);
break;
}
if (err >= 0) {
#if moriyoshi_0
if (regs->beg[0] == regs->end[0]) {
raise_warning("Empty regular expression");
break;
}
#endif
/* copy the part of the string before the match */
out_buf.append((const char *)pos,
(OnigUChar *)(str.data() + regs->beg[0]) - pos);
/* copy replacement and backrefs */
i = 0;
p = replacement.data();
while (i < replacement.size()) {
int fwd = (int)php_mb_mbchar_bytes_ex(p, enc);
n = -1;
auto const remaining = replacement.size() - i;
if (remaining >= 2 && fwd == 1 &&
p[0] == '\\' && p[1] >= '0' && p[1] <= '9') {
n = p[1] - '0';
}
if (n >= 0 && n < regs->num_regs) {
if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] &&
regs->end[n] <= str.size()) {
out_buf.append(str.data() + regs->beg[n],
regs->end[n] - regs->beg[n]);
}
p += 2;
i += 2;
} else if (remaining >= fwd) {
out_buf.append(p, fwd);
p += fwd;
i += fwd;
} else {
raise_warning("Replacement ends with unterminated %s: 0x%hhx",
enc->name, *p);
break;
}
}
n = regs->end[0];
if ((pos - (OnigUChar *)str.data()) < n) {
pos = (OnigUChar *)(str.data() + n);
} else {
if (pos < string_lim) {
out_buf.append((const char *)pos, 1);
}
pos++;
}
} else { /* nomatch */
/* stick that last bit of string on our output */
if (string_lim - pos > 0) {
out_buf.append((const char *)pos, string_lim - pos);
}
}
onig_region_free(regs, 0);
}
if (regs != nullptr) {
onig_region_free(regs, 1);
}
if (err <= -2) {
return false;
}
return out_buf.detach();
}
Variant HHVM_FUNCTION(mb_ereg_replace,
const Variant& pattern,
const String& replacement,
const String& str,
const Variant& opt_option) {
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_replace_exec(pattern, replacement,
str, option, 0);
}
Variant HHVM_FUNCTION(mb_eregi_replace,
const Variant& pattern,
const String& replacement,
const String& str,
const Variant& opt_option) {
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_replace_exec(pattern, replacement,
str, option, ONIG_OPTION_IGNORECASE);
}
int64_t HHVM_FUNCTION(mb_ereg_search_getpos) {
return MBSTRG(search_pos);
}
bool HHVM_FUNCTION(mb_ereg_search_setpos,
int position) {
if (position < 0 || position >= (int)MBSTRG(search_str).size()) {
raise_warning("Position is out of range");
MBSTRG(search_pos) = 0;
return false;
}
MBSTRG(search_pos) = position;
return true;
}
Variant HHVM_FUNCTION(mb_ereg_search_getregs) {
OnigRegion *search_regs = MBSTRG(search_regs);
if (search_regs && !MBSTRG(search_str).empty()) {
Array ret;
OnigUChar *str = (OnigUChar *)MBSTRG(search_str).data();
int len = MBSTRG(search_str).size();
int n = search_regs->num_regs;
for (int i = 0; i < n; i++) {
int beg = search_regs->beg[i];
int end = search_regs->end[i];
if (beg >= 0 && beg <= end && end <= len) {
ret.append(String((const char *)(str + beg), end - beg, CopyString));
} else {
ret.append(false);
}
}
return ret;
}
return false;
}
bool HHVM_FUNCTION(mb_ereg_search_init,
const String& str,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
OnigOptionType noption = MBSTRG(regex_default_options);
OnigSyntaxType *syntax = MBSTRG(regex_default_syntax);
if (!option.empty()) {
noption = 0;
_php_mb_regex_init_options(option.data(), option.size(),
&noption, &syntax, nullptr);
}
if (!pattern.empty()) {
if ((MBSTRG(search_re) = php_mbregex_compile_pattern
(pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) {
return false;
}
}
MBSTRG(search_str) = std::string(str.data(), str.size());
MBSTRG(search_pos) = 0;
if (MBSTRG(search_regs) != nullptr) {
onig_region_free(MBSTRG(search_regs), 1);
MBSTRG(search_regs) = (OnigRegion *)nullptr;
}
return true;
}
/* regex search */
static Variant _php_mb_regex_ereg_search_exec(const String& pattern,
const String& option,
int mode) {
int n, i, err, pos, len, beg, end;
OnigUChar *str;
OnigSyntaxType *syntax = MBSTRG(regex_default_syntax);
OnigOptionType noption;
noption = MBSTRG(regex_default_options);
if (!option.empty()) {
noption = 0;
_php_mb_regex_init_options(option.data(), option.size(),
&noption, &syntax, nullptr);
}
if (!pattern.empty()) {
if ((MBSTRG(search_re) = php_mbregex_compile_pattern
(pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) {
return false;
}
}
pos = MBSTRG(search_pos);
str = nullptr;
len = 0;
if (!MBSTRG(search_str).empty()) {
str = (OnigUChar *)MBSTRG(search_str).data();
len = MBSTRG(search_str).size();
}
if (MBSTRG(search_re) == nullptr) {
raise_warning("No regex given");
return false;
}
if (str == nullptr) {
raise_warning("No string given");
return false;
}
if (MBSTRG(search_regs)) {
onig_region_free(MBSTRG(search_regs), 1);
}
MBSTRG(search_regs) = onig_region_new();
err = onig_search(MBSTRG(search_re), str, str + len, str + pos, str + len,
MBSTRG(search_regs), 0);
Variant ret;
if (err == ONIG_MISMATCH) {
MBSTRG(search_pos) = len;
ret = false;
} else if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
raise_warning("mbregex search failure in mbregex_search(): %s", err_str);
ret = false;
} else {
if (MBSTRG(search_regs)->beg[0] == MBSTRG(search_regs)->end[0]) {
raise_warning("Empty regular expression");
}
switch (mode) {
case 1:
{
beg = MBSTRG(search_regs)->beg[0];
end = MBSTRG(search_regs)->end[0];
ret = make_packed_array(beg, end - beg);
}
break;
case 2:
n = MBSTRG(search_regs)->num_regs;
ret = Variant(Array::Create());
for (i = 0; i < n; i++) {
beg = MBSTRG(search_regs)->beg[i];
end = MBSTRG(search_regs)->end[i];
if (beg >= 0 && beg <= end && end <= len) {
ret.toArrRef().append(
String((const char *)(str + beg), end - beg, CopyString));
} else {
ret.toArrRef().append(false);
}
}
break;
default:
ret = true;
break;
}
end = MBSTRG(search_regs)->end[0];
if (pos < end) {
MBSTRG(search_pos) = end;
} else {
MBSTRG(search_pos) = pos + 1;
}
}
if (err < 0) {
onig_region_free(MBSTRG(search_regs), 1);
MBSTRG(search_regs) = (OnigRegion *)nullptr;
}
return ret;
}
Variant HHVM_FUNCTION(mb_ereg_search,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_search_exec(pattern, option, 0);
}
Variant HHVM_FUNCTION(mb_ereg_search_pos,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_search_exec(pattern, option, 1);
}
Variant HHVM_FUNCTION(mb_ereg_search_regs,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_search_exec(pattern, option, 2);
}
static Variant _php_mb_regex_ereg_exec(const Variant& pattern, const String& str,
Variant *regs, int icase) {
php_mb_regex_t *re;
OnigRegion *regions = nullptr;
int i, match_len, beg, end;
OnigOptionType options;
options = MBSTRG(regex_default_options);
if (icase) {
options |= ONIG_OPTION_IGNORECASE;
}
/* compile the regular expression from the supplied regex */
String spattern;
if (!pattern.isString()) {
/* we convert numbers to integers and treat them as a string */
if (pattern.is(KindOfDouble)) {
spattern = String(pattern.toInt64()); /* get rid of decimal places */
} else {
spattern = pattern.toString();
}
} else {
spattern = pattern.toString();
}
re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype),
MBSTRG(regex_default_syntax));
if (re == nullptr) {
return false;
}
regions = onig_region_new();
/* actually execute the regular expression */
if (onig_search(re, (OnigUChar *)str.data(),
(OnigUChar *)(str.data() + str.size()),
(OnigUChar *)str.data(),
(OnigUChar *)(str.data() + str.size()),
regions, 0) < 0) {
onig_region_free(regions, 1);
return false;
}
const char *s = str.data();
int string_len = str.size();
match_len = regions->end[0] - regions->beg[0];
PackedArrayInit regsPai(regions->num_regs);
for (i = 0; i < regions->num_regs; i++) {
beg = regions->beg[i];
end = regions->end[i];
if (beg >= 0 && beg < end && end <= string_len) {
regsPai.append(String(s + beg, end - beg, CopyString));
} else {
regsPai.append(false);
}
}
if (regs) *regs = regsPai.toArray();
if (match_len == 0) {
match_len = 1;
}
if (regions != nullptr) {
onig_region_free(regions, 1);
}
return match_len;
}
Variant HHVM_FUNCTION(mb_ereg,
const Variant& pattern,
const String& str,
Variant& regs) {
return _php_mb_regex_ereg_exec(pattern, str, ®s, 0);
}
Variant HHVM_FUNCTION(mb_eregi,
const Variant& pattern,
const String& str,
Variant& regs) {
return _php_mb_regex_ereg_exec(pattern, str, ®s, 1);
}
Variant HHVM_FUNCTION(mb_regex_encoding,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
if (encoding.empty()) {
const char *retval = php_mb_regex_mbctype2name(MBSTRG(current_mbctype));
if (retval != nullptr) {
return String(retval, CopyString);
}
return false;
}
OnigEncoding mbctype = php_mb_regex_name2mbctype(encoding.data());
if (mbctype == ONIG_ENCODING_UNDEF) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
MBSTRG(current_mbctype) = mbctype;
return true;
}
static void php_mb_regex_set_options(OnigOptionType options,
OnigSyntaxType *syntax,
OnigOptionType *prev_options,
OnigSyntaxType **prev_syntax) {
if (prev_options != nullptr) {
*prev_options = MBSTRG(regex_default_options);
}
if (prev_syntax != nullptr) {
*prev_syntax = MBSTRG(regex_default_syntax);
}
MBSTRG(regex_default_options) = options;
MBSTRG(regex_default_syntax) = syntax;
}
String HHVM_FUNCTION(mb_regex_set_options,
const Variant& opt_options) {
const String options = convertArg(opt_options);
OnigOptionType opt;
OnigSyntaxType *syntax;
char buf[16];
if (!options.empty()) {
opt = 0;
syntax = nullptr;
_php_mb_regex_init_options(options.data(), options.size(),
&opt, &syntax, nullptr);
php_mb_regex_set_options(opt, syntax, nullptr, nullptr);
} else {
opt = MBSTRG(regex_default_options);
syntax = MBSTRG(regex_default_syntax);
}
_php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax);
return String(buf, CopyString);
}
Variant HHVM_FUNCTION(mb_split,
const String& pattern,
const String& str,
int count /* = -1 */) {
php_mb_regex_t *re;
OnigRegion *regs = nullptr;
int n, err;
if (count == 0) {
count = 1;
}
/* create regex pattern buffer */
if ((re = php_mbregex_compile_pattern(pattern,
MBSTRG(regex_default_options),
MBSTRG(current_mbctype),
MBSTRG(regex_default_syntax)))
== nullptr) {
return false;
}
Array ret;
OnigUChar *pos0 = (OnigUChar *)str.data();
OnigUChar *pos_end = (OnigUChar *)(str.data() + str.size());
OnigUChar *pos = pos0;
err = 0;
regs = onig_region_new();
/* churn through str, generating array entries as we go */
while ((--count != 0) &&
(err = onig_search(re, pos0, pos_end, pos, pos_end, regs, 0)) >= 0) {
if (regs->beg[0] == regs->end[0]) {
raise_warning("Empty regular expression");
break;
}
/* add it to the array */
if (regs->beg[0] < str.size() && regs->beg[0] >= (pos - pos0)) {
ret.append(String((const char *)pos,
((OnigUChar *)(str.data() + regs->beg[0]) - pos),
CopyString));
} else {
err = -2;
break;
}
/* point at our new starting point */
n = regs->end[0];
if ((pos - pos0) < n) {
pos = pos0 + n;
}
if (count < 0) {
count = 0;
}
onig_region_free(regs, 0);
}
onig_region_free(regs, 1);
/* see if we encountered an error */
if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
raise_warning("mbregex search failure in mbsplit(): %s", err_str);
return false;
}
/* otherwise we just have one last element to add to the array */
n = pos_end - pos;
if (n > 0) {
ret.append(String((const char *)pos, n, CopyString));
} else {
ret.append("");
}
return ret;
}
///////////////////////////////////////////////////////////////////////////////
#define SKIP_LONG_HEADER_SEP_MBSTRING(str, pos) \
if (str[pos] == '\r' && str[pos + 1] == '\n' && \
(str[pos + 2] == ' ' || str[pos + 2] == '\t')) { \
pos += 2; \
while (str[pos + 1] == ' ' || str[pos + 1] == '\t') { \
pos++; \
} \
continue; \
}
static int _php_mbstr_parse_mail_headers(Array &ht, const char *str,
size_t str_len) {
const char *ps;
size_t icnt;
int state = 0;
int crlf_state = -1;
StringBuffer token;
String fld_name, fld_val;
ps = str;
icnt = str_len;
/*
* C o n t e n t - T y p e : t e x t / h t m l \r\n
* ^ ^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^^^
* state 0 1 2 3
*
* C o n t e n t - T y p e : t e x t / h t m l \r\n
* ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^
* crlf_state -1 0 1 -1
*
*/
while (icnt > 0) {
switch (*ps) {
case ':':
if (crlf_state == 1) {
token.append('\r');
}
if (state == 0 || state == 1) {
fld_name = token.detach();
state = 2;
} else {
token.append(*ps);
}
crlf_state = 0;
break;
case '\n':
if (crlf_state == -1) {
goto out;
}
crlf_state = -1;
break;
case '\r':
if (crlf_state == 1) {
token.append('\r');
} else {
crlf_state = 1;
}
break;
case ' ': case '\t':
if (crlf_state == -1) {
if (state == 3) {
/* continuing from the previous line */
state = 4;
} else {
/* simply skipping this new line */
state = 5;
}
} else {
if (crlf_state == 1) {
token.append('\r');
}
if (state == 1 || state == 3) {
token.append(*ps);
}
}
crlf_state = 0;
break;
default:
switch (state) {
case 0:
token.clear();
state = 1;
break;
case 2:
if (crlf_state != -1) {
token.clear();
state = 3;
break;
}
/* break is missing intentionally */
case 3:
if (crlf_state == -1) {
fld_val = token.detach();
if (!fld_name.empty() && !fld_val.empty()) {
/* FIXME: some locale free implementation is
* really required here,,, */
ht.set(HHVM_FN(strtoupper)(fld_name), fld_val);
}
state = 1;
}
break;
case 4:
token.append(' ');
state = 3;
break;
}
if (crlf_state == 1) {
token.append('\r');
}
token.append(*ps);
crlf_state = 0;
break;
}
ps++, icnt--;
}
out:
if (state == 2) {
token.clear();
state = 3;
}
if (state == 3) {
fld_val = token.detach();
if (!fld_name.empty() && !fld_val.empty()) {
/* FIXME: some locale free implementation is
* really required here,,, */
ht.set(HHVM_FN(strtoupper)(fld_name), fld_val);
}
}
return state;
}
static int php_mail(const char *to, const char *subject, const char *message,
const char *headers, const char *extra_cmd) {
const char *sendmail_path = "/usr/sbin/sendmail -t -i";
String sendmail_cmd = sendmail_path;
if (extra_cmd != nullptr) {
sendmail_cmd += " ";
sendmail_cmd += extra_cmd;
}
/* Since popen() doesn't indicate if the internal fork() doesn't work
* (e.g. the shell can't be executed) we explicitly set it to 0 to be
* sure we don't catch any older errno value. */
errno = 0;
FILE *sendmail = popen(sendmail_cmd.data(), "w");
if (sendmail == nullptr) {
raise_warning("Could not execute mail delivery program '%s'",
sendmail_path);
return 0;
}
if (EACCES == errno) {
raise_warning("Permission denied: unable to execute shell to run "
"mail delivery binary '%s'", sendmail_path);
pclose(sendmail);
return 0;
}
fprintf(sendmail, "To: %s\n", to);
fprintf(sendmail, "Subject: %s\n", subject);
if (headers != nullptr) {
fprintf(sendmail, "%s\n", headers);
}
fprintf(sendmail, "\n%s\n", message);
int ret = pclose(sendmail);
#if defined(EX_TEMPFAIL)
if ((ret != EX_OK) && (ret != EX_TEMPFAIL)) return 0;
#elif defined(EX_OK)
if (ret != EX_OK) return 0;
#else
if (ret != 0) return 0;
#endif
return 1;
}
bool HHVM_FUNCTION(mb_send_mail,
const String& to,
const String& subject,
const String& message,
const Variant& opt_headers,
const Variant& opt_extra_cmd) {
const String headers = convertArg(opt_headers);
const String extra_cmd = convertArg(opt_extra_cmd);
/* initialize */
/* automatic allocateable buffer for additional header */
mbfl_memory_device device;
mbfl_memory_device_init(&device, 0, 0);
mbfl_string orig_str, conv_str;
mbfl_string_init(&orig_str);
mbfl_string_init(&conv_str);
/* character-set, transfer-encoding */
mbfl_no_encoding
tran_cs, /* transfar text charset */
head_enc, /* header transfar encoding */
body_enc; /* body transfar encoding */
tran_cs = mbfl_no_encoding_utf8;
head_enc = mbfl_no_encoding_base64;
body_enc = mbfl_no_encoding_base64;
const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language));
if (lang != nullptr) {
tran_cs = lang->mail_charset;
head_enc = lang->mail_header_encoding;
body_enc = lang->mail_body_encoding;
}
Array ht_headers;
if (!headers.empty()) {
_php_mbstr_parse_mail_headers(ht_headers, headers.data(), headers.size());
}
struct {
unsigned int cnt_type:1;
unsigned int cnt_trans_enc:1;
} suppressed_hdrs = { 0, 0 };
static const StaticString s_CONTENT_TYPE("CONTENT-TYPE");
String s = ht_headers[s_CONTENT_TYPE].toString();
if (!s.isNull()) {
char *tmp;
char *param_name;
char *charset = nullptr;
char *p = const_cast<char*>(strchr(s.data(), ';'));
if (p != nullptr) {
/* skipping the padded spaces */
do {
++p;
} while (*p == ' ' || *p == '\t');
if (*p != '\0') {
if ((param_name = strtok_r(p, "= ", &tmp)) != nullptr) {
if (strcasecmp(param_name, "charset") == 0) {
mbfl_no_encoding _tran_cs = tran_cs;
charset = strtok_r(nullptr, "= ", &tmp);
if (charset != nullptr) {
_tran_cs = mbfl_name2no_encoding(charset);
}
if (_tran_cs == mbfl_no_encoding_invalid) {
raise_warning("Unsupported charset \"%s\" - "
"will be regarded as ascii", charset);
_tran_cs = mbfl_no_encoding_ascii;
}
tran_cs = _tran_cs;
}
}
}
}
suppressed_hdrs.cnt_type = 1;
}
static const StaticString
s_CONTENT_TRANSFER_ENCODING("CONTENT-TRANSFER-ENCODING");
s = ht_headers[s_CONTENT_TRANSFER_ENCODING].toString();
if (!s.isNull()) {
mbfl_no_encoding _body_enc = mbfl_name2no_encoding(s.data());
switch (_body_enc) {
case mbfl_no_encoding_base64:
case mbfl_no_encoding_7bit:
case mbfl_no_encoding_8bit:
body_enc = _body_enc;
break;
default:
raise_warning("Unsupported transfer encoding \"%s\" - "
"will be regarded as 8bit", s.data());
body_enc = mbfl_no_encoding_8bit;
break;
}
suppressed_hdrs.cnt_trans_enc = 1;
}
/* To: */
char *to_r = nullptr;
int err = 0;
if (auto to_len = strlen(to.data())) { // not to.size()
to_r = req::strndup(to.data(), to_len);
for (; to_len; to_len--) {
if (!isspace((unsigned char)to_r[to_len - 1])) {
break;
}
to_r[to_len - 1] = '\0';
}
for (size_t i = 0; to_r[i]; i++) {
if (iscntrl((unsigned char)to_r[i])) {
/**
* According to RFC 822, section 3.1.1 long headers may be
* separated into parts using CRLF followed at least one
* linear-white-space character ('\t' or ' ').
* To prevent these separators from being replaced with a space,
* we use the SKIP_LONG_HEADER_SEP_MBSTRING to skip over them.
*/
SKIP_LONG_HEADER_SEP_MBSTRING(to_r, i);
to_r[i] = ' ';
}
}
} else {
raise_warning("Missing To: field");
err = 1;
}
/* Subject: */
String encoded_subject;
if (!subject.isNull()) {
orig_str.no_language = MBSTRG(current_language);
orig_str.val = (unsigned char *)subject.data();
orig_str.len = subject.size();
orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
if (orig_str.no_encoding == mbfl_no_encoding_invalid
|| orig_str.no_encoding == mbfl_no_encoding_pass) {
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_identify_encoding2(&orig_str,
(const mbfl_encoding**) MBSTRG(current_detect_order_list),
MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection));
orig_str.no_encoding = encoding != nullptr
? encoding->no_encoding
: mbfl_no_encoding_invalid;
}
mbfl_string *pstr = mbfl_mime_header_encode
(&orig_str, &conv_str, tran_cs, head_enc,
"\n", sizeof("Subject: [PHP-jp nnnnnnnn]"));
if (pstr != nullptr) {
encoded_subject = String(reinterpret_cast<char*>(pstr->val),
pstr->len,
AttachString);
}
} else {
raise_warning("Missing Subject: field");
err = 1;
}
/* message body */
String encoded_message;
if (!message.empty()) {
orig_str.no_language = MBSTRG(current_language);
orig_str.val = (unsigned char*)message.data();
orig_str.len = message.size();
orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
if (orig_str.no_encoding == mbfl_no_encoding_invalid
|| orig_str.no_encoding == mbfl_no_encoding_pass) {
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_identify_encoding2(&orig_str,
(const mbfl_encoding**) MBSTRG(current_detect_order_list),
MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection));
orig_str.no_encoding = encoding != nullptr
? encoding->no_encoding
: mbfl_no_encoding_invalid;
}
mbfl_string *pstr = nullptr;
{
mbfl_string tmpstr;
if (mbfl_convert_encoding(&orig_str, &tmpstr, tran_cs) != nullptr) {
tmpstr.no_encoding = mbfl_no_encoding_8bit;
pstr = mbfl_convert_encoding(&tmpstr, &conv_str, body_enc);
free(tmpstr.val);
}
}
if (pstr != nullptr) {
encoded_message = String(reinterpret_cast<char*>(pstr->val),
pstr->len,
AttachString);
}
} else {
/* this is not really an error, so it is allowed. */
raise_warning("Empty message body");
}
/* other headers */
#define PHP_MBSTR_MAIL_MIME_HEADER1 "Mime-Version: 1.0"
#define PHP_MBSTR_MAIL_MIME_HEADER2 "Content-Type: text/plain"
#define PHP_MBSTR_MAIL_MIME_HEADER3 "; charset="
#define PHP_MBSTR_MAIL_MIME_HEADER4 "Content-Transfer-Encoding: "
if (!headers.empty()) {
const char *p = headers.data();
int n = headers.size();
mbfl_memory_device_strncat(&device, p, n);
if (n > 0 && p[n - 1] != '\n') {
mbfl_memory_device_strncat(&device, "\n", 1);
}
}
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER1,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER1) - 1);
mbfl_memory_device_strncat(&device, "\n", 1);
if (!suppressed_hdrs.cnt_type) {
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER2,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER2) - 1);
char *p = (char *)mbfl_no2preferred_mime_name(tran_cs);
if (p != nullptr) {
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER3,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER3) - 1);
mbfl_memory_device_strcat(&device, p);
}
mbfl_memory_device_strncat(&device, "\n", 1);
}
if (!suppressed_hdrs.cnt_trans_enc) {
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER4,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER4) - 1);
const char *p = (char *)mbfl_no2preferred_mime_name(body_enc);
if (p == nullptr) {
p = "7bit";
}
mbfl_memory_device_strcat(&device, p);
mbfl_memory_device_strncat(&device, "\n", 1);
}
mbfl_memory_device_unput(&device);
mbfl_memory_device_output('\0', &device);
char *all_headers = (char *)device.buffer;
String cmd = string_escape_shell_cmd(extra_cmd.c_str());
bool ret = (!err && php_mail(to_r, encoded_subject.data(),
encoded_message.data(),
all_headers, cmd.data()));
mbfl_memory_device_clear(&device);
req::free(to_r);
return ret;
}
static struct mbstringExtension final : Extension {
mbstringExtension() : Extension("mbstring", NO_EXTENSION_VERSION_YET) {}
void moduleInit() override {
// TODO make these PHP_INI_ALL and thread local once we use them
IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_input",
&http_input);
IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_output",
&http_output);
IniSetting::Bind(this, IniSetting::PHP_INI_ALL,
"mbstring.substitute_character",
&MBSTRG(current_filter_illegal_mode));
HHVM_RC_INT(MB_OVERLOAD_MAIL, 1);
HHVM_RC_INT(MB_OVERLOAD_STRING, 2);
HHVM_RC_INT(MB_OVERLOAD_REGEX, 4);
HHVM_RC_INT(MB_CASE_UPPER, PHP_UNICODE_CASE_UPPER);
HHVM_RC_INT(MB_CASE_LOWER, PHP_UNICODE_CASE_LOWER);
HHVM_RC_INT(MB_CASE_TITLE, PHP_UNICODE_CASE_TITLE);
HHVM_FE(mb_list_encodings);
HHVM_FE(mb_list_encodings_alias_names);
HHVM_FE(mb_list_mime_names);
HHVM_FE(mb_check_encoding);
HHVM_FE(mb_convert_case);
HHVM_FE(mb_convert_encoding);
HHVM_FE(mb_convert_kana);
HHVM_FE(mb_convert_variables);
HHVM_FE(mb_decode_mimeheader);
HHVM_FE(mb_decode_numericentity);
HHVM_FE(mb_detect_encoding);
HHVM_FE(mb_detect_order);
HHVM_FE(mb_encode_mimeheader);
HHVM_FE(mb_encode_numericentity);
HHVM_FE(mb_encoding_aliases);
HHVM_FE(mb_ereg_match);
HHVM_FE(mb_ereg_replace);
HHVM_FE(mb_ereg_search_getpos);
HHVM_FE(mb_ereg_search_getregs);
HHVM_FE(mb_ereg_search_init);
HHVM_FE(mb_ereg_search_pos);
HHVM_FE(mb_ereg_search_regs);
HHVM_FE(mb_ereg_search_setpos);
HHVM_FE(mb_ereg_search);
HHVM_FE(mb_ereg);
HHVM_FE(mb_eregi_replace);
HHVM_FE(mb_eregi);
HHVM_FE(mb_get_info);
HHVM_FE(mb_http_input);
HHVM_FE(mb_http_output);
HHVM_FE(mb_internal_encoding);
HHVM_FE(mb_language);
HHVM_FE(mb_output_handler);
HHVM_FE(mb_parse_str);
HHVM_FE(mb_preferred_mime_name);
HHVM_FE(mb_regex_encoding);
HHVM_FE(mb_regex_set_options);
HHVM_FE(mb_send_mail);
HHVM_FE(mb_split);
HHVM_FE(mb_strcut);
HHVM_FE(mb_strimwidth);
HHVM_FE(mb_stripos);
HHVM_FE(mb_stristr);
HHVM_FE(mb_strlen);
HHVM_FE(mb_strpos);
HHVM_FE(mb_strrchr);
HHVM_FE(mb_strrichr);
HHVM_FE(mb_strripos);
HHVM_FE(mb_strrpos);
HHVM_FE(mb_strstr);
HHVM_FE(mb_strtolower);
HHVM_FE(mb_strtoupper);
HHVM_FE(mb_strwidth);
HHVM_FE(mb_substitute_character);
HHVM_FE(mb_substr_count);
HHVM_FE(mb_substr);
loadSystemlib();
}
static std::string http_input;
static std::string http_output;
static std::string substitute_character;
} s_mbstring_extension;
std::string mbstringExtension::http_input = "pass";
std::string mbstringExtension::http_output = "pass";
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_847_0 |
crossvul-cpp_data_good_4220_1 | /* -*- C++ -*-
* Copyright 2019-2020 LibRaw LLC (info@libraw.org)
*
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
*/
#include "../../internal/libraw_cxx_defs.h"
#ifndef NO_JPEG
struct jpegErrorManager
{
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
static void jpegErrorExit(j_common_ptr cinfo)
{
jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err;
longjmp(myerr->setjmp_buffer, 1);
}
#endif
int LibRaw::unpack_thumb(void)
{
CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY);
CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD);
#define THUMB_SIZE_CHECKT(A) \
do { \
if (INT64(A) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \
if (INT64(A) > 0 && INT64(A) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \
} while (0)
#define THUMB_SIZE_CHECKTNZ(A) \
do { \
if (INT64(A) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \
if (INT64(A) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \
} while (0)
#define THUMB_SIZE_CHECKWH(W,H) \
do { \
if (INT64(W)*INT64(H) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \
if (INT64(W)*INT64(H) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \
} while (0)
try
{
if (!libraw_internal_data.internal_data.input)
return LIBRAW_INPUT_CLOSED;
int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7;
int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8;
if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
load_raw == &LibRaw::broadcom_load_raw) // RPi
)
{
return LIBRAW_NO_THUMBNAIL;
}
else if (thumb_load_raw)
{
kodak_thumb_loader();
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else
{
#ifdef USE_X3FTOOLS
if (write_thumb == &LibRaw::x3f_thumb_loader)
{
INT64 tsize = x3f_thumb_size();
if (tsize < 2048 || INT64(ID.toffset) + tsize < 1)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND)
throw LIBRAW_EXCEPTION_IO_EOF;
THUMB_SIZE_CHECKT(tsize);
}
#else
if (0) {}
#endif
else
{
if (INT64(ID.toffset) + INT64(T.tlength) < 1)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (INT64(ID.toffset) + INT64(T.tlength) >
ID.input->size() + THUMB_READ_BEYOND)
throw LIBRAW_EXCEPTION_IO_EOF;
}
ID.input->seek(ID.toffset, SEEK_SET);
if (write_thumb == &LibRaw::jpeg_thumb)
{
THUMB_SIZE_CHECKTNZ(T.tlength);
if (T.thumb)
free(T.thumb);
T.thumb = (char *)malloc(T.tlength);
merror(T.thumb, "jpeg_thumb()");
ID.input->read(T.thumb, 1, T.tlength);
unsigned char *tthumb = (unsigned char *)T.thumb;
tthumb[0] = 0xff;
tthumb[1] = 0xd8;
#ifdef NO_JPEG
T.tcolors = 3;
#else
{
jpegErrorManager jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jpegErrorExit;
if (setjmp(jerr.setjmp_buffer))
{
err2:
// Error in original JPEG thumb, read it again because
// original bytes 0-1 was damaged above
jpeg_destroy_decompress(&cinfo);
T.tcolors = 3;
T.tformat = LIBRAW_THUMBNAIL_UNKNOWN;
ID.input->seek(ID.toffset, SEEK_SET);
ID.input->read(T.thumb, 1, T.tlength);
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength);
int rc = jpeg_read_header(&cinfo, TRUE);
if (rc != 1)
goto err2;
T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3)
? cinfo.num_components
: 3;
jpeg_destroy_decompress(&cinfo);
}
#endif
T.tformat = LIBRAW_THUMBNAIL_JPEG;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::layer_thumb)
{
int colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7;
if (colors != 1 && colors != 3)
return LIBRAW_UNSUPPORTED_THUMBNAIL;
THUMB_SIZE_CHECKWH(T.twidth, T.theight);
int tlength = T.twidth * T.theight;
if (T.thumb)
free(T.thumb);
T.thumb = (char *)calloc(colors, tlength);
merror(T.thumb, "layer_thumb()");
unsigned char *tbuf = (unsigned char *)calloc(colors, tlength);
merror(tbuf, "layer_thumb()");
ID.input->read(tbuf, colors, T.tlength);
if (libraw_internal_data.unpacker_data.thumb_misc >> 8 &&
colors == 3) // GRB order
for (int i = 0; i < tlength; i++)
{
T.thumb[i * 3] = tbuf[i + tlength];
T.thumb[i * 3 + 1] = tbuf[i];
T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength];
}
else if (colors == 3) // RGB or 1-channel
for (int i = 0; i < tlength; i++)
{
T.thumb[i * 3] = tbuf[i];
T.thumb[i * 3 + 1] = tbuf[i + tlength];
T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength];
}
else if (colors == 1)
{
free(T.thumb);
T.thumb = (char *)tbuf;
tbuf = 0;
}
if (tbuf)
free(tbuf);
T.tcolors = colors;
T.tlength = colors * tlength;
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::rollei_thumb)
{
int i;
THUMB_SIZE_CHECKWH(T.twidth, T.theight);
int tlength = T.twidth * T.theight;
if (T.thumb)
free(T.thumb);
T.tcolors = 3;
T.thumb = (char *)calloc(T.tcolors, tlength);
merror(T.thumb, "layer_thumb()");
unsigned short *tbuf = (unsigned short *)calloc(2, tlength);
merror(tbuf, "layer_thumb()");
read_shorts(tbuf, tlength);
for (i = 0; i < tlength; i++)
{
T.thumb[i * 3] = (tbuf[i] << 3) & 0xff;
T.thumb[i * 3 + 1] = (tbuf[i] >> 5 << 2) & 0xff;
T.thumb[i * 3 + 2] = (tbuf[i] >> 11 << 3) & 0xff;
}
free(tbuf);
T.tlength = T.tcolors * tlength;
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::ppm_thumb)
{
if (t_bytesps > 1)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more
// bits
THUMB_SIZE_CHECKWH(T.twidth, T.theight);
int t_length = T.twidth * T.theight * t_colors;
if (T.tlength &&
(int)T.tlength < t_length) // try to find tiff ifd with needed offset
{
int pifd = find_ifd_by_offset(libraw_internal_data.internal_data.toffset);
if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count &&
tiff_ifd[pifd].strip_byte_counts_count)
{
// We found it, calculate final size
unsigned total_size = 0;
for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++)
total_size += tiff_ifd[pifd].strip_byte_counts[i];
if (total_size != (unsigned)t_length) // recalculate colors
{
if (total_size == T.twidth * T.tlength * 3)
T.tcolors = 3;
else if (total_size == T.twidth * T.tlength)
T.tcolors = 1;
}
T.tlength = total_size;
THUMB_SIZE_CHECKTNZ(T.tlength);
if (T.thumb)
free(T.thumb);
T.thumb = (char *)malloc(T.tlength);
merror(T.thumb, "ppm_thumb()");
char *dest = T.thumb;
INT64 pos = ID.input->tell();
for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count &&
i < tiff_ifd[pifd].strip_offsets_count;
i++)
{
int remain = T.tlength;
int sz = tiff_ifd[pifd].strip_byte_counts[i];
int off = tiff_ifd[pifd].strip_offsets[i];
if (off >= 0 && off + sz <= ID.input->size() && sz <= remain)
{
ID.input->seek(off, SEEK_SET);
ID.input->read(dest, sz, 1);
remain -= sz;
dest += sz;
}
}
ID.input->seek(pos, SEEK_SET);
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
}
if (!T.tlength)
T.tlength = t_length;
if (T.thumb)
free(T.thumb);
THUMB_SIZE_CHECKTNZ(T.tlength);
T.thumb = (char *)malloc(T.tlength);
if (!T.tcolors)
T.tcolors = t_colors;
merror(T.thumb, "ppm_thumb()");
ID.input->read(T.thumb, 1, T.tlength);
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
else if (write_thumb == &LibRaw::ppm16_thumb)
{
if (t_bytesps > 2)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for
// more bits
int o_bps = (imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_USE_PPM16_THUMBS)
? 2
: 1;
int o_length = T.twidth * T.theight * t_colors * o_bps;
int i_length = T.twidth * T.theight * t_colors * 2;
if (!T.tlength)
T.tlength = o_length;
THUMB_SIZE_CHECKTNZ(o_length);
THUMB_SIZE_CHECKTNZ(i_length);
THUMB_SIZE_CHECKTNZ(T.tlength);
ushort *t_thumb = (ushort *)calloc(i_length, 1);
ID.input->read(t_thumb, 1, i_length);
if ((libraw_internal_data.unpacker_data.order == 0x4949) ==
(ntohs(0x1234) == 0x1234))
swab((char *)t_thumb, (char *)t_thumb, i_length);
if (T.thumb)
free(T.thumb);
if ((imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_USE_PPM16_THUMBS))
{
T.thumb = (char *)t_thumb;
T.tformat = LIBRAW_THUMBNAIL_BITMAP16;
}
else
{
T.thumb = (char *)malloc(o_length);
merror(T.thumb, "ppm_thumb()");
for (int i = 0; i < o_length; i++)
T.thumb[i] = t_thumb[i] >> 8;
free(t_thumb);
T.tformat = LIBRAW_THUMBNAIL_BITMAP;
}
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
#ifdef USE_X3FTOOLS
else if (write_thumb == &LibRaw::x3f_thumb_loader)
{
x3f_thumb_loader();
SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD);
return 0;
}
#endif
else
{
return LIBRAW_UNSUPPORTED_THUMBNAIL;
}
}
// last resort
return LIBRAW_UNSUPPORTED_THUMBNAIL;
}
catch (LibRaw_exceptions err)
{
EXCEPTION_HANDLER(err);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_4220_1 |
crossvul-cpp_data_good_4877_0 | #include "Hub.h"
#include "HTTPSocket.h"
#include <openssl/sha.h>
static const int INFLATE_LESS_THAN_ROUGHLY = 16777216;
namespace uWS {
char *Hub::inflate(char *data, size_t &length) {
dynamicInflationBuffer.clear();
inflationStream.next_in = (Bytef *) data;
inflationStream.avail_in = length;
int err;
do {
inflationStream.next_out = (Bytef *) inflationBuffer;
inflationStream.avail_out = LARGE_BUFFER_SIZE;
err = ::inflate(&inflationStream, Z_FINISH);
if (!inflationStream.avail_in) {
break;
}
dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
} while (err == Z_BUF_ERROR && dynamicInflationBuffer.length() <= INFLATE_LESS_THAN_ROUGHLY);
inflateReset(&inflationStream);
if ((err != Z_BUF_ERROR && err != Z_OK) || dynamicInflationBuffer.length() > INFLATE_LESS_THAN_ROUGHLY) {
length = 0;
return nullptr;
}
if (dynamicInflationBuffer.length()) {
dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
length = dynamicInflationBuffer.length();
return (char *) dynamicInflationBuffer.data();
}
length = LARGE_BUFFER_SIZE - inflationStream.avail_out;
return inflationBuffer;
}
void Hub::onServerAccept(uS::Socket s) {
uS::SocketData *socketData = s.getSocketData();
s.startTimeout<HTTPSocket<SERVER>::onEnd>();
s.enterState<HTTPSocket<SERVER>>(new HTTPSocket<SERVER>::Data(socketData));
delete socketData;
}
void Hub::onClientConnection(uS::Socket s, bool error) {
HTTPSocket<CLIENT>::Data *httpSocketData = (HTTPSocket<CLIENT>::Data *) s.getSocketData();
if (error) {
((Group<CLIENT> *) httpSocketData->nodeData)->errorHandler(httpSocketData->httpUser);
delete httpSocketData;
} else {
s.enterState<HTTPSocket<CLIENT>>(s.getSocketData());
HTTPSocket<CLIENT>(s).upgrade();
}
}
bool Hub::listen(int port, uS::TLS::Context sslContext, int options, Group<SERVER> *eh) {
if (!eh) {
eh = (Group<SERVER> *) this;
}
if (uS::Node::listen<onServerAccept>(port, sslContext, options, (uS::NodeData *) eh, nullptr)) {
eh->errorHandler(port);
return false;
}
return true;
}
void Hub::connect(std::string uri, void *user, int timeoutMs, Group<CLIENT> *eh) {
if (!eh) {
eh = (Group<CLIENT> *) this;
}
int offset = 0;
std::string protocol = uri.substr(offset, uri.find("://")), hostname, portStr, path;
if ((offset += protocol.length() + 3) < uri.length()) {
hostname = uri.substr(offset, uri.find_first_of(":/", offset) - offset);
offset += hostname.length();
if (uri[offset] == ':') {
offset++;
portStr = uri.substr(offset, uri.find("/", offset) - offset);
}
offset += portStr.length();
if (uri[offset] == '/') {
path = uri.substr(++offset);
}
}
if (hostname.length()) {
int port = 80;
bool secure = false;
if (protocol == "wss") {
port = 443;
secure = true;
} else if (protocol != "ws") {
eh->errorHandler(user);
}
if (portStr.length()) {
port = stoi(portStr);
}
uS::SocketData socketData((uS::NodeData *) eh);
HTTPSocket<CLIENT>::Data *httpSocketData = new HTTPSocket<CLIENT>::Data(&socketData);
httpSocketData->host = hostname;
httpSocketData->path = path;
httpSocketData->httpUser = user;
uS::Socket s = uS::Node::connect<onClientConnection>(hostname.c_str(), port, secure, httpSocketData);
if (s) {
s.startTimeout<HTTPSocket<CLIENT>::onEnd>(timeoutMs);
}
} else {
eh->errorHandler(user);
}
}
bool Hub::upgrade(uv_os_sock_t fd, const char *secKey, SSL *ssl, const char *extensions, size_t extensionsLength, Group<SERVER> *serverGroup) {
if (!serverGroup) {
serverGroup = &getDefaultGroup<SERVER>();
}
uS::Socket s = uS::Socket::init((uS::NodeData *) serverGroup, fd, ssl);
uS::SocketData *socketData = s.getSocketData();
HTTPSocket<SERVER>::Data *temporaryHttpData = new HTTPSocket<SERVER>::Data(socketData);
delete socketData;
s.enterState<HTTPSocket<SERVER>>(temporaryHttpData);
// todo: move this into upgrade call
bool perMessageDeflate = false;
std::string extensionsResponse;
if (extensionsLength) {
ExtensionsNegotiator<uWS::SERVER> extensionsNegotiator(serverGroup->extensionOptions);
extensionsNegotiator.readOffer(std::string(extensions, extensionsLength));
extensionsResponse = extensionsNegotiator.generateOffer();
if (extensionsNegotiator.getNegotiatedOptions() & PERMESSAGE_DEFLATE) {
perMessageDeflate = true;
}
}
if (HTTPSocket<SERVER>(s).upgrade(secKey, extensionsResponse.data(), extensionsResponse.length())) {
s.enterState<WebSocket<SERVER>>(new WebSocket<SERVER>::Data(perMessageDeflate, s.getSocketData()));
serverGroup->addWebSocket(s);
serverGroup->connectionHandler(WebSocket<SERVER>(s), {nullptr, nullptr, 0, 0});
delete temporaryHttpData;
return true;
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_4877_0 |
crossvul-cpp_data_good_1798_0 | /*
* InspIRCd -- Internet Relay Chat Daemon
*
* Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
* Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
* Copyright (C) 2006, 2009 Robin Burchell <robin+git@viroteck.net>
* Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
* Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
* Copyright (C) 2005-2007 Craig Edwards <craigedwards@brainbox.cc>
*
* This file is part of InspIRCd. InspIRCd is free software: you can
* redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Core */
/*
dns.cpp - Nonblocking DNS functions.
Very very loosely based on the firedns library,
Copyright (C) 2002 Ian Gulliver. This file is no
longer anything like firedns, there are many major
differences between this code and the original.
Please do not assume that firedns works like this,
looks like this, walks like this or tastes like this.
*/
#ifndef _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#include "inspircd_win32wrapper.h"
#endif
#include "inspircd.h"
#include "socketengine.h"
#include "configreader.h"
#include "socket.h"
#define DN_COMP_BITMASK 0xC000 /* highest 6 bits in a DN label header */
/** Masks to mask off the responses we get from the DNSRequest methods
*/
enum QueryInfo
{
ERROR_MASK = 0x10000 /* Result is an error */
};
/** Flags which can be ORed into a request or reply for different meanings
*/
enum QueryFlags
{
FLAGS_MASK_RD = 0x01, /* Recursive */
FLAGS_MASK_TC = 0x02,
FLAGS_MASK_AA = 0x04, /* Authoritative */
FLAGS_MASK_OPCODE = 0x78,
FLAGS_MASK_QR = 0x80,
FLAGS_MASK_RCODE = 0x0F, /* Request */
FLAGS_MASK_Z = 0x70,
FLAGS_MASK_RA = 0x80
};
/** Represents a dns resource record (rr)
*/
struct ResourceRecord
{
QueryType type; /* Record type */
unsigned int rr_class; /* Record class */
unsigned long ttl; /* Time to live */
unsigned int rdlength; /* Record length */
};
/** Represents a dns request/reply header, and its payload as opaque data.
*/
class DNSHeader
{
public:
unsigned char id[2]; /* Request id */
unsigned int flags1; /* Flags */
unsigned int flags2; /* Flags */
unsigned int qdcount;
unsigned int ancount; /* Answer count */
unsigned int nscount; /* Nameserver count */
unsigned int arcount;
unsigned char payload[512]; /* Packet payload */
};
class DNSRequest
{
public:
unsigned char id[2]; /* Request id */
unsigned char* res; /* Result processing buffer */
unsigned int rr_class; /* Request class */
QueryType type; /* Request type */
DNS* dnsobj; /* DNS caller (where we get our FD from) */
unsigned long ttl; /* Time to live */
std::string orig; /* Original requested name/ip */
DNSRequest(DNS* dns, int id, const std::string &original);
~DNSRequest();
DNSInfo ResultIsReady(DNSHeader &h, unsigned length);
int SendRequests(const DNSHeader *header, const int length, QueryType qt);
};
class CacheTimer : public Timer
{
private:
DNS* dns;
public:
CacheTimer(DNS* thisdns)
: Timer(3600, ServerInstance->Time(), true), dns(thisdns) { }
virtual void Tick(time_t)
{
dns->PruneCache();
}
};
class RequestTimeout : public Timer
{
DNSRequest* watch;
int watchid;
public:
RequestTimeout(unsigned long n, DNSRequest* watching, int id) : Timer(n, ServerInstance->Time()), watch(watching), watchid(id)
{
}
~RequestTimeout()
{
if (ServerInstance->Res)
Tick(0);
}
void Tick(time_t)
{
if (ServerInstance->Res->requests[watchid] == watch)
{
/* Still exists, whack it */
if (ServerInstance->Res->Classes[watchid])
{
ServerInstance->Res->Classes[watchid]->OnError(RESOLVER_TIMEOUT, "Request timed out");
delete ServerInstance->Res->Classes[watchid];
ServerInstance->Res->Classes[watchid] = NULL;
}
ServerInstance->Res->requests[watchid] = NULL;
delete watch;
}
}
};
CachedQuery::CachedQuery(const std::string &res, QueryType qt, unsigned int ttl) : data(res), type(qt)
{
expires = ServerInstance->Time() + ttl;
}
int CachedQuery::CalcTTLRemaining()
{
int n = expires - ServerInstance->Time();
return (n < 0 ? 0 : n);
}
/* Allocate the processing buffer */
DNSRequest::DNSRequest(DNS* dns, int rid, const std::string &original) : dnsobj(dns)
{
/* hardening against overflow here: make our work buffer twice the theoretical
* maximum size so that hostile input doesn't screw us over.
*/
res = new unsigned char[sizeof(DNSHeader) * 2];
*res = 0;
orig = original;
RequestTimeout* RT = new RequestTimeout(ServerInstance->Config->dns_timeout ? ServerInstance->Config->dns_timeout : 5, this, rid);
ServerInstance->Timers->AddTimer(RT); /* The timer manager frees this */
}
/* Deallocate the processing buffer */
DNSRequest::~DNSRequest()
{
delete[] res;
}
/** Fill a ResourceRecord class based on raw data input */
inline void DNS::FillResourceRecord(ResourceRecord* rr, const unsigned char *input)
{
rr->type = (QueryType)((input[0] << 8) + input[1]);
rr->rr_class = (input[2] << 8) + input[3];
rr->ttl = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + input[7];
rr->rdlength = (input[8] << 8) + input[9];
}
/** Fill a DNSHeader class based on raw data input of a given length */
inline void DNS::FillHeader(DNSHeader *header, const unsigned char *input, const int length)
{
header->id[0] = input[0];
header->id[1] = input[1];
header->flags1 = input[2];
header->flags2 = input[3];
header->qdcount = (input[4] << 8) + input[5];
header->ancount = (input[6] << 8) + input[7];
header->nscount = (input[8] << 8) + input[9];
header->arcount = (input[10] << 8) + input[11];
memcpy(header->payload,&input[12],length);
}
/** Empty a DNSHeader class out into raw data, ready for transmission */
inline void DNS::EmptyHeader(unsigned char *output, const DNSHeader *header, const int length)
{
output[0] = header->id[0];
output[1] = header->id[1];
output[2] = header->flags1;
output[3] = header->flags2;
output[4] = header->qdcount >> 8;
output[5] = header->qdcount & 0xFF;
output[6] = header->ancount >> 8;
output[7] = header->ancount & 0xFF;
output[8] = header->nscount >> 8;
output[9] = header->nscount & 0xFF;
output[10] = header->arcount >> 8;
output[11] = header->arcount & 0xFF;
memcpy(&output[12],header->payload,length);
}
/** Send requests we have previously built down the UDP socket */
int DNSRequest::SendRequests(const DNSHeader *header, const int length, QueryType qt)
{
ServerInstance->Logs->Log("RESOLVER", DEBUG,"DNSRequest::SendRequests");
unsigned char payload[sizeof(DNSHeader)];
this->rr_class = 1;
this->type = qt;
DNS::EmptyHeader(payload,header,length);
if (ServerInstance->SE->SendTo(dnsobj, payload, length + 12, 0, &(dnsobj->myserver.sa), sa_size(dnsobj->myserver)) != length+12)
return -1;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Sent OK");
return 0;
}
/** Add a query with a predefined header, and allocate an ID for it. */
DNSRequest* DNS::AddQuery(DNSHeader *header, int &id, const char* original)
{
/* Is the DNS connection down? */
if (this->GetFd() == -1)
return NULL;
/* Create an id */
unsigned int tries = 0;
do {
id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
if (++tries == DNS::MAX_REQUEST_ID*5)
{
// If we couldn't find an empty slot this many times, do a sequential scan as a last
// resort. If an empty slot is found that way, go on, otherwise throw an exception
id = -1;
for (int i = 0; i < DNS::MAX_REQUEST_ID; i++)
{
if (!requests[i])
{
id = i;
break;
}
}
if (id == -1)
throw ModuleException("DNS: All ids are in use");
break;
}
} while (requests[id]);
DNSRequest* req = new DNSRequest(this, id, original);
header->id[0] = req->id[0] = id >> 8;
header->id[1] = req->id[1] = id & 0xFF;
header->flags1 = FLAGS_MASK_RD;
header->flags2 = 0;
header->qdcount = 1;
header->ancount = 0;
header->nscount = 0;
header->arcount = 0;
/* At this point we already know the id doesnt exist,
* so there needs to be no second check for the ::end()
*/
requests[id] = req;
/* According to the C++ spec, new never returns NULL. */
return req;
}
int DNS::ClearCache()
{
/* This ensures the buckets are reset to sane levels */
int rv = this->cache->size();
delete this->cache;
this->cache = new dnscache();
return rv;
}
int DNS::PruneCache()
{
int n = 0;
dnscache* newcache = new dnscache();
for (dnscache::iterator i = this->cache->begin(); i != this->cache->end(); i++)
/* Dont include expired items (theres no point) */
if (i->second.CalcTTLRemaining())
newcache->insert(*i);
else
n++;
delete this->cache;
this->cache = newcache;
return n;
}
void DNS::Rehash()
{
if (this->GetFd() > -1)
{
ServerInstance->SE->DelFd(this);
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
/* Rehash the cache */
this->PruneCache();
}
else
{
/* Create initial dns cache */
this->cache = new dnscache();
}
irc::sockets::aptosa(ServerInstance->Config->DNSServer, DNS::QUERY_PORT, myserver);
/* Initialize mastersocket */
int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
this->SetFd(s);
/* Have we got a socket and is it nonblocking? */
if (this->GetFd() != -1)
{
ServerInstance->SE->SetReuse(s);
ServerInstance->SE->NonBlocking(s);
irc::sockets::sockaddrs bindto;
memset(&bindto, 0, sizeof(bindto));
bindto.sa.sa_family = myserver.sa.sa_family;
if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0)
{
/* Failed to bind */
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error binding dns socket - hostnames will NOT resolve");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Internal error starting DNS - hostnames will NOT resolve.");
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
this->SetFd(-1);
}
}
else
{
ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error creating DNS socket - hostnames will NOT resolve");
}
}
/** Initialise the DNS UDP socket so that we can send requests */
DNS::DNS()
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::DNS");
/* Clear the Resolver class table */
memset(Classes,0,sizeof(Classes));
/* Clear the requests class table */
memset(requests,0,sizeof(requests));
/* DNS::Rehash() sets this to a valid ptr
*/
this->cache = NULL;
/* Again, DNS::Rehash() sets this to a
* valid value
*/
this->SetFd(-1);
/* Actually read the settings
*/
this->Rehash();
this->PruneTimer = new CacheTimer(this);
ServerInstance->Timers->AddTimer(this->PruneTimer);
}
/** Build a payload to be placed after the header, based upon input data, a resource type, a class and a pointer to a buffer */
int DNS::MakePayload(const char * const name, const QueryType rr, const unsigned short rr_class, unsigned char * const payload)
{
short payloadpos = 0;
const char* tempchr, *tempchr2 = name;
unsigned short length;
/* split name up into labels, create query */
while ((tempchr = strchr(tempchr2,'.')) != NULL)
{
length = tempchr - tempchr2;
if (payloadpos + length + 1 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
tempchr2 = &tempchr[1];
}
length = strlen(tempchr2);
if (length)
{
if (payloadpos + length + 2 > 507)
return -1;
payload[payloadpos++] = length;
memcpy(&payload[payloadpos],tempchr2,length);
payloadpos += length;
payload[payloadpos++] = 0;
}
if (payloadpos > 508)
return -1;
length = htons(rr);
memcpy(&payload[payloadpos],&length,2);
length = htons(rr_class);
memcpy(&payload[payloadpos + 2],&length,2);
return payloadpos + 4;
}
/** Start lookup of an hostname to an IP address */
int DNS::GetIP(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_A, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_A) == -1))
return -1;
return id;
}
/** Start lookup of an hostname to an IPv6 address */
int DNS::GetIP6(const char *name)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(name, DNS_QUERY_AAAA, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, name);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_AAAA) == -1))
return -1;
return id;
}
/** Start lookup of a cname to another name */
int DNS::GetCName(const char *alias)
{
DNSHeader h;
int id;
int length;
if ((length = this->MakePayload(alias, DNS_QUERY_CNAME, 1, (unsigned char*)&h.payload)) == -1)
return -1;
DNSRequest* req = this->AddQuery(&h, id, alias);
if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_CNAME) == -1))
return -1;
return id;
}
/** Start lookup of an IP address to a hostname */
int DNS::GetNameForce(const char *ip, ForceProtocol fp)
{
char query[128];
DNSHeader h;
int id;
int length;
if (fp == PROTOCOL_IPV6)
{
in6_addr i;
if (inet_pton(AF_INET6, ip, &i) > 0)
{
DNS::MakeIP6Int(query, &i);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv6 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
else
{
in_addr i;
if (inet_aton(ip, &i))
{
unsigned char* c = (unsigned char*)&i.s_addr;
sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv4 bad format for '%s'", ip);
/* Invalid IP address */
return -1;
}
}
length = this->MakePayload(query, DNS_QUERY_PTR, 1, (unsigned char*)&h.payload);
if (length == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't query '%s' using '%s' because it's too long", ip, query);
return -1;
}
DNSRequest* req = this->AddQuery(&h, id, ip);
if (!req)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't add query (resolver down?)");
return -1;
}
if (req->SendRequests(&h, length, DNS_QUERY_PTR) == -1)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't send (firewall?)");
return -1;
}
return id;
}
/** Build an ipv6 reverse domain from an in6_addr
*/
void DNS::MakeIP6Int(char* query, const in6_addr *ip)
{
const char* hex = "0123456789abcdef";
for (int index = 31; index >= 0; index--) /* for() loop steps twice per byte */
{
if (index % 2)
/* low nibble */
*query++ = hex[ip->s6_addr[index / 2] & 0x0F];
else
/* high nibble */
*query++ = hex[(ip->s6_addr[index / 2] & 0xF0) >> 4];
*query++ = '.'; /* Seperator */
}
strcpy(query,"ip6.arpa"); /* Suffix the string */
}
/** Return the next id which is ready, and the result attached to it */
DNSResult DNS::GetResult()
{
/* Fetch dns query response and decide where it belongs */
DNSHeader header;
DNSRequest *req;
unsigned char buffer[sizeof(DNSHeader)];
irc::sockets::sockaddrs from;
memset(&from, 0, sizeof(from));
socklen_t x = sizeof(from);
int length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x);
/* Did we get the whole header? */
if (length < 12)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"GetResult didn't get a full packet (len=%d)", length);
/* Nope - something screwed up. */
return DNSResult(-1,"",0,"");
}
/* Check wether the reply came from a different DNS
* server to the one we sent it to, or the source-port
* is not 53.
* A user could in theory still spoof dns packets anyway
* but this is less trivial than just sending garbage
* to the server, which is possible without this check.
*
* -- Thanks jilles for pointing this one out.
*/
if (from != myserver)
{
std::string server1 = from.str();
std::string server2 = myserver.str();
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
server1.c_str(), server2.c_str());
return DNSResult(-1,"",0,"");
}
/* Put the read header info into a header class */
DNS::FillHeader(&header,buffer,length - 12);
/* Get the id of this request.
* Its a 16 bit value stored in two char's,
* so we use logic shifts to create the value.
*/
unsigned long this_id = header.id[1] + (header.id[0] << 8);
/* Do we have a pending request matching this id? */
if (!requests[this_id])
{
/* Somehow we got a DNS response for a request we never made... */
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.", this_id);
return DNSResult(-1,"",0,"");
}
else
{
/* Remove the query from the list of pending queries */
req = requests[this_id];
requests[this_id] = NULL;
}
/* Inform the DNSRequest class that it has a result to be read.
* When its finished it will return a DNSInfo which is a pair of
* unsigned char* resource record data, and an error message.
*/
DNSInfo data = req->ResultIsReady(header, length);
std::string resultstr;
/* Check if we got a result, if we didnt, its an error */
if (data.first == NULL)
{
/* An error.
* Mask the ID with the value of ERROR_MASK, so that
* the dns_deal_with_classes() function knows that its
* an error response and needs to be treated uniquely.
* Put the error message in the second field.
*/
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, data.second, 0, ro);
}
else
{
unsigned long ttl = req->ttl;
char formatted[128];
/* Forward lookups come back as binary data. We must format them into ascii */
switch (req->type)
{
case DNS_QUERY_A:
snprintf(formatted,16,"%u.%u.%u.%u",data.first[0],data.first[1],data.first[2],data.first[3]);
resultstr = formatted;
break;
case DNS_QUERY_AAAA:
{
if (!inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted)))
{
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, "inet_ntop() failed", 0, ro);
}
resultstr = formatted;
/* Special case. Sending ::1 around between servers
* and to clients is dangerous, because the : on the
* start makes the client or server interpret the IP
* as the last parameter on the line with a value ":1".
*/
if (*formatted == ':')
resultstr.insert(0, "0");
}
break;
case DNS_QUERY_CNAME:
/* Identical handling to PTR */
case DNS_QUERY_PTR:
{
/* Reverse lookups just come back as char* */
resultstr = std::string((const char*)data.first);
if (resultstr.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-") != std::string::npos)
{
std::string ro = req->orig;
delete req;
return DNSResult(this_id | ERROR_MASK, "Invalid char(s) in reply", 0, ro);
}
}
break;
default:
break;
}
/* Build the reply with the id and hostname/ip in it */
std::string ro = req->orig;
DNSResult result = DNSResult(this_id,resultstr,ttl,ro,req->type);
delete req;
return result;
}
}
/** A result is ready, process it */
DNSInfo DNSRequest::ResultIsReady(DNSHeader &header, unsigned length)
{
unsigned i = 0, o;
int q = 0;
int curanswer;
ResourceRecord rr;
unsigned short ptr;
/* This is just to keep _FORTIFY_SOURCE happy */
rr.type = DNS_QUERY_NONE;
rr.rdlength = 0;
rr.ttl = 1; /* GCC is a whiney bastard -- see the XXX below. */
rr.rr_class = 0; /* Same for VC++ */
if (!(header.flags1 & FLAGS_MASK_QR))
return std::make_pair((unsigned char*)NULL,"Not a query result");
if (header.flags1 & FLAGS_MASK_OPCODE)
return std::make_pair((unsigned char*)NULL,"Unexpected value in DNS reply packet");
if (header.flags2 & FLAGS_MASK_RCODE)
return std::make_pair((unsigned char*)NULL,"Domain name not found");
if (header.ancount < 1)
return std::make_pair((unsigned char*)NULL,"No resource records returned");
/* Subtract the length of the header from the length of the packet */
length -= 12;
while ((unsigned int)q < header.qdcount && i < length)
{
if (header.payload[i] > 63)
{
i += 6;
q++;
}
else
{
if (header.payload[i] == 0)
{
q++;
i += 5;
}
else i += header.payload[i] + 1;
}
}
curanswer = 0;
while ((unsigned)curanswer < header.ancount)
{
q = 0;
while (q == 0 && i < length)
{
if (header.payload[i] > 63)
{
i += 2;
q = 1;
}
else
{
if (header.payload[i] == 0)
{
i++;
q = 1;
}
else i += header.payload[i] + 1; /* skip length and label */
}
}
if (static_cast<int>(length - i) < 10)
return std::make_pair((unsigned char*)NULL,"Incorrectly sized DNS reply");
/* XXX: We actually initialise 'rr' here including its ttl field */
DNS::FillResourceRecord(&rr,&header.payload[i]);
i += 10;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver: rr.type is %d and this.type is %d rr.class %d this.class %d", rr.type, this->type, rr.rr_class, this->rr_class);
if (rr.type != this->type)
{
curanswer++;
i += rr.rdlength;
continue;
}
if (rr.rr_class != this->rr_class)
{
curanswer++;
i += rr.rdlength;
continue;
}
break;
}
if ((unsigned int)curanswer == header.ancount)
return std::make_pair((unsigned char*)NULL,"No A, AAAA or PTR type answers (" + ConvToStr(header.ancount) + " answers)");
if (i + rr.rdlength > (unsigned int)length)
return std::make_pair((unsigned char*)NULL,"Resource record larger than stated");
if (rr.rdlength > 1023)
return std::make_pair((unsigned char*)NULL,"Resource record too large");
this->ttl = rr.ttl;
switch (rr.type)
{
/*
* CNAME and PTR are compressed. We need to decompress them.
*/
case DNS_QUERY_CNAME:
case DNS_QUERY_PTR:
{
unsigned short lowest_pos = length;
o = 0;
q = 0;
while (q == 0 && i < length && o + 256 < 1023)
{
/* DN label found (byte over 63) */
if (header.payload[i] > 63)
{
memcpy(&ptr,&header.payload[i],2);
i = ntohs(ptr);
/* check that highest two bits are set. if not, we've been had */
if ((i & DN_COMP_BITMASK) != DN_COMP_BITMASK)
return std::make_pair((unsigned char *) NULL, "DN label decompression header is bogus");
/* mask away the two highest bits. */
i &= ~DN_COMP_BITMASK;
/* and decrease length by 12 bytes. */
i -= 12;
if (i >= lowest_pos)
return std::make_pair((unsigned char *) NULL, "Invalid decompression pointer");
lowest_pos = i;
}
else
{
if (header.payload[i] == 0)
{
q = 1;
}
else
{
res[o] = 0;
if (o != 0)
res[o++] = '.';
if (o + header.payload[i] > sizeof(DNSHeader))
return std::make_pair((unsigned char *) NULL, "DN label decompression is impossible -- malformed/hostile packet?");
memcpy(&res[o], &header.payload[i + 1], header.payload[i]);
o += header.payload[i];
i += header.payload[i] + 1;
}
}
}
res[o] = 0;
}
break;
case DNS_QUERY_AAAA:
if (rr.rdlength != sizeof(struct in6_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 16 bytes for an ipv6 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
case DNS_QUERY_A:
if (rr.rdlength != sizeof(struct in_addr))
return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 4 bytes for an ipv4 entry -- malformed/hostile packet?");
memcpy(res,&header.payload[i],rr.rdlength);
res[rr.rdlength] = 0;
break;
default:
return std::make_pair((unsigned char *) NULL, "don't know how to handle undefined type (" + ConvToStr(rr.type) + ") -- rejecting");
break;
}
return std::make_pair(res,"No error");
}
/** Close the master socket */
DNS::~DNS()
{
ServerInstance->SE->Shutdown(this, 2);
ServerInstance->SE->Close(this);
ServerInstance->Timers->DelTimer(this->PruneTimer);
if (cache)
delete cache;
}
CachedQuery* DNS::GetCache(const std::string &source)
{
dnscache::iterator x = cache->find(source.c_str());
if (x != cache->end())
return &(x->second);
else
return NULL;
}
void DNS::DelCache(const std::string &source)
{
cache->erase(source.c_str());
}
void Resolver::TriggerCachedResult()
{
if (CQ)
OnLookupComplete(CQ->data, time_left, true);
}
/** High level abstraction of dns used by application at large */
Resolver::Resolver(const std::string &source, QueryType qt, bool &cached, Module* creator) : Creator(creator), input(source), querytype(qt)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver::Resolver");
cached = false;
CQ = ServerInstance->Res->GetCache(source);
if (CQ)
{
time_left = CQ->CalcTTLRemaining();
if (!time_left)
{
ServerInstance->Res->DelCache(source);
}
else if (CQ->type == qt)
{
cached = true;
return;
}
CQ = NULL;
}
switch (querytype)
{
case DNS_QUERY_A:
this->myid = ServerInstance->Res->GetIP(source.c_str());
break;
case DNS_QUERY_PTR4:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV4);
break;
case DNS_QUERY_PTR6:
querytype = DNS_QUERY_PTR;
this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV6);
break;
case DNS_QUERY_AAAA:
this->myid = ServerInstance->Res->GetIP6(source.c_str());
break;
case DNS_QUERY_CNAME:
this->myid = ServerInstance->Res->GetCName(source.c_str());
break;
default:
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request with unknown query type %d", querytype);
this->myid = -1;
break;
}
if (this->myid == -1)
{
throw ModuleException("Resolver: Couldn't get an id to make a request");
}
else
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request id %d", this->myid);
}
}
/** Called when an error occurs */
void Resolver::OnError(ResolverError, const std::string&)
{
/* Nothing in here */
}
/** Destroy a resolver */
Resolver::~Resolver()
{
/* Nothing here (yet) either */
}
/** Get the request id associated with this class */
int Resolver::GetId()
{
return this->myid;
}
Module* Resolver::GetCreator()
{
return this->Creator;
}
/** Process a socket read event */
void DNS::HandleEvent(EventType, int)
{
/* Fetch the id and result of the next available packet */
DNSResult res(0,"",0,"");
res.id = 0;
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Handle DNS event");
res = this->GetResult();
ServerInstance->Logs->Log("RESOLVER",DEBUG,"Result id %d", res.id);
/* Is there a usable request id? */
if (res.id != -1)
{
/* Its an error reply */
if (res.id & ERROR_MASK)
{
/* Mask off the error bit */
res.id -= ERROR_MASK;
/* Marshall the error to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsBad++;
Classes[res.id]->OnError(RESOLVER_NXDOMAIN, res.result);
delete Classes[res.id];
Classes[res.id] = NULL;
}
return;
}
else
{
/* It is a non-error result, marshall the result to the correct class */
if (Classes[res.id])
{
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDnsGood++;
if (!this->GetCache(res.original.c_str()))
this->cache->insert(std::make_pair(res.original.c_str(), CachedQuery(res.result, res.type, res.ttl)));
Classes[res.id]->OnLookupComplete(res.result, res.ttl, false);
delete Classes[res.id];
Classes[res.id] = NULL;
}
}
if (ServerInstance && ServerInstance->stats)
ServerInstance->stats->statsDns++;
}
}
/** Add a derived Resolver to the working set */
bool DNS::AddResolverClass(Resolver* r)
{
ServerInstance->Logs->Log("RESOLVER",DEBUG,"AddResolverClass 0x%08lx", (unsigned long)r);
/* Check the pointers validity and the id's validity */
if ((r) && (r->GetId() > -1))
{
/* Check the slot isnt already occupied -
* This should NEVER happen unless we have
* a severely broken DNS server somewhere
*/
if (!Classes[r->GetId()])
{
/* Set up the pointer to the class */
Classes[r->GetId()] = r;
return true;
}
}
/* Pointer or id not valid, or duplicate id.
* Free the item and return
*/
delete r;
return false;
}
void DNS::CleanResolvers(Module* module)
{
for (int i = 0; i < MAX_REQUEST_ID; i++)
{
if (Classes[i])
{
if (Classes[i]->GetCreator() == module)
{
Classes[i]->OnError(RESOLVER_FORCEUNLOAD, "Parent module is unloading");
delete Classes[i];
Classes[i] = NULL;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1798_0 |
crossvul-cpp_data_bad_1442_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
* Copyright (C) 2008 by Stefan Rado
* based on admin.cpp by Sebastian Ramacher
* based on admin.cpp in crox branch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
using std::map;
using std::vector;
template <std::size_t N>
struct array_size_helper {
char __place_holder[N];
};
template <class T, std::size_t N>
static array_size_helper<N> array_size(T (&)[N]) {
return array_size_helper<N>();
}
#define ARRAY_SIZE(array) sizeof(array_size((array)))
class CAdminMod : public CModule {
using CModule::PutModule;
struct Setting {
const char* name;
CString type;
};
void PrintVarsHelp(const CString& sFilter, const Setting vars[],
unsigned int uSize, const CString& sDescription) {
CTable VarTable;
VarTable.AddColumn(t_s("Type", "helptable"));
VarTable.AddColumn(t_s("Variables", "helptable"));
std::map<CString, VCString> mvsTypedVariables;
for (unsigned int i = 0; i != uSize; ++i) {
CString sVar = CString(vars[i].name).AsLower();
if (sFilter.empty() || sVar.StartsWith(sFilter) ||
sVar.WildCmp(sFilter)) {
mvsTypedVariables[vars[i].type].emplace_back(vars[i].name);
}
}
for (const auto& i : mvsTypedVariables) {
VarTable.AddRow();
VarTable.SetCell(t_s("Type", "helptable"), i.first);
VarTable.SetCell(
t_s("Variables", "helptable"),
CString(", ").Join(i.second.cbegin(), i.second.cend()));
}
if (!VarTable.empty()) {
PutModule(sDescription);
PutModule(VarTable);
}
}
void PrintHelp(const CString& sLine) {
HandleHelpCommand(sLine);
const CString str = t_s("String");
const CString boolean = t_s("Boolean (true/false)");
const CString integer = t_s("Integer");
const CString number = t_s("Number");
const CString sCmdFilter = sLine.Token(1, false);
const CString sVarFilter = sLine.Token(2, true).AsLower();
if (sCmdFilter.empty() || sCmdFilter.StartsWith("Set") ||
sCmdFilter.StartsWith("Get")) {
Setting vars[] = {
{"Nick", str},
{"Altnick", str},
{"Ident", str},
{"RealName", str},
{"BindHost", str},
{"MultiClients", boolean},
{"DenyLoadMod", boolean},
{"DenySetBindHost", boolean},
{"DefaultChanModes", str},
{"QuitMsg", str},
{"ChanBufferSize", integer},
{"QueryBufferSize", integer},
{"AutoClearChanBuffer", boolean},
{"AutoClearQueryBuffer", boolean},
{"Password", str},
{"JoinTries", integer},
{"MaxJoins", integer},
{"MaxNetworks", integer},
{"MaxQueryBuffers", integer},
{"Timezone", str},
{"Admin", boolean},
{"AppendTimestamp", boolean},
{"PrependTimestamp", boolean},
{"AuthOnlyViaModule", boolean},
{"TimestampFormat", str},
{"DCCBindHost", str},
{"StatusPrefix", str},
#ifdef HAVE_I18N
{"Language", str},
#endif
#ifdef HAVE_ICU
{"ClientEncoding", str},
#endif
};
PrintVarsHelp(sVarFilter, vars, ARRAY_SIZE(vars),
t_s("The following variables are available when "
"using the Set/Get commands:"));
}
if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetNetwork") ||
sCmdFilter.StartsWith("GetNetwork")) {
Setting nvars[] = {
{"Nick", str},
{"Altnick", str},
{"Ident", str},
{"RealName", str},
{"BindHost", str},
{"FloodRate", number},
{"FloodBurst", integer},
{"JoinDelay", integer},
#ifdef HAVE_ICU
{"Encoding", str},
#endif
{"QuitMsg", str},
{"TrustAllCerts", boolean},
{"TrustPKI", boolean},
};
PrintVarsHelp(sVarFilter, nvars, ARRAY_SIZE(nvars),
t_s("The following variables are available when "
"using the SetNetwork/GetNetwork commands:"));
}
if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetChan") ||
sCmdFilter.StartsWith("GetChan")) {
Setting cvars[] = {{"DefModes", str},
{"Key", str},
{"BufferSize", integer},
{"InConfig", boolean},
{"AutoClearChanBuffer", boolean},
{"Detached", boolean}};
PrintVarsHelp(sVarFilter, cvars, ARRAY_SIZE(cvars),
t_s("The following variables are available when "
"using the SetChan/GetChan commands:"));
}
if (sCmdFilter.empty())
PutModule(
t_s("You can use $user as the user name and $network as the "
"network name for modifying your own user and network."));
}
CUser* FindUser(const CString& sUsername) {
if (sUsername.Equals("$me") || sUsername.Equals("$user"))
return GetUser();
CUser* pUser = CZNC::Get().FindUser(sUsername);
if (!pUser) {
PutModule(t_f("Error: User [{1}] does not exist!")(sUsername));
return nullptr;
}
if (pUser != GetUser() && !GetUser()->IsAdmin()) {
PutModule(t_s(
"Error: You need to have admin rights to modify other users!"));
return nullptr;
}
return pUser;
}
CIRCNetwork* FindNetwork(CUser* pUser, const CString& sNetwork) {
if (sNetwork.Equals("$net") || sNetwork.Equals("$network")) {
if (pUser != GetUser()) {
PutModule(t_s(
"Error: You cannot use $network to modify other users!"));
return nullptr;
}
return CModule::GetNetwork();
}
CIRCNetwork* pNetwork = pUser->FindNetwork(sNetwork);
if (!pNetwork) {
PutModule(
t_f("Error: User {1} does not have a network named [{2}].")(
pUser->GetUserName(), sNetwork));
}
return pNetwork;
}
void Get(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUsername = sLine.Token(2, true);
CUser* pUser;
if (sVar.empty()) {
PutModule(t_s("Usage: Get <variable> [username]"));
return;
}
if (sUsername.empty()) {
pUser = GetUser();
} else {
pUser = FindUser(sUsername);
}
if (!pUser) return;
if (sVar == "nick")
PutModule("Nick = " + pUser->GetNick());
else if (sVar == "altnick")
PutModule("AltNick = " + pUser->GetAltNick());
else if (sVar == "ident")
PutModule("Ident = " + pUser->GetIdent());
else if (sVar == "realname")
PutModule("RealName = " + pUser->GetRealName());
else if (sVar == "bindhost")
PutModule("BindHost = " + pUser->GetBindHost());
else if (sVar == "multiclients")
PutModule("MultiClients = " + CString(pUser->MultiClients()));
else if (sVar == "denyloadmod")
PutModule("DenyLoadMod = " + CString(pUser->DenyLoadMod()));
else if (sVar == "denysetbindhost")
PutModule("DenySetBindHost = " + CString(pUser->DenySetBindHost()));
else if (sVar == "defaultchanmodes")
PutModule("DefaultChanModes = " + pUser->GetDefaultChanModes());
else if (sVar == "quitmsg")
PutModule("QuitMsg = " + pUser->GetQuitMsg());
else if (sVar == "buffercount")
PutModule("BufferCount = " + CString(pUser->GetBufferCount()));
else if (sVar == "chanbuffersize")
PutModule("ChanBufferSize = " +
CString(pUser->GetChanBufferSize()));
else if (sVar == "querybuffersize")
PutModule("QueryBufferSize = " +
CString(pUser->GetQueryBufferSize()));
else if (sVar == "keepbuffer")
// XXX compatibility crap, added in 0.207
PutModule("KeepBuffer = " + CString(!pUser->AutoClearChanBuffer()));
else if (sVar == "autoclearchanbuffer")
PutModule("AutoClearChanBuffer = " +
CString(pUser->AutoClearChanBuffer()));
else if (sVar == "autoclearquerybuffer")
PutModule("AutoClearQueryBuffer = " +
CString(pUser->AutoClearQueryBuffer()));
else if (sVar == "maxjoins")
PutModule("MaxJoins = " + CString(pUser->MaxJoins()));
else if (sVar == "notraffictimeout")
PutModule("NoTrafficTimeout = " +
CString(pUser->GetNoTrafficTimeout()));
else if (sVar == "maxnetworks")
PutModule("MaxNetworks = " + CString(pUser->MaxNetworks()));
else if (sVar == "maxquerybuffers")
PutModule("MaxQueryBuffers = " + CString(pUser->MaxQueryBuffers()));
else if (sVar == "jointries")
PutModule("JoinTries = " + CString(pUser->JoinTries()));
else if (sVar == "timezone")
PutModule("Timezone = " + pUser->GetTimezone());
else if (sVar == "appendtimestamp")
PutModule("AppendTimestamp = " +
CString(pUser->GetTimestampAppend()));
else if (sVar == "prependtimestamp")
PutModule("PrependTimestamp = " +
CString(pUser->GetTimestampPrepend()));
else if (sVar == "authonlyviamodule")
PutModule("AuthOnlyViaModule = " +
CString(pUser->AuthOnlyViaModule()));
else if (sVar == "timestampformat")
PutModule("TimestampFormat = " + pUser->GetTimestampFormat());
else if (sVar == "dccbindhost")
PutModule("DCCBindHost = " + CString(pUser->GetDCCBindHost()));
else if (sVar == "admin")
PutModule("Admin = " + CString(pUser->IsAdmin()));
else if (sVar == "statusprefix")
PutModule("StatusPrefix = " + pUser->GetStatusPrefix());
#ifdef HAVE_I18N
else if (sVar == "language")
PutModule("Language = " + (pUser->GetLanguage().empty()
? "en"
: pUser->GetLanguage()));
#endif
#ifdef HAVE_ICU
else if (sVar == "clientencoding")
PutModule("ClientEncoding = " + pUser->GetClientEncoding());
#endif
else
PutModule(t_s("Error: Unknown variable"));
}
void Set(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUserName = sLine.Token(2);
CString sValue = sLine.Token(3, true);
if (sValue.empty()) {
PutModule(t_s("Usage: Set <variable> <username> <value>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
if (sVar == "nick") {
pUser->SetNick(sValue);
PutModule("Nick = " + sValue);
} else if (sVar == "altnick") {
pUser->SetAltNick(sValue);
PutModule("AltNick = " + sValue);
} else if (sVar == "ident") {
pUser->SetIdent(sValue);
PutModule("Ident = " + sValue);
} else if (sVar == "realname") {
pUser->SetRealName(sValue);
PutModule("RealName = " + sValue);
} else if (sVar == "bindhost") {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
if (sValue.Equals(pUser->GetBindHost())) {
PutModule(t_s("This bind host is already set!"));
return;
}
pUser->SetBindHost(sValue);
PutModule("BindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "multiclients") {
bool b = sValue.ToBool();
pUser->SetMultiClients(b);
PutModule("MultiClients = " + CString(b));
} else if (sVar == "denyloadmod") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetDenyLoadMod(b);
PutModule("DenyLoadMod = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "denysetbindhost") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetDenySetBindHost(b);
PutModule("DenySetBindHost = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "defaultchanmodes") {
pUser->SetDefaultChanModes(sValue);
PutModule("DefaultChanModes = " + sValue);
} else if (sVar == "quitmsg") {
pUser->SetQuitMsg(sValue);
PutModule("QuitMsg = " + sValue);
} else if (sVar == "chanbuffersize" || sVar == "buffercount") {
unsigned int i = sValue.ToUInt();
// Admins don't have to honour the buffer limit
if (pUser->SetChanBufferSize(i, GetUser()->IsAdmin())) {
PutModule("ChanBufferSize = " + sValue);
} else {
PutModule(t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
}
} else if (sVar == "querybuffersize") {
unsigned int i = sValue.ToUInt();
// Admins don't have to honour the buffer limit
if (pUser->SetQueryBufferSize(i, GetUser()->IsAdmin())) {
PutModule("QueryBufferSize = " + sValue);
} else {
PutModule(t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
}
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
bool b = !sValue.ToBool();
pUser->SetAutoClearChanBuffer(b);
PutModule("AutoClearChanBuffer = " + CString(b));
} else if (sVar == "autoclearchanbuffer") {
bool b = sValue.ToBool();
pUser->SetAutoClearChanBuffer(b);
PutModule("AutoClearChanBuffer = " + CString(b));
} else if (sVar == "autoclearquerybuffer") {
bool b = sValue.ToBool();
pUser->SetAutoClearQueryBuffer(b);
PutModule("AutoClearQueryBuffer = " + CString(b));
} else if (sVar == "password") {
const CString sSalt = CUtils::GetSalt();
const CString sHash = CUser::SaltedHash(sValue, sSalt);
pUser->SetPass(sHash, CUser::HASH_DEFAULT, sSalt);
PutModule(t_s("Password has been changed!"));
} else if (sVar == "maxjoins") {
unsigned int i = sValue.ToUInt();
pUser->SetMaxJoins(i);
PutModule("MaxJoins = " + CString(pUser->MaxJoins()));
} else if (sVar == "notraffictimeout") {
unsigned int i = sValue.ToUInt();
if (i < 30) {
PutModule(t_s("Timeout can't be less than 30 seconds!"));
} else {
pUser->SetNoTrafficTimeout(i);
PutModule("NoTrafficTimeout = " +
CString(pUser->GetNoTrafficTimeout()));
}
} else if (sVar == "maxnetworks") {
if (GetUser()->IsAdmin()) {
unsigned int i = sValue.ToUInt();
pUser->SetMaxNetworks(i);
PutModule("MaxNetworks = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "maxquerybuffers") {
unsigned int i = sValue.ToUInt();
pUser->SetMaxQueryBuffers(i);
PutModule("MaxQueryBuffers = " + sValue);
} else if (sVar == "jointries") {
unsigned int i = sValue.ToUInt();
pUser->SetJoinTries(i);
PutModule("JoinTries = " + CString(pUser->JoinTries()));
} else if (sVar == "timezone") {
pUser->SetTimezone(sValue);
PutModule("Timezone = " + pUser->GetTimezone());
} else if (sVar == "admin") {
if (GetUser()->IsAdmin() && pUser != GetUser()) {
bool b = sValue.ToBool();
pUser->SetAdmin(b);
PutModule("Admin = " + CString(pUser->IsAdmin()));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "prependtimestamp") {
bool b = sValue.ToBool();
pUser->SetTimestampPrepend(b);
PutModule("PrependTimestamp = " + CString(b));
} else if (sVar == "appendtimestamp") {
bool b = sValue.ToBool();
pUser->SetTimestampAppend(b);
PutModule("AppendTimestamp = " + CString(b));
} else if (sVar == "authonlyviamodule") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetAuthOnlyViaModule(b);
PutModule("AuthOnlyViaModule = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "timestampformat") {
pUser->SetTimestampFormat(sValue);
PutModule("TimestampFormat = " + sValue);
} else if (sVar == "dccbindhost") {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
pUser->SetDCCBindHost(sValue);
PutModule("DCCBindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "statusprefix") {
if (sVar.find_first_of(" \t\n") == CString::npos) {
pUser->SetStatusPrefix(sValue);
PutModule("StatusPrefix = " + sValue);
} else {
PutModule(t_s("That would be a bad idea!"));
}
}
#ifdef HAVE_I18N
else if (sVar == "language") {
auto mTranslations = CTranslationInfo::GetTranslations();
// TODO: maybe stop special-casing English
if (sValue == "en") {
pUser->SetLanguage("");
PutModule("Language is set to English");
} else if (mTranslations.count(sValue)) {
pUser->SetLanguage(sValue);
PutModule("Language = " + sValue);
} else {
VCString vsCodes = {"en"};
for (const auto it : mTranslations) {
vsCodes.push_back(it.first);
}
PutModule(t_f("Supported languages: {1}")(
CString(", ").Join(vsCodes.begin(), vsCodes.end())));
}
}
#endif
#ifdef HAVE_ICU
else if (sVar == "clientencoding") {
pUser->SetClientEncoding(sValue);
PutModule("ClientEncoding = " + sValue);
}
#endif
else
PutModule(t_s("Error: Unknown variable"));
}
void GetNetwork(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
const CString sUsername = sLine.Token(2);
const CString sNetwork = sLine.Token(3);
CIRCNetwork* pNetwork = nullptr;
CUser* pUser;
if (sVar.empty()) {
PutModule(t_s("Usage: GetNetwork <variable> [username] [network]"));
return;
}
if (sUsername.empty()) {
pUser = GetUser();
} else {
pUser = FindUser(sUsername);
}
if (!pUser) {
return;
}
if (sNetwork.empty()) {
if (pUser == GetUser()) {
pNetwork = CModule::GetNetwork();
} else {
PutModule(
t_s("Error: A network must be specified to get another "
"users settings."));
return;
}
if (!pNetwork) {
PutModule(t_s("You are not currently attached to a network."));
return;
}
} else {
pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
PutModule(t_s("Error: Invalid network."));
return;
}
}
if (sVar.Equals("nick")) {
PutModule("Nick = " + pNetwork->GetNick());
} else if (sVar.Equals("altnick")) {
PutModule("AltNick = " + pNetwork->GetAltNick());
} else if (sVar.Equals("ident")) {
PutModule("Ident = " + pNetwork->GetIdent());
} else if (sVar.Equals("realname")) {
PutModule("RealName = " + pNetwork->GetRealName());
} else if (sVar.Equals("bindhost")) {
PutModule("BindHost = " + pNetwork->GetBindHost());
} else if (sVar.Equals("floodrate")) {
PutModule("FloodRate = " + CString(pNetwork->GetFloodRate()));
} else if (sVar.Equals("floodburst")) {
PutModule("FloodBurst = " + CString(pNetwork->GetFloodBurst()));
} else if (sVar.Equals("joindelay")) {
PutModule("JoinDelay = " + CString(pNetwork->GetJoinDelay()));
#ifdef HAVE_ICU
} else if (sVar.Equals("encoding")) {
PutModule("Encoding = " + pNetwork->GetEncoding());
#endif
} else if (sVar.Equals("quitmsg")) {
PutModule("QuitMsg = " + pNetwork->GetQuitMsg());
} else if (sVar.Equals("trustallcerts")) {
PutModule("TrustAllCerts = " + CString(pNetwork->GetTrustAllCerts()));
} else if (sVar.Equals("trustpki")) {
PutModule("TrustPKI = " + CString(pNetwork->GetTrustPKI()));
} else {
PutModule(t_s("Error: Unknown variable"));
}
}
void SetNetwork(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
const CString sUsername = sLine.Token(2);
const CString sNetwork = sLine.Token(3);
const CString sValue = sLine.Token(4, true);
if (sValue.empty()) {
PutModule(t_s(
"Usage: SetNetwork <variable> <username> <network> <value>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) {
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (sVar.Equals("nick")) {
pNetwork->SetNick(sValue);
PutModule("Nick = " + pNetwork->GetNick());
} else if (sVar.Equals("altnick")) {
pNetwork->SetAltNick(sValue);
PutModule("AltNick = " + pNetwork->GetAltNick());
} else if (sVar.Equals("ident")) {
pNetwork->SetIdent(sValue);
PutModule("Ident = " + pNetwork->GetIdent());
} else if (sVar.Equals("realname")) {
pNetwork->SetRealName(sValue);
PutModule("RealName = " + pNetwork->GetRealName());
} else if (sVar.Equals("bindhost")) {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
if (sValue.Equals(pNetwork->GetBindHost())) {
PutModule(t_s("This bind host is already set!"));
return;
}
pNetwork->SetBindHost(sValue);
PutModule("BindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar.Equals("floodrate")) {
pNetwork->SetFloodRate(sValue.ToDouble());
PutModule("FloodRate = " + CString(pNetwork->GetFloodRate()));
} else if (sVar.Equals("floodburst")) {
pNetwork->SetFloodBurst(sValue.ToUShort());
PutModule("FloodBurst = " + CString(pNetwork->GetFloodBurst()));
} else if (sVar.Equals("joindelay")) {
pNetwork->SetJoinDelay(sValue.ToUShort());
PutModule("JoinDelay = " + CString(pNetwork->GetJoinDelay()));
#ifdef HAVE_ICU
} else if (sVar.Equals("encoding")) {
pNetwork->SetEncoding(sValue);
PutModule("Encoding = " + pNetwork->GetEncoding());
#endif
} else if (sVar.Equals("quitmsg")) {
pNetwork->SetQuitMsg(sValue);
PutModule("QuitMsg = " + pNetwork->GetQuitMsg());
} else if (sVar.Equals("trustallcerts")) {
bool b = sValue.ToBool();
pNetwork->SetTrustAllCerts(b);
PutModule("TrustAllCerts = " + CString(b));
} else if (sVar.Equals("trustpki")) {
bool b = sValue.ToBool();
pNetwork->SetTrustPKI(b);
PutModule("TrustPKI = " + CString(b));
} else {
PutModule(t_s("Error: Unknown variable"));
}
}
void AddChan(const CString& sLine) {
const CString sUsername = sLine.Token(1);
const CString sNetwork = sLine.Token(2);
const CString sChan = sLine.Token(3);
if (sChan.empty()) {
PutModule(t_s("Usage: AddChan <username> <network> <channel>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork->FindChan(sChan)) {
PutModule(t_f("Error: User {1} already has a channel named {2}.")(
sUsername, sChan));
return;
}
CChan* pChan = new CChan(sChan, pNetwork, true);
if (pNetwork->AddChan(pChan))
PutModule(t_f("Channel {1} for user {2} added to network {3}.")(
pChan->GetName(), sUsername, pNetwork->GetName()));
else
PutModule(t_f(
"Could not add channel {1} for user {2} to network {3}, does "
"it already exist?")(sChan, sUsername, pNetwork->GetName()));
}
void DelChan(const CString& sLine) {
const CString sUsername = sLine.Token(1);
const CString sNetwork = sLine.Token(2);
const CString sChan = sLine.Token(3);
if (sChan.empty()) {
PutModule(t_s("Usage: DelChan <username> <network> <channel>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
std::vector<CChan*> vChans = pNetwork->FindChans(sChan);
if (vChans.empty()) {
PutModule(
t_f("Error: User {1} does not have any channel matching [{2}] "
"in network {3}")(sUsername, sChan, pNetwork->GetName()));
return;
}
VCString vsNames;
for (const CChan* pChan : vChans) {
const CString& sName = pChan->GetName();
vsNames.push_back(sName);
pNetwork->PutIRC("PART " + sName);
pNetwork->DelChan(sName);
}
PutModule(t_p("Channel {1} is deleted from network {2} of user {3}",
"Channels {1} are deleted from network {2} of user {3}",
vsNames.size())(
CString(", ").Join(vsNames.begin(), vsNames.end()),
pNetwork->GetName(), sUsername));
}
void GetChan(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUsername = sLine.Token(2);
CString sNetwork = sLine.Token(3);
CString sChan = sLine.Token(4, true);
if (sChan.empty()) {
PutModule(
t_s("Usage: GetChan <variable> <username> <network> <chan>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
std::vector<CChan*> vChans = pNetwork->FindChans(sChan);
if (vChans.empty()) {
PutModule(t_f("Error: No channels matching [{1}] found.")(sChan));
return;
}
for (CChan* pChan : vChans) {
if (sVar == "defmodes") {
PutModule(pChan->GetName() + ": DefModes = " +
pChan->GetDefaultModes());
} else if (sVar == "buffersize" || sVar == "buffer") {
CString sValue(pChan->GetBufferCount());
if (!pChan->HasBufferCountSet()) {
sValue += " (default)";
}
PutModule(pChan->GetName() + ": BufferSize = " + sValue);
} else if (sVar == "inconfig") {
PutModule(pChan->GetName() + ": InConfig = " +
CString(pChan->InConfig()));
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
PutModule(pChan->GetName() + ": KeepBuffer = " +
CString(!pChan->AutoClearChanBuffer()));
} else if (sVar == "autoclearchanbuffer") {
CString sValue(pChan->AutoClearChanBuffer());
if (!pChan->HasAutoClearChanBufferSet()) {
sValue += " (default)";
}
PutModule(pChan->GetName() + ": AutoClearChanBuffer = " +
sValue);
} else if (sVar == "detached") {
PutModule(pChan->GetName() + ": Detached = " +
CString(pChan->IsDetached()));
} else if (sVar == "key") {
PutModule(pChan->GetName() + ": Key = " + pChan->GetKey());
} else {
PutModule(t_s("Error: Unknown variable"));
return;
}
}
}
void SetChan(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUsername = sLine.Token(2);
CString sNetwork = sLine.Token(3);
CString sChan = sLine.Token(4);
CString sValue = sLine.Token(5, true);
if (sValue.empty()) {
PutModule(
t_s("Usage: SetChan <variable> <username> <network> <chan> "
"<value>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
std::vector<CChan*> vChans = pNetwork->FindChans(sChan);
if (vChans.empty()) {
PutModule(t_f("Error: No channels matching [{1}] found.")(sChan));
return;
}
for (CChan* pChan : vChans) {
if (sVar == "defmodes") {
pChan->SetDefaultModes(sValue);
PutModule(pChan->GetName() + ": DefModes = " + sValue);
} else if (sVar == "buffersize" || sVar == "buffer") {
unsigned int i = sValue.ToUInt();
if (sValue.Equals("-")) {
pChan->ResetBufferCount();
PutModule(pChan->GetName() + ": BufferSize = " +
CString(pChan->GetBufferCount()));
} else if (pChan->SetBufferCount(i, GetUser()->IsAdmin())) {
// Admins don't have to honour the buffer limit
PutModule(pChan->GetName() + ": BufferSize = " + sValue);
} else {
PutModule(
t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
return;
}
} else if (sVar == "inconfig") {
bool b = sValue.ToBool();
pChan->SetInConfig(b);
PutModule(pChan->GetName() + ": InConfig = " + CString(b));
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
bool b = !sValue.ToBool();
pChan->SetAutoClearChanBuffer(b);
PutModule(pChan->GetName() + ": AutoClearChanBuffer = " +
CString(b));
} else if (sVar == "autoclearchanbuffer") {
if (sValue.Equals("-")) {
pChan->ResetAutoClearChanBuffer();
} else {
bool b = sValue.ToBool();
pChan->SetAutoClearChanBuffer(b);
}
PutModule(pChan->GetName() + ": AutoClearChanBuffer = " +
CString(pChan->AutoClearChanBuffer()));
} else if (sVar == "detached") {
bool b = sValue.ToBool();
if (pChan->IsDetached() != b) {
if (b)
pChan->DetachUser();
else
pChan->AttachUser();
}
PutModule(pChan->GetName() + ": Detached = " + CString(b));
} else if (sVar == "key") {
pChan->SetKey(sValue);
PutModule(pChan->GetName() + ": Key = " + sValue);
} else {
PutModule(t_s("Error: Unknown variable"));
return;
}
}
}
void ListUsers(const CString&) {
if (!GetUser()->IsAdmin()) return;
const map<CString, CUser*>& msUsers = CZNC::Get().GetUserMap();
CTable Table;
Table.AddColumn(t_s("Username", "listusers"));
Table.AddColumn(t_s("Realname", "listusers"));
Table.AddColumn(t_s("IsAdmin", "listusers"));
Table.AddColumn(t_s("Nick", "listusers"));
Table.AddColumn(t_s("AltNick", "listusers"));
Table.AddColumn(t_s("Ident", "listusers"));
Table.AddColumn(t_s("BindHost", "listusers"));
for (const auto& it : msUsers) {
Table.AddRow();
Table.SetCell(t_s("Username", "listusers"), it.first);
Table.SetCell(t_s("Realname", "listusers"),
it.second->GetRealName());
if (!it.second->IsAdmin())
Table.SetCell(t_s("IsAdmin", "listusers"), t_s("No"));
else
Table.SetCell(t_s("IsAdmin", "listusers"), t_s("Yes"));
Table.SetCell(t_s("Nick", "listusers"), it.second->GetNick());
Table.SetCell(t_s("AltNick", "listusers"), it.second->GetAltNick());
Table.SetCell(t_s("Ident", "listusers"), it.second->GetIdent());
Table.SetCell(t_s("BindHost", "listusers"),
it.second->GetBindHost());
}
PutModule(Table);
}
void AddUser(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule(
t_s("Error: You need to have admin rights to add new users!"));
return;
}
const CString sUsername = sLine.Token(1), sPassword = sLine.Token(2);
if (sPassword.empty()) {
PutModule(t_s("Usage: AddUser <username> <password>"));
return;
}
if (CZNC::Get().FindUser(sUsername)) {
PutModule(t_f("Error: User {1} already exists!")(sUsername));
return;
}
CUser* pNewUser = new CUser(sUsername);
CString sSalt = CUtils::GetSalt();
pNewUser->SetPass(CUser::SaltedHash(sPassword, sSalt),
CUser::HASH_DEFAULT, sSalt);
CString sErr;
if (!CZNC::Get().AddUser(pNewUser, sErr)) {
delete pNewUser;
PutModule(t_f("Error: User not added: {1}")(sErr));
return;
}
PutModule(t_f("User {1} added!")(sUsername));
return;
}
void DelUser(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule(
t_s("Error: You need to have admin rights to delete users!"));
return;
}
const CString sUsername = sLine.Token(1, true);
if (sUsername.empty()) {
PutModule(t_s("Usage: DelUser <username>"));
return;
}
CUser* pUser = CZNC::Get().FindUser(sUsername);
if (!pUser) {
PutModule(t_f("Error: User [{1}] does not exist!")(sUsername));
return;
}
if (pUser == GetUser()) {
PutModule(t_s("Error: You can't delete yourself!"));
return;
}
if (!CZNC::Get().DeleteUser(pUser->GetUserName())) {
// This can't happen, because we got the user from FindUser()
PutModule(t_s("Error: Internal error!"));
return;
}
PutModule(t_f("User {1} deleted!")(sUsername));
return;
}
void CloneUser(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule(
t_s("Error: You need to have admin rights to add new users!"));
return;
}
const CString sOldUsername = sLine.Token(1),
sNewUsername = sLine.Token(2, true);
if (sOldUsername.empty() || sNewUsername.empty()) {
PutModule(t_s("Usage: CloneUser <old username> <new username>"));
return;
}
CUser* pOldUser = CZNC::Get().FindUser(sOldUsername);
if (!pOldUser) {
PutModule(t_f("Error: User [{1}] does not exist!")(sOldUsername));
return;
}
CUser* pNewUser = new CUser(sNewUsername);
CString sError;
if (!pNewUser->Clone(*pOldUser, sError)) {
delete pNewUser;
PutModule(t_f("Error: Cloning failed: {1}")(sError));
return;
}
if (!CZNC::Get().AddUser(pNewUser, sError)) {
delete pNewUser;
PutModule(t_f("Error: User not added: {1}")(sError));
return;
}
PutModule(t_f("User {1} added!")(sNewUsername));
return;
}
void AddNetwork(const CString& sLine) {
CString sUser = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CUser* pUser = GetUser();
if (sNetwork.empty()) {
sNetwork = sUser;
} else {
pUser = FindUser(sUser);
if (!pUser) {
return;
}
}
if (sNetwork.empty()) {
PutModule(t_s("Usage: AddNetwork [user] network"));
return;
}
if (!GetUser()->IsAdmin() && !pUser->HasSpaceForNewNetwork()) {
PutStatus(
t_s("Network number limit reached. Ask an admin to increase "
"the limit for you, or delete unneeded networks using /znc "
"DelNetwork <name>"));
return;
}
if (pUser->FindNetwork(sNetwork)) {
PutModule(
t_f("Error: User {1} already has a network with the name {2}")(
pUser->GetUserName(), sNetwork));
return;
}
CString sNetworkAddError;
if (pUser->AddNetwork(sNetwork, sNetworkAddError)) {
PutModule(t_f("Network {1} added to user {2}.")(
sNetwork, pUser->GetUserName()));
} else {
PutModule(t_f(
"Error: Network [{1}] could not be added for user {2}: {3}")(
sNetwork, pUser->GetUserName(), sNetworkAddError));
}
}
void DelNetwork(const CString& sLine) {
CString sUser = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CUser* pUser = GetUser();
if (sNetwork.empty()) {
sNetwork = sUser;
} else {
pUser = FindUser(sUser);
if (!pUser) {
return;
}
}
if (sNetwork.empty()) {
PutModule(t_s("Usage: DelNetwork [user] network"));
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork == CModule::GetNetwork()) {
PutModule(t_f(
"The currently active network can be deleted via {1}status")(
GetUser()->GetStatusPrefix()));
return;
}
if (pUser->DeleteNetwork(sNetwork)) {
PutModule(t_f("Network {1} deleted for user {2}.")(
sNetwork, pUser->GetUserName()));
} else {
PutModule(
t_f("Error: Network {1} could not be deleted for user {2}.")(
sNetwork, pUser->GetUserName()));
}
}
void ListNetworks(const CString& sLine) {
CString sUser = sLine.Token(1);
CUser* pUser = GetUser();
if (!sUser.empty()) {
pUser = FindUser(sUser);
if (!pUser) {
return;
}
}
const vector<CIRCNetwork*>& vNetworks = pUser->GetNetworks();
CTable Table;
Table.AddColumn(t_s("Network", "listnetworks"));
Table.AddColumn(t_s("OnIRC", "listnetworks"));
Table.AddColumn(t_s("IRC Server", "listnetworks"));
Table.AddColumn(t_s("IRC User", "listnetworks"));
Table.AddColumn(t_s("Channels", "listnetworks"));
for (const CIRCNetwork* pNetwork : vNetworks) {
Table.AddRow();
Table.SetCell(t_s("Network", "listnetworks"), pNetwork->GetName());
if (pNetwork->IsIRCConnected()) {
Table.SetCell(t_s("OnIRC", "listnetworks"), t_s("Yes"));
Table.SetCell(t_s("IRC Server", "listnetworks"),
pNetwork->GetIRCServer());
Table.SetCell(t_s("IRC User", "listnetworks"),
pNetwork->GetIRCNick().GetNickMask());
Table.SetCell(t_s("Channels", "listnetworks"),
CString(pNetwork->GetChans().size()));
} else {
Table.SetCell(t_s("OnIRC", "listnetworks"), t_s("No"));
}
}
if (PutModule(Table) == 0) {
PutModule(t_s("No networks"));
}
}
void AddServer(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sServer = sLine.Token(3, true);
if (sServer.empty()) {
PutModule(
t_s("Usage: AddServer <username> <network> <server> [[+]port] "
"[password]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork->AddServer(sServer))
PutModule(t_f("Added IRC Server {1} to network {2} for user {3}.")(
sServer, pNetwork->GetName(), pUser->GetUserName()));
else
PutModule(t_f(
"Error: Could not add IRC server {1} to network {2} for user "
"{3}.")(sServer, pNetwork->GetName(), pUser->GetUserName()));
}
void DelServer(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sServer = sLine.Token(3, true);
unsigned short uPort = sLine.Token(4).ToUShort();
CString sPass = sLine.Token(5);
if (sServer.empty()) {
PutModule(
t_s("Usage: DelServer <username> <network> <server> [[+]port] "
"[password]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork->DelServer(sServer, uPort, sPass))
PutModule(
t_f("Deleted IRC Server {1} from network {2} for user {3}.")(
sServer, pNetwork->GetName(), pUser->GetUserName()));
else
PutModule(
t_f("Error: Could not delete IRC server {1} from network {2} "
"for user {3}.")(sServer, pNetwork->GetName(),
pUser->GetUserName()));
}
void ReconnectUser(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sNetwork = sLine.Token(2);
if (sNetwork.empty()) {
PutModule(t_s("Usage: Reconnect <username> <network>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) {
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
CIRCSock* pIRCSock = pNetwork->GetIRCSock();
// cancel connection attempt:
if (pIRCSock && !pIRCSock->IsConnected()) {
pIRCSock->Close();
}
// or close existing connection:
else if (pIRCSock) {
pIRCSock->Quit();
}
// then reconnect
pNetwork->SetIRCConnectEnabled(true);
PutModule(t_f("Queued network {1} of user {2} for a reconnect.")(
pNetwork->GetName(), pUser->GetUserName()));
}
void DisconnectUser(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sNetwork = sLine.Token(2);
if (sNetwork.empty()) {
PutModule(t_s("Usage: Disconnect <username> <network>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) {
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
pNetwork->SetIRCConnectEnabled(false);
PutModule(t_f("Closed IRC connection for network {1} of user {2}.")(
pNetwork->GetName(), pUser->GetUserName()));
}
void ListCTCP(const CString& sLine) {
CString sUserName = sLine.Token(1, true);
if (sUserName.empty()) {
sUserName = GetUser()->GetUserName();
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
const MCString& msCTCPReplies = pUser->GetCTCPReplies();
CTable Table;
Table.AddColumn(t_s("Request", "listctcp"));
Table.AddColumn(t_s("Reply", "listctcp"));
for (const auto& it : msCTCPReplies) {
Table.AddRow();
Table.SetCell(t_s("Request", "listctcp"), it.first);
Table.SetCell(t_s("Reply", "listctcp"), it.second);
}
if (Table.empty()) {
PutModule(t_f("No CTCP replies for user {1} are configured")(
pUser->GetUserName()));
} else {
PutModule(t_f("CTCP replies for user {1}:")(pUser->GetUserName()));
PutModule(Table);
}
}
void AddCTCP(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sCTCPRequest = sLine.Token(2);
CString sCTCPReply = sLine.Token(3, true);
if (sCTCPRequest.empty()) {
sCTCPRequest = sUserName;
sCTCPReply = sLine.Token(2, true);
sUserName = GetUser()->GetUserName();
}
if (sCTCPRequest.empty()) {
PutModule(t_s("Usage: AddCTCP [user] [request] [reply]"));
PutModule(
t_s("This will cause ZNC to reply to the CTCP instead of "
"forwarding it to clients."));
PutModule(t_s(
"An empty reply will cause the CTCP request to be blocked."));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
pUser->AddCTCPReply(sCTCPRequest, sCTCPReply);
if (sCTCPReply.empty()) {
PutModule(t_f("CTCP requests {1} to user {2} will now be blocked.")(
sCTCPRequest.AsUpper(), pUser->GetUserName()));
} else {
PutModule(
t_f("CTCP requests {1} to user {2} will now get reply: {3}")(
sCTCPRequest.AsUpper(), pUser->GetUserName(), sCTCPReply));
}
}
void DelCTCP(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sCTCPRequest = sLine.Token(2, true);
if (sCTCPRequest.empty()) {
sCTCPRequest = sUserName;
sUserName = GetUser()->GetUserName();
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
if (sCTCPRequest.empty()) {
PutModule(t_s("Usage: DelCTCP [user] [request]"));
return;
}
if (pUser->DelCTCPReply(sCTCPRequest)) {
PutModule(t_f(
"CTCP requests {1} to user {2} will now be sent to IRC clients")(
sCTCPRequest.AsUpper(), pUser->GetUserName()));
} else {
PutModule(
t_f("CTCP requests {1} to user {2} will be sent to IRC clients "
"(nothing has changed)")(sCTCPRequest.AsUpper(),
pUser->GetUserName()));
}
}
void LoadModuleFor(CModules& Modules, const CString& sModName,
const CString& sArgs, CModInfo::EModuleType eType,
CUser* pUser, CIRCNetwork* pNetwork) {
if (pUser->DenyLoadMod() && !GetUser()->IsAdmin()) {
PutModule(t_s("Loading modules has been disabled."));
return;
}
CString sModRet;
CModule* pMod = Modules.FindModule(sModName);
if (!pMod) {
if (!Modules.LoadModule(sModName, sArgs, eType, pUser, pNetwork,
sModRet)) {
PutModule(t_f("Error: Unable to load module {1}: {2}")(
sModName, sModRet));
} else {
PutModule(t_f("Loaded module {1}")(sModName));
}
} else if (pMod->GetArgs() != sArgs) {
if (!Modules.ReloadModule(sModName, sArgs, pUser, pNetwork,
sModRet)) {
PutModule(t_f("Error: Unable to reload module {1}: {2}")(
sModName, sModRet));
} else {
PutModule(t_f("Reloaded module {1}")(sModName));
}
} else {
PutModule(
t_f("Error: Unable to load module {1} because it is already "
"loaded")(sModName));
}
}
void LoadModuleForUser(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sModName = sLine.Token(2);
CString sArgs = sLine.Token(3, true);
if (sModName.empty()) {
PutModule(t_s("Usage: LoadModule <username> <modulename> [args]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
LoadModuleFor(pUser->GetModules(), sModName, sArgs,
CModInfo::UserModule, pUser, nullptr);
}
void LoadModuleForNetwork(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sModName = sLine.Token(3);
CString sArgs = sLine.Token(4, true);
if (sModName.empty()) {
PutModule(
t_s("Usage: LoadNetModule <username> <network> <modulename> "
"[args]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
LoadModuleFor(pNetwork->GetModules(), sModName, sArgs,
CModInfo::NetworkModule, pUser, pNetwork);
}
void UnLoadModuleFor(CModules& Modules, const CString& sModName,
CUser* pUser) {
if (pUser->DenyLoadMod() && !GetUser()->IsAdmin()) {
PutModule(t_s("Loading modules has been disabled."));
return;
}
if (Modules.FindModule(sModName) == this) {
PutModule(t_f("Please use /znc unloadmod {1}")(sModName));
return;
}
CString sModRet;
if (!Modules.UnloadModule(sModName, sModRet)) {
PutModule(t_f("Error: Unable to unload module {1}: {2}")(sModName,
sModRet));
} else {
PutModule(t_f("Unloaded module {1}")(sModName));
}
}
void UnLoadModuleForUser(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sModName = sLine.Token(2);
if (sModName.empty()) {
PutModule(t_s("Usage: UnloadModule <username> <modulename>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
UnLoadModuleFor(pUser->GetModules(), sModName, pUser);
}
void UnLoadModuleForNetwork(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sModName = sLine.Token(3);
if (sModName.empty()) {
PutModule(t_s(
"Usage: UnloadNetModule <username> <network> <modulename>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
UnLoadModuleFor(pNetwork->GetModules(), sModName, pUser);
}
void ListModulesFor(CModules& Modules) {
CTable Table;
Table.AddColumn(t_s("Name", "listmodules"));
Table.AddColumn(t_s("Arguments", "listmodules"));
for (const CModule* pMod : Modules) {
Table.AddRow();
Table.SetCell(t_s("Name", "listmodules"), pMod->GetModName());
Table.SetCell(t_s("Arguments", "listmodules"), pMod->GetArgs());
}
PutModule(Table);
}
void ListModulesForUser(const CString& sLine) {
CString sUsername = sLine.Token(1);
if (sUsername.empty()) {
PutModule("Usage: ListMods <username>");
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
if (pUser->GetModules().empty()) {
PutModule(
t_f("User {1} has no modules loaded.")(pUser->GetUserName()));
return;
}
PutModule(t_f("Modules loaded for user {1}:")(pUser->GetUserName()));
ListModulesFor(pUser->GetModules());
}
void ListModulesForNetwork(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
if (sNetwork.empty()) {
PutModule("Usage: ListNetMods <username> <network>");
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) return;
if (pNetwork->GetModules().empty()) {
PutModule(t_f("Network {1} of user {2} has no modules loaded.")(
pNetwork->GetName(), pUser->GetUserName()));
return;
}
PutModule(t_f("Modules loaded for network {1} of user {2}:")(
pNetwork->GetName(), pUser->GetUserName()));
ListModulesFor(pNetwork->GetModules());
}
public:
MODCONSTRUCTOR(CAdminMod) {
AddCommand("Help", t_d("[command] [variable]"),
t_d("Prints help for matching commands and variables"),
[=](const CString& sLine) { PrintHelp(sLine); });
AddCommand(
"Get", t_d("<variable> [username]"),
t_d("Prints the variable's value for the given or current user"),
[=](const CString& sLine) { Get(sLine); });
AddCommand("Set", t_d("<variable> <username> <value>"),
t_d("Sets the variable's value for the given user"),
[=](const CString& sLine) { Set(sLine); });
AddCommand("GetNetwork", t_d("<variable> [username] [network]"),
t_d("Prints the variable's value for the given network"),
[=](const CString& sLine) { GetNetwork(sLine); });
AddCommand("SetNetwork", t_d("<variable> <username> <network> <value>"),
t_d("Sets the variable's value for the given network"),
[=](const CString& sLine) { SetNetwork(sLine); });
AddCommand("GetChan", t_d("<variable> [username] <network> <chan>"),
t_d("Prints the variable's value for the given channel"),
[=](const CString& sLine) { GetChan(sLine); });
AddCommand("SetChan",
t_d("<variable> <username> <network> <chan> <value>"),
t_d("Sets the variable's value for the given channel"),
[=](const CString& sLine) { SetChan(sLine); });
AddCommand("AddChan", t_d("<username> <network> <chan>"),
t_d("Adds a new channel"),
[=](const CString& sLine) { AddChan(sLine); });
AddCommand("DelChan", t_d("<username> <network> <chan>"),
t_d("Deletes a channel"),
[=](const CString& sLine) { DelChan(sLine); });
AddCommand("ListUsers", "", t_d("Lists users"),
[=](const CString& sLine) { ListUsers(sLine); });
AddCommand("AddUser", t_d("<username> <password>"),
t_d("Adds a new user"),
[=](const CString& sLine) { AddUser(sLine); });
AddCommand("DelUser", t_d("<username>"), t_d("Deletes a user"),
[=](const CString& sLine) { DelUser(sLine); });
AddCommand("CloneUser", t_d("<old username> <new username>"),
t_d("Clones a user"),
[=](const CString& sLine) { CloneUser(sLine); });
AddCommand("AddServer", t_d("<username> <network> <server>"),
t_d("Adds a new IRC server for the given or current user"),
[=](const CString& sLine) { AddServer(sLine); });
AddCommand("DelServer", t_d("<username> <network> <server>"),
t_d("Deletes an IRC server from the given or current user"),
[=](const CString& sLine) { DelServer(sLine); });
AddCommand("Reconnect", t_d("<username> <network>"),
t_d("Cycles the user's IRC server connection"),
[=](const CString& sLine) { ReconnectUser(sLine); });
AddCommand("Disconnect", t_d("<username> <network>"),
t_d("Disconnects the user from their IRC server"),
[=](const CString& sLine) { DisconnectUser(sLine); });
AddCommand("LoadModule", t_d("<username> <modulename> [args]"),
t_d("Loads a Module for a user"),
[=](const CString& sLine) { LoadModuleForUser(sLine); });
AddCommand("UnLoadModule", t_d("<username> <modulename>"),
t_d("Removes a Module of a user"),
[=](const CString& sLine) { UnLoadModuleForUser(sLine); });
AddCommand("ListMods", t_d("<username>"),
t_d("Get the list of modules for a user"),
[=](const CString& sLine) { ListModulesForUser(sLine); });
AddCommand("LoadNetModule",
t_d("<username> <network> <modulename> [args]"),
t_d("Loads a Module for a network"),
[=](const CString& sLine) { LoadModuleForNetwork(sLine); });
AddCommand(
"UnLoadNetModule", t_d("<username> <network> <modulename>"),
t_d("Removes a Module of a network"),
[=](const CString& sLine) { UnLoadModuleForNetwork(sLine); });
AddCommand("ListNetMods", t_d("<username> <network>"),
t_d("Get the list of modules for a network"),
[=](const CString& sLine) { ListModulesForNetwork(sLine); });
AddCommand("ListCTCPs", t_d("<username>"),
t_d("List the configured CTCP replies"),
[=](const CString& sLine) { ListCTCP(sLine); });
AddCommand("AddCTCP", t_d("<username> <ctcp> [reply]"),
t_d("Configure a new CTCP reply"),
[=](const CString& sLine) { AddCTCP(sLine); });
AddCommand("DelCTCP", t_d("<username> <ctcp>"),
t_d("Remove a CTCP reply"),
[=](const CString& sLine) { DelCTCP(sLine); });
// Network commands
AddCommand("AddNetwork", t_d("[username] <network>"),
t_d("Add a network for a user"),
[=](const CString& sLine) { AddNetwork(sLine); });
AddCommand("DelNetwork", t_d("[username] <network>"),
t_d("Delete a network for a user"),
[=](const CString& sLine) { DelNetwork(sLine); });
AddCommand("ListNetworks", t_d("[username]"),
t_d("List all networks for a user"),
[=](const CString& sLine) { ListNetworks(sLine); });
}
~CAdminMod() override {}
};
template <>
void TModInfo<CAdminMod>(CModInfo& Info) {
Info.SetWikiPage("controlpanel");
}
USERMODULEDEFS(CAdminMod,
t_s("Dynamic configuration through IRC. Allows editing only "
"yourself if you're not ZNC admin."))
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1442_0 |
crossvul-cpp_data_good_2369_0 | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/math.h>
#include <base/system.h>
#include <engine/config.h>
#include <engine/console.h>
#include <engine/engine.h>
#include <engine/map.h>
#include <engine/masterserver.h>
#include <engine/server.h>
#include <engine/storage.h>
#include <engine/shared/compression.h>
#include <engine/shared/config.h>
#include <engine/shared/datafile.h>
#include <engine/shared/demo.h>
#include <engine/shared/econ.h>
#include <engine/shared/filecollection.h>
#include <engine/shared/mapchecker.h>
#include <engine/shared/netban.h>
#include <engine/shared/network.h>
#include <engine/shared/packer.h>
#include <engine/shared/protocol.h>
#include <engine/shared/snapshot.h>
#include <mastersrv/mastersrv.h>
#include "register.h"
#include "server.h"
#if defined(CONF_FAMILY_WINDOWS)
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
static const char *StrLtrim(const char *pStr)
{
while(*pStr && *pStr >= 0 && *pStr <= 32)
pStr++;
return pStr;
}
static void StrRtrim(char *pStr)
{
int i = str_length(pStr);
while(i >= 0)
{
if(pStr[i] < 0 || pStr[i] > 32)
break;
pStr[i] = 0;
i--;
}
}
CSnapIDPool::CSnapIDPool()
{
Reset();
}
void CSnapIDPool::Reset()
{
for(int i = 0; i < MAX_IDS; i++)
{
m_aIDs[i].m_Next = i+1;
m_aIDs[i].m_State = 0;
}
m_aIDs[MAX_IDS-1].m_Next = -1;
m_FirstFree = 0;
m_FirstTimed = -1;
m_LastTimed = -1;
m_Usage = 0;
m_InUsage = 0;
}
void CSnapIDPool::RemoveFirstTimeout()
{
int NextTimed = m_aIDs[m_FirstTimed].m_Next;
// add it to the free list
m_aIDs[m_FirstTimed].m_Next = m_FirstFree;
m_aIDs[m_FirstTimed].m_State = 0;
m_FirstFree = m_FirstTimed;
// remove it from the timed list
m_FirstTimed = NextTimed;
if(m_FirstTimed == -1)
m_LastTimed = -1;
m_Usage--;
}
int CSnapIDPool::NewID()
{
int64 Now = time_get();
// process timed ids
while(m_FirstTimed != -1 && m_aIDs[m_FirstTimed].m_Timeout < Now)
RemoveFirstTimeout();
int ID = m_FirstFree;
dbg_assert(ID != -1, "id error");
if(ID == -1)
return ID;
m_FirstFree = m_aIDs[m_FirstFree].m_Next;
m_aIDs[ID].m_State = 1;
m_Usage++;
m_InUsage++;
return ID;
}
void CSnapIDPool::TimeoutIDs()
{
// process timed ids
while(m_FirstTimed != -1)
RemoveFirstTimeout();
}
void CSnapIDPool::FreeID(int ID)
{
if(ID < 0)
return;
dbg_assert(m_aIDs[ID].m_State == 1, "id is not alloced");
m_InUsage--;
m_aIDs[ID].m_State = 2;
m_aIDs[ID].m_Timeout = time_get()+time_freq()*5;
m_aIDs[ID].m_Next = -1;
if(m_LastTimed != -1)
{
m_aIDs[m_LastTimed].m_Next = ID;
m_LastTimed = ID;
}
else
{
m_FirstTimed = ID;
m_LastTimed = ID;
}
}
void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer* pServer)
{
CNetBan::Init(pConsole, pStorage);
m_pServer = pServer;
// overwrites base command, todo: improve this
Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason");
}
template<class T>
int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)
{
// validate address
if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS &&
Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
{
if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID)))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)");
return -1;
}
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
continue;
if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
return -1;
}
}
}
else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE)
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
continue;
if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
return -1;
}
}
}
int Result = Ban(pBanPool, pData, Seconds, pReason);
if(Result != 0)
return Result;
// drop banned clients
typename T::CDataType Data = *pData;
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
continue;
if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i)))
{
CNetHash NetHash(&Data);
char aBuf[256];
MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER);
Server()->m_NetServer.Drop(i, aBuf);
}
}
return Result;
}
int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)
{
return BanExt(&m_BanAddrPool, pAddr, Seconds, pReason);
}
int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
{
if(pRange->IsValid())
return BanExt(&m_BanRangePool, pRange, Seconds, pReason);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
return -1;
}
void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser)
{
CServerBan *pThis = static_cast<CServerBan *>(pUser);
const char *pStr = pResult->GetString(0);
int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30;
const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given";
if(StrAllnum(pStr))
{
int ClientID = str_toint(pStr);
if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)");
else
pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason);
}
else
ConBan(pResult, pUser);
}
void CServer::CClient::Reset()
{
// reset input
for(int i = 0; i < 200; i++)
m_aInputs[i].m_GameTick = -1;
m_CurrentInput = 0;
mem_zero(&m_LatestInput, sizeof(m_LatestInput));
m_Snapshots.PurgeAll();
m_LastAckedSnapshot = -1;
m_LastInputTick = -1;
m_SnapRate = CClient::SNAPRATE_INIT;
m_Score = 0;
}
CServer::CServer() : m_DemoRecorder(&m_SnapshotDelta)
{
m_TickSpeed = SERVER_TICK_SPEED;
m_pGameServer = 0;
m_CurrentGameTick = 0;
m_RunServer = 1;
m_pCurrentMapData = 0;
m_CurrentMapSize = 0;
m_MapReload = 0;
m_RconClientID = IServer::RCON_CID_SERV;
m_RconAuthLevel = AUTHED_ADMIN;
Init();
}
int CServer::TrySetClientName(int ClientID, const char *pName)
{
char aTrimmedName[64];
// trim the name
str_copy(aTrimmedName, StrLtrim(pName), sizeof(aTrimmedName));
StrRtrim(aTrimmedName);
// check for empty names
if(!aTrimmedName[0])
return -1;
// check if new and old name are the same
if(m_aClients[ClientID].m_aName[0] && str_comp(m_aClients[ClientID].m_aName, aTrimmedName) == 0)
return 0;
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "'%s' -> '%s'", pName, aTrimmedName);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
pName = aTrimmedName;
// make sure that two clients doesn't have the same name
for(int i = 0; i < MAX_CLIENTS; i++)
if(i != ClientID && m_aClients[i].m_State >= CClient::STATE_READY)
{
if(str_comp(pName, m_aClients[i].m_aName) == 0)
return -1;
}
// set the client name
str_copy(m_aClients[ClientID].m_aName, pName, MAX_NAME_LENGTH);
return 0;
}
void CServer::SetClientName(int ClientID, const char *pName)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)
return;
if(!pName)
return;
char aCleanName[MAX_NAME_LENGTH];
str_copy(aCleanName, pName, sizeof(aCleanName));
// clear name
for(char *p = aCleanName; *p; ++p)
{
if(*p < 32)
*p = ' ';
}
if(TrySetClientName(ClientID, aCleanName))
{
// auto rename
for(int i = 1;; i++)
{
char aNameTry[MAX_NAME_LENGTH];
str_format(aNameTry, sizeof(aCleanName), "(%d)%s", i, aCleanName);
if(TrySetClientName(ClientID, aNameTry) == 0)
break;
}
}
}
void CServer::SetClientClan(int ClientID, const char *pClan)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pClan)
return;
str_copy(m_aClients[ClientID].m_aClan, pClan, MAX_CLAN_LENGTH);
}
void CServer::SetClientCountry(int ClientID, int Country)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)
return;
m_aClients[ClientID].m_Country = Country;
}
void CServer::SetClientScore(int ClientID, int Score)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)
return;
m_aClients[ClientID].m_Score = Score;
}
void CServer::Kick(int ClientID, const char *pReason)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY)
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client id to kick");
return;
}
else if(m_RconClientID == ClientID)
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't kick yourself");
return;
}
else if(m_aClients[ClientID].m_Authed > m_RconAuthLevel)
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "kick command denied");
return;
}
m_NetServer.Drop(ClientID, pReason);
}
/*int CServer::Tick()
{
return m_CurrentGameTick;
}*/
int64 CServer::TickStartTime(int Tick)
{
return m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED;
}
/*int CServer::TickSpeed()
{
return SERVER_TICK_SPEED;
}*/
int CServer::Init()
{
for(int i = 0; i < MAX_CLIENTS; i++)
{
m_aClients[i].m_State = CClient::STATE_EMPTY;
m_aClients[i].m_aName[0] = 0;
m_aClients[i].m_aClan[0] = 0;
m_aClients[i].m_Country = -1;
m_aClients[i].m_Snapshots.Init();
}
m_CurrentGameTick = 0;
return 0;
}
void CServer::SetRconCID(int ClientID)
{
m_RconClientID = ClientID;
}
bool CServer::IsAuthed(int ClientID)
{
return m_aClients[ClientID].m_Authed;
}
int CServer::GetClientInfo(int ClientID, CClientInfo *pInfo)
{
dbg_assert(ClientID >= 0 && ClientID < MAX_CLIENTS, "client_id is not valid");
dbg_assert(pInfo != 0, "info can not be null");
if(m_aClients[ClientID].m_State == CClient::STATE_INGAME)
{
pInfo->m_pName = m_aClients[ClientID].m_aName;
pInfo->m_Latency = m_aClients[ClientID].m_Latency;
return 1;
}
return 0;
}
void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size)
{
if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME)
net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false);
}
const char *CServer::ClientName(int ClientID)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
return "(invalid)";
if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)
return m_aClients[ClientID].m_aName;
else
return "(connecting)";
}
const char *CServer::ClientClan(int ClientID)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
return "";
if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)
return m_aClients[ClientID].m_aClan;
else
return "";
}
int CServer::ClientCountry(int ClientID)
{
if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
return -1;
if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)
return m_aClients[ClientID].m_Country;
else
return -1;
}
bool CServer::ClientIngame(int ClientID)
{
return ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME;
}
int CServer::MaxClients() const
{
return m_NetServer.MaxClients();
}
int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)
{
return SendMsgEx(pMsg, Flags, ClientID, false);
}
int CServer::SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System)
{
CNetChunk Packet;
if(!pMsg)
return -1;
mem_zero(&Packet, sizeof(CNetChunk));
Packet.m_ClientID = ClientID;
Packet.m_pData = pMsg->Data();
Packet.m_DataSize = pMsg->Size();
// HACK: modify the message id in the packet and store the system flag
*((unsigned char*)Packet.m_pData) <<= 1;
if(System)
*((unsigned char*)Packet.m_pData) |= 1;
if(Flags&MSGFLAG_VITAL)
Packet.m_Flags |= NETSENDFLAG_VITAL;
if(Flags&MSGFLAG_FLUSH)
Packet.m_Flags |= NETSENDFLAG_FLUSH;
// write message to demo recorder
if(!(Flags&MSGFLAG_NORECORD))
m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());
if(!(Flags&MSGFLAG_NOSEND))
{
if(ClientID == -1)
{
// broadcast
int i;
for(i = 0; i < MAX_CLIENTS; i++)
if(m_aClients[i].m_State == CClient::STATE_INGAME)
{
Packet.m_ClientID = i;
m_NetServer.Send(&Packet);
}
}
else
m_NetServer.Send(&Packet);
}
return 0;
}
void CServer::DoSnapshot()
{
GameServer()->OnPreSnap();
// create snapshot for demo recording
if(m_DemoRecorder.IsRecording())
{
char aData[CSnapshot::MAX_SIZE];
int SnapshotSize;
// build snap and possibly add some messages
m_SnapshotBuilder.Init();
GameServer()->OnSnap(-1);
SnapshotSize = m_SnapshotBuilder.Finish(aData);
// write snapshot
m_DemoRecorder.RecordSnapshot(Tick(), aData, SnapshotSize);
}
// create snapshots for all clients
for(int i = 0; i < MAX_CLIENTS; i++)
{
// client must be ingame to recive snapshots
if(m_aClients[i].m_State != CClient::STATE_INGAME)
continue;
// this client is trying to recover, don't spam snapshots
if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick()%50) != 0)
continue;
// this client is trying to recover, don't spam snapshots
if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0)
continue;
{
char aData[CSnapshot::MAX_SIZE];
CSnapshot *pData = (CSnapshot*)aData; // Fix compiler warning for strict-aliasing
char aDeltaData[CSnapshot::MAX_SIZE];
char aCompData[CSnapshot::MAX_SIZE];
int SnapshotSize;
int Crc;
static CSnapshot EmptySnap;
CSnapshot *pDeltashot = &EmptySnap;
int DeltashotSize;
int DeltaTick = -1;
int DeltaSize;
m_SnapshotBuilder.Init();
GameServer()->OnSnap(i);
// finish snapshot
SnapshotSize = m_SnapshotBuilder.Finish(pData);
Crc = pData->Crc();
// remove old snapshos
// keep 3 seconds worth of snapshots
m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3);
// save it the snapshot
m_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0);
// find snapshot that we can preform delta against
EmptySnap.Clear();
{
DeltashotSize = m_aClients[i].m_Snapshots.Get(m_aClients[i].m_LastAckedSnapshot, 0, &pDeltashot, 0);
if(DeltashotSize >= 0)
DeltaTick = m_aClients[i].m_LastAckedSnapshot;
else
{
// no acked package found, force client to recover rate
if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL)
m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER;
}
}
// create delta
DeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData);
if(DeltaSize)
{
// compress it
int SnapshotSize;
const int MaxSize = MAX_SNAPSHOT_PACKSIZE;
int NumPackets;
SnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData);
NumPackets = (SnapshotSize+MaxSize-1)/MaxSize;
for(int n = 0, Left = SnapshotSize; Left; n++)
{
int Chunk = Left < MaxSize ? Left : MaxSize;
Left -= Chunk;
if(NumPackets == 1)
{
CMsgPacker Msg(NETMSG_SNAPSINGLE);
Msg.AddInt(m_CurrentGameTick);
Msg.AddInt(m_CurrentGameTick-DeltaTick);
Msg.AddInt(Crc);
Msg.AddInt(Chunk);
Msg.AddRaw(&aCompData[n*MaxSize], Chunk);
SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true);
}
else
{
CMsgPacker Msg(NETMSG_SNAP);
Msg.AddInt(m_CurrentGameTick);
Msg.AddInt(m_CurrentGameTick-DeltaTick);
Msg.AddInt(NumPackets);
Msg.AddInt(n);
Msg.AddInt(Crc);
Msg.AddInt(Chunk);
Msg.AddRaw(&aCompData[n*MaxSize], Chunk);
SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true);
}
}
}
else
{
CMsgPacker Msg(NETMSG_SNAPEMPTY);
Msg.AddInt(m_CurrentGameTick);
Msg.AddInt(m_CurrentGameTick-DeltaTick);
SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true);
}
}
}
GameServer()->OnPostSnap();
}
int CServer::NewClientCallback(int ClientID, void *pUser)
{
CServer *pThis = (CServer *)pUser;
pThis->m_aClients[ClientID].m_State = CClient::STATE_AUTH;
pThis->m_aClients[ClientID].m_aName[0] = 0;
pThis->m_aClients[ClientID].m_aClan[0] = 0;
pThis->m_aClients[ClientID].m_Country = -1;
pThis->m_aClients[ClientID].m_Authed = AUTHED_NO;
pThis->m_aClients[ClientID].m_AuthTries = 0;
pThis->m_aClients[ClientID].m_pRconCmdToSend = 0;
pThis->m_aClients[ClientID].Reset();
return 0;
}
int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser)
{
CServer *pThis = (CServer *)pUser;
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason);
pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
// notify the mod about the drop
if(pThis->m_aClients[ClientID].m_State >= CClient::STATE_READY)
pThis->GameServer()->OnClientDrop(ClientID, pReason);
pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY;
pThis->m_aClients[ClientID].m_aName[0] = 0;
pThis->m_aClients[ClientID].m_aClan[0] = 0;
pThis->m_aClients[ClientID].m_Country = -1;
pThis->m_aClients[ClientID].m_Authed = AUTHED_NO;
pThis->m_aClients[ClientID].m_AuthTries = 0;
pThis->m_aClients[ClientID].m_pRconCmdToSend = 0;
pThis->m_aClients[ClientID].m_Snapshots.PurgeAll();
return 0;
}
void CServer::SendMap(int ClientID)
{
CMsgPacker Msg(NETMSG_MAP_CHANGE);
Msg.AddString(GetMapName(), 0);
Msg.AddInt(m_CurrentMapCrc);
Msg.AddInt(m_CurrentMapSize);
SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true);
}
void CServer::SendConnectionReady(int ClientID)
{
CMsgPacker Msg(NETMSG_CON_READY);
SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true);
}
void CServer::SendRconLine(int ClientID, const char *pLine)
{
CMsgPacker Msg(NETMSG_RCON_LINE);
Msg.AddString(pLine, 512);
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
}
void CServer::SendRconLineAuthed(const char *pLine, void *pUser)
{
CServer *pThis = (CServer *)pUser;
static volatile int ReentryGuard = 0;
int i;
if(ReentryGuard) return;
ReentryGuard++;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY && pThis->m_aClients[i].m_Authed >= pThis->m_RconAuthLevel)
pThis->SendRconLine(i, pLine);
}
ReentryGuard--;
}
void CServer::SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID)
{
CMsgPacker Msg(NETMSG_RCON_CMD_ADD);
Msg.AddString(pCommandInfo->m_pName, IConsole::TEMPCMD_NAME_LENGTH);
Msg.AddString(pCommandInfo->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH);
Msg.AddString(pCommandInfo->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH);
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
}
void CServer::SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID)
{
CMsgPacker Msg(NETMSG_RCON_CMD_REM);
Msg.AddString(pCommandInfo->m_pName, 256);
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
}
void CServer::UpdateClientRconCommands()
{
int ClientID = Tick() % MAX_CLIENTS;
if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed)
{
int ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD;
for(int i = 0; i < MAX_RCONCMD_SEND && m_aClients[ClientID].m_pRconCmdToSend; ++i)
{
SendRconCmdAdd(m_aClients[ClientID].m_pRconCmdToSend, ClientID);
m_aClients[ClientID].m_pRconCmdToSend = m_aClients[ClientID].m_pRconCmdToSend->NextCommandInfo(ConsoleAccessLevel, CFGFLAG_SERVER);
}
}
}
void CServer::ProcessClientPacket(CNetChunk *pPacket)
{
int ClientID = pPacket->m_ClientID;
CUnpacker Unpacker;
Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize);
// unpack msgid and system flag
int Msg = Unpacker.GetInt();
int Sys = Msg&1;
Msg >>= 1;
if(Unpacker.Error())
return;
if(Sys)
{
// system message
if(Msg == NETMSG_INFO)
{
if(m_aClients[ClientID].m_State == CClient::STATE_AUTH)
{
const char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC);
if(str_comp(pVersion, GameServer()->NetVersion()) != 0)
{
// wrong version
char aReason[256];
str_format(aReason, sizeof(aReason), "Wrong version. Server is running '%s' and client '%s'", GameServer()->NetVersion(), pVersion);
m_NetServer.Drop(ClientID, aReason);
return;
}
const char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC);
if(g_Config.m_Password[0] != 0 && str_comp(g_Config.m_Password, pPassword) != 0)
{
// wrong password
m_NetServer.Drop(ClientID, "Wrong password");
return;
}
m_aClients[ClientID].m_State = CClient::STATE_CONNECTING;
SendMap(ClientID);
}
}
else if(Msg == NETMSG_REQUEST_MAP_DATA)
{
if(m_aClients[ClientID].m_State < CClient::STATE_CONNECTING)
return;
int Chunk = Unpacker.GetInt();
unsigned int ChunkSize = 1024-128;
unsigned int Offset = Chunk * ChunkSize;
int Last = 0;
// drop faulty map data requests
if(Chunk < 0 || Offset > m_CurrentMapSize)
return;
if(Offset+ChunkSize >= m_CurrentMapSize)
{
ChunkSize = m_CurrentMapSize-Offset;
if(ChunkSize < 0)
ChunkSize = 0;
Last = 1;
}
CMsgPacker Msg(NETMSG_MAP_DATA);
Msg.AddInt(Last);
Msg.AddInt(m_CurrentMapCrc);
Msg.AddInt(Chunk);
Msg.AddInt(ChunkSize);
Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize);
SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true);
if(g_Config.m_Debug)
{
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "sending chunk %d with size %d", Chunk, ChunkSize);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf);
}
}
else if(Msg == NETMSG_READY)
{
if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING)
{
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%x addr=%s", ClientID, aAddrStr);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
m_aClients[ClientID].m_State = CClient::STATE_READY;
GameServer()->OnClientConnected(ClientID);
SendConnectionReady(ClientID);
}
}
else if(Msg == NETMSG_ENTERGAME)
{
if(m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID))
{
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%x addr=%s", ClientID, aAddrStr);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
m_aClients[ClientID].m_State = CClient::STATE_INGAME;
GameServer()->OnClientEnter(ClientID);
}
}
else if(Msg == NETMSG_INPUT)
{
CClient::CInput *pInput;
int64 TagTime;
m_aClients[ClientID].m_LastAckedSnapshot = Unpacker.GetInt();
int IntendedTick = Unpacker.GetInt();
int Size = Unpacker.GetInt();
// check for errors
if(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE)
return;
if(m_aClients[ClientID].m_LastAckedSnapshot > 0)
m_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL;
if(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0)
m_aClients[ClientID].m_Latency = (int)(((time_get()-TagTime)*1000)/time_freq());
// add message to report the input timing
// skip packets that are old
if(IntendedTick > m_aClients[ClientID].m_LastInputTick)
{
int TimeLeft = ((TickStartTime(IntendedTick)-time_get())*1000) / time_freq();
CMsgPacker Msg(NETMSG_INPUTTIMING);
Msg.AddInt(IntendedTick);
Msg.AddInt(TimeLeft);
SendMsgEx(&Msg, 0, ClientID, true);
}
m_aClients[ClientID].m_LastInputTick = IntendedTick;
pInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput];
if(IntendedTick <= Tick())
IntendedTick = Tick()+1;
pInput->m_GameTick = IntendedTick;
for(int i = 0; i < Size/4; i++)
pInput->m_aData[i] = Unpacker.GetInt();
mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int));
m_aClients[ClientID].m_CurrentInput++;
m_aClients[ClientID].m_CurrentInput %= 200;
// call the mod with the fresh input data
if(m_aClients[ClientID].m_State == CClient::STATE_INGAME)
GameServer()->OnClientDirectInput(ClientID, m_aClients[ClientID].m_LatestInput.m_aData);
}
else if(Msg == NETMSG_RCON_CMD)
{
const char *pCmd = Unpacker.GetString();
if(Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed)
{
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "ClientID=%d rcon='%s'", ClientID, pCmd);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
m_RconClientID = ClientID;
m_RconAuthLevel = m_aClients[ClientID].m_Authed;
Console()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD);
Console()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER);
Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN);
m_RconClientID = IServer::RCON_CID_SERV;
m_RconAuthLevel = AUTHED_ADMIN;
}
}
else if(Msg == NETMSG_RCON_AUTH)
{
const char *pPw;
Unpacker.GetString(); // login name, not used
pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC);
if(Unpacker.Error() == 0)
{
if(g_Config.m_SvRconPassword[0] == 0 && g_Config.m_SvRconModPassword[0] == 0)
{
SendRconLine(ClientID, "No rcon password set on server. Set sv_rcon_password and/or sv_rcon_mod_password to enable the remote console.");
}
else if(g_Config.m_SvRconPassword[0] && str_comp(pPw, g_Config.m_SvRconPassword) == 0)
{
CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
Msg.AddInt(1); //authed
Msg.AddInt(1); //cmdlist
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
m_aClients[ClientID].m_Authed = AUTHED_ADMIN;
int SendRconCmds = Unpacker.GetInt();
if(Unpacker.Error() == 0 && SendRconCmds)
m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_ADMIN, CFGFLAG_SERVER);
SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted.");
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (admin)", ClientID);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
else if(g_Config.m_SvRconModPassword[0] && str_comp(pPw, g_Config.m_SvRconModPassword) == 0)
{
CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
Msg.AddInt(1); //authed
Msg.AddInt(1); //cmdlist
SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true);
m_aClients[ClientID].m_Authed = AUTHED_MOD;
int SendRconCmds = Unpacker.GetInt();
if(Unpacker.Error() == 0 && SendRconCmds)
m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_MOD, CFGFLAG_SERVER);
SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted.");
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (moderator)", ClientID);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
else if(g_Config.m_SvRconMaxTries)
{
m_aClients[ClientID].m_AuthTries++;
char aBuf[128];
str_format(aBuf, sizeof(aBuf), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, g_Config.m_SvRconMaxTries);
SendRconLine(ClientID, aBuf);
if(m_aClients[ClientID].m_AuthTries >= g_Config.m_SvRconMaxTries)
{
if(!g_Config.m_SvRconBantime)
m_NetServer.Drop(ClientID, "Too many remote console authentication tries");
else
m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, "Too many remote console authentication tries");
}
}
else
{
SendRconLine(ClientID, "Wrong password.");
}
}
}
else if(Msg == NETMSG_PING)
{
CMsgPacker Msg(NETMSG_PING_REPLY);
SendMsgEx(&Msg, 0, ClientID, true);
}
else
{
if(g_Config.m_Debug)
{
char aHex[] = "0123456789ABCDEF";
char aBuf[512];
for(int b = 0; b < pPacket->m_DataSize && b < 32; b++)
{
aBuf[b*3] = aHex[((const unsigned char *)pPacket->m_pData)[b]>>4];
aBuf[b*3+1] = aHex[((const unsigned char *)pPacket->m_pData)[b]&0xf];
aBuf[b*3+2] = ' ';
aBuf[b*3+3] = 0;
}
char aBufMsg[256];
str_format(aBufMsg, sizeof(aBufMsg), "strange message ClientID=%d msg=%d data_size=%d", ClientID, Msg, pPacket->m_DataSize);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBufMsg);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf);
}
}
}
else
{
// game message
if(m_aClients[ClientID].m_State >= CClient::STATE_READY)
GameServer()->OnMessage(Msg, &Unpacker, ClientID);
}
}
void CServer::SendServerInfo(const NETADDR *pAddr, int Token)
{
CNetChunk Packet;
CPacker p;
char aBuf[128];
// count the players
int PlayerCount = 0, ClientCount = 0;
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
{
if(GameServer()->IsClientPlayer(i))
PlayerCount++;
ClientCount++;
}
}
p.Reset();
p.AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO));
str_format(aBuf, sizeof(aBuf), "%d", Token);
p.AddString(aBuf, 6);
p.AddString(GameServer()->Version(), 32);
p.AddString(g_Config.m_SvName, 64);
p.AddString(GetMapName(), 32);
// gametype
p.AddString(GameServer()->GameType(), 16);
// flags
int i = 0;
if(g_Config.m_Password[0]) // password set
i |= SERVER_FLAG_PASSWORD;
str_format(aBuf, sizeof(aBuf), "%d", i);
p.AddString(aBuf, 2);
str_format(aBuf, sizeof(aBuf), "%d", PlayerCount); p.AddString(aBuf, 3); // num players
str_format(aBuf, sizeof(aBuf), "%d", m_NetServer.MaxClients()-g_Config.m_SvSpectatorSlots); p.AddString(aBuf, 3); // max players
str_format(aBuf, sizeof(aBuf), "%d", ClientCount); p.AddString(aBuf, 3); // num clients
str_format(aBuf, sizeof(aBuf), "%d", m_NetServer.MaxClients()); p.AddString(aBuf, 3); // max clients
for(i = 0; i < MAX_CLIENTS; i++)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
{
p.AddString(ClientName(i), MAX_NAME_LENGTH); // client name
p.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan
str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Country); p.AddString(aBuf, 6); // client country
str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Score); p.AddString(aBuf, 6); // client score
str_format(aBuf, sizeof(aBuf), "%d", GameServer()->IsClientPlayer(i)?1:0); p.AddString(aBuf, 2); // is player?
}
}
Packet.m_ClientID = -1;
Packet.m_Address = *pAddr;
Packet.m_Flags = NETSENDFLAG_CONNLESS;
Packet.m_DataSize = p.Size();
Packet.m_pData = p.Data();
m_NetServer.Send(&Packet);
}
void CServer::UpdateServerInfo()
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
SendServerInfo(m_NetServer.ClientAddr(i), -1);
}
}
void CServer::PumpNetwork()
{
CNetChunk Packet;
m_NetServer.Update();
// process packets
while(m_NetServer.Recv(&Packet))
{
if(Packet.m_ClientID == -1)
{
// stateless
if(!m_Register.RegisterProcessPacket(&Packet))
{
if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETINFO)+1 &&
mem_comp(Packet.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0)
{
SendServerInfo(&Packet.m_Address, ((unsigned char *)Packet.m_pData)[sizeof(SERVERBROWSE_GETINFO)]);
}
}
}
else
ProcessClientPacket(&Packet);
}
m_ServerBan.Update();
m_Econ.Update();
}
char *CServer::GetMapName()
{
// get the name of the map without his path
char *pMapShortName = &g_Config.m_SvMap[0];
for(int i = 0; i < str_length(g_Config.m_SvMap)-1; i++)
{
if(g_Config.m_SvMap[i] == '/' || g_Config.m_SvMap[i] == '\\')
pMapShortName = &g_Config.m_SvMap[i+1];
}
return pMapShortName;
}
int CServer::LoadMap(const char *pMapName)
{
//DATAFILE *df;
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName);
/*df = datafile_load(buf);
if(!df)
return 0;*/
// check for valid standard map
if(!m_MapChecker.ReadAndValidateMap(Storage(), aBuf, IStorage::TYPE_ALL))
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapchecker", "invalid standard map");
return 0;
}
if(!m_pMap->Load(aBuf))
return 0;
// stop recording when we change map
m_DemoRecorder.Stop();
// reinit snapshot ids
m_IDPool.TimeoutIDs();
// get the crc of the map
m_CurrentMapCrc = m_pMap->Crc();
char aBufMsg[256];
str_format(aBufMsg, sizeof(aBufMsg), "%s crc is %08x", aBuf, m_CurrentMapCrc);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg);
str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap));
//map_set(df);
// load complete map into memory for download
{
IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);
m_CurrentMapSize = (int)io_length(File);
if(m_pCurrentMapData)
mem_free(m_pCurrentMapData);
m_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize, 1);
io_read(File, m_pCurrentMapData, m_CurrentMapSize);
io_close(File);
}
return 1;
}
void CServer::InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole)
{
m_Register.Init(pNetServer, pMasterServer, pConsole);
}
int CServer::Run()
{
//
m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, SendRconLineAuthed, this);
// load map
if(!LoadMap(g_Config.m_SvMap))
{
dbg_msg("server", "failed to load map. mapname='%s'", g_Config.m_SvMap);
return -1;
}
// start server
NETADDR BindAddr;
if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)
{
// sweet!
BindAddr.type = NETTYPE_ALL;
BindAddr.port = g_Config.m_SvPort;
}
else
{
mem_zero(&BindAddr, sizeof(BindAddr));
BindAddr.type = NETTYPE_ALL;
BindAddr.port = g_Config.m_SvPort;
}
if(!m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0))
{
dbg_msg("server", "couldn't open socket. port %d might already be in use", g_Config.m_SvPort);
return -1;
}
m_NetServer.SetCallbacks(NewClientCallback, DelClientCallback, this);
m_Econ.Init(Console(), &m_ServerBan);
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "server name is '%s'", g_Config.m_SvName);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
GameServer()->OnInit();
str_format(aBuf, sizeof(aBuf), "version %s", GameServer()->NetVersion());
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
// process pending commands
m_pConsole->StoreCommands(false);
// start game
{
int64 ReportTime = time_get();
int ReportInterval = 3;
m_Lastheartbeat = 0;
m_GameStartTime = time_get();
if(g_Config.m_Debug)
{
str_format(aBuf, sizeof(aBuf), "baseline memory usage %dk", mem_stats()->allocated/1024);
Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf);
}
while(m_RunServer)
{
int64 t = time_get();
int NewTicks = 0;
// load new map TODO: don't poll this
if(str_comp(g_Config.m_SvMap, m_aCurrentMap) != 0 || m_MapReload)
{
m_MapReload = 0;
// load map
if(LoadMap(g_Config.m_SvMap))
{
// new map loaded
GameServer()->OnShutdown();
for(int c = 0; c < MAX_CLIENTS; c++)
{
if(m_aClients[c].m_State <= CClient::STATE_AUTH)
continue;
SendMap(c);
m_aClients[c].Reset();
m_aClients[c].m_State = CClient::STATE_CONNECTING;
}
m_GameStartTime = time_get();
m_CurrentGameTick = 0;
Kernel()->ReregisterInterface(GameServer());
GameServer()->OnInit();
UpdateServerInfo();
}
else
{
str_format(aBuf, sizeof(aBuf), "failed to load map. mapname='%s'", g_Config.m_SvMap);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
str_copy(g_Config.m_SvMap, m_aCurrentMap, sizeof(g_Config.m_SvMap));
}
}
while(t > TickStartTime(m_CurrentGameTick+1))
{
m_CurrentGameTick++;
NewTicks++;
// apply new input
for(int c = 0; c < MAX_CLIENTS; c++)
{
if(m_aClients[c].m_State == CClient::STATE_EMPTY)
continue;
for(int i = 0; i < 200; i++)
{
if(m_aClients[c].m_aInputs[i].m_GameTick == Tick())
{
if(m_aClients[c].m_State == CClient::STATE_INGAME)
GameServer()->OnClientPredictedInput(c, m_aClients[c].m_aInputs[i].m_aData);
break;
}
}
}
GameServer()->OnTick();
}
// snap game
if(NewTicks)
{
if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0)
DoSnapshot();
UpdateClientRconCommands();
}
// master server stuff
m_Register.RegisterUpdate(m_NetServer.NetType());
PumpNetwork();
if(ReportTime < time_get())
{
if(g_Config.m_Debug)
{
/*
static NETSTATS prev_stats;
NETSTATS stats;
netserver_stats(net, &stats);
perf_next();
if(config.dbg_pref)
perf_dump(&rootscope);
dbg_msg("server", "send=%8d recv=%8d",
(stats.send_bytes - prev_stats.send_bytes)/reportinterval,
(stats.recv_bytes - prev_stats.recv_bytes)/reportinterval);
prev_stats = stats;
*/
}
ReportTime += time_freq()*ReportInterval;
}
// wait for incomming data
net_socket_read_wait(m_NetServer.Socket(), 5);
}
}
// disconnect all clients on shutdown
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(m_aClients[i].m_State != CClient::STATE_EMPTY)
m_NetServer.Drop(i, "Server shutdown");
m_Econ.Shutdown();
}
GameServer()->OnShutdown();
m_pMap->Unload();
if(m_pCurrentMapData)
mem_free(m_pCurrentMapData);
return 0;
}
void CServer::ConKick(IConsole::IResult *pResult, void *pUser)
{
if(pResult->NumArguments() > 1)
{
char aBuf[128];
str_format(aBuf, sizeof(aBuf), "Kicked (%s)", pResult->GetString(1));
((CServer *)pUser)->Kick(pResult->GetInteger(0), aBuf);
}
else
((CServer *)pUser)->Kick(pResult->GetInteger(0), "Kicked by console");
}
void CServer::ConStatus(IConsole::IResult *pResult, void *pUser)
{
char aBuf[1024];
char aAddrStr[NETADDR_MAXSTRSIZE];
CServer* pThis = static_cast<CServer *>(pUser);
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY)
{
net_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true);
if(pThis->m_aClients[i].m_State == CClient::STATE_INGAME)
{
const char *pAuthStr = pThis->m_aClients[i].m_Authed == CServer::AUTHED_ADMIN ? "(Admin)" :
pThis->m_aClients[i].m_Authed == CServer::AUTHED_MOD ? "(Mod)" : "";
str_format(aBuf, sizeof(aBuf), "id=%d addr=%s name='%s' score=%d %s", i, aAddrStr,
pThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score, pAuthStr);
}
else
str_format(aBuf, sizeof(aBuf), "id=%d addr=%s connecting", i, aAddrStr);
pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf);
}
}
}
void CServer::ConShutdown(IConsole::IResult *pResult, void *pUser)
{
((CServer *)pUser)->m_RunServer = 0;
}
void CServer::DemoRecorder_HandleAutoStart()
{
if(g_Config.m_SvAutoDemoRecord)
{
m_DemoRecorder.Stop();
char aFilename[128];
char aDate[20];
str_timestamp(aDate, sizeof(aDate));
str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", "auto/autorecord", aDate);
m_DemoRecorder.Start(Storage(), m_pConsole, aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "server");
if(g_Config.m_SvAutoDemoMax)
{
// clean up auto recorded demos
CFileCollection AutoDemos;
AutoDemos.Init(Storage(), "demos/server", "autorecord", ".demo", g_Config.m_SvAutoDemoMax);
}
}
}
bool CServer::DemoRecorder_IsRecording()
{
return m_DemoRecorder.IsRecording();
}
void CServer::ConRecord(IConsole::IResult *pResult, void *pUser)
{
CServer* pServer = (CServer *)pUser;
char aFilename[128];
if(pResult->NumArguments())
str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pResult->GetString(0));
else
{
char aDate[20];
str_timestamp(aDate, sizeof(aDate));
str_format(aFilename, sizeof(aFilename), "demos/demo_%s.demo", aDate);
}
pServer->m_DemoRecorder.Start(pServer->Storage(), pServer->Console(), aFilename, pServer->GameServer()->NetVersion(), pServer->m_aCurrentMap, pServer->m_CurrentMapCrc, "server");
}
void CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser)
{
((CServer *)pUser)->m_DemoRecorder.Stop();
}
void CServer::ConMapReload(IConsole::IResult *pResult, void *pUser)
{
((CServer *)pUser)->m_MapReload = 1;
}
void CServer::ConLogout(IConsole::IResult *pResult, void *pUser)
{
CServer *pServer = (CServer *)pUser;
if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS &&
pServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
{
CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
Msg.AddInt(0); //authed
Msg.AddInt(0); //cmdlist
pServer->SendMsgEx(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID, true);
pServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO;
pServer->m_aClients[pServer->m_RconClientID].m_AuthTries = 0;
pServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0;
pServer->SendRconLine(pServer->m_RconClientID, "Logout successful.");
char aBuf[32];
str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out", pServer->m_RconClientID);
pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
}
void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments())
((CServer *)pUserData)->UpdateServerInfo();
}
void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments())
((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIP(pResult->GetInteger(0));
}
void CServer::ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
if(pResult->NumArguments() == 2)
{
CServer *pThis = static_cast<CServer *>(pUserData);
const IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false);
int OldAccessLevel = 0;
if(pInfo)
OldAccessLevel = pInfo->GetAccessLevel();
pfnCallback(pResult, pCallbackUserData);
if(pInfo && OldAccessLevel != pInfo->GetAccessLevel())
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || pThis->m_aClients[i].m_Authed != CServer::AUTHED_MOD ||
(pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0))
continue;
if(OldAccessLevel == IConsole::ACCESS_LEVEL_ADMIN)
pThis->SendRconCmdAdd(pInfo, i);
else
pThis->SendRconCmdRem(pInfo, i);
}
}
}
else
pfnCallback(pResult, pCallbackUserData);
}
void CServer::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments() == 1)
{
CServer *pThis = static_cast<CServer *>(pUserData);
pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0));
}
}
void CServer::RegisterCommands()
{
m_pConsole = Kernel()->RequestInterface<IConsole>();
m_pGameServer = Kernel()->RequestInterface<IGameServer>();
m_pMap = Kernel()->RequestInterface<IEngineMap>();
m_pStorage = Kernel()->RequestInterface<IStorage>();
// register console commands
Console()->Register("kick", "i?r", CFGFLAG_SERVER, ConKick, this, "Kick player with specified id for any reason");
Console()->Register("status", "", CFGFLAG_SERVER, ConStatus, this, "List players");
Console()->Register("shutdown", "", CFGFLAG_SERVER, ConShutdown, this, "Shut down");
Console()->Register("logout", "", CFGFLAG_SERVER, ConLogout, this, "Logout of rcon");
Console()->Register("record", "?s", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file");
Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording");
Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, "Reload the map");
Console()->Chain("sv_name", ConchainSpecialInfoupdate, this);
Console()->Chain("password", ConchainSpecialInfoupdate, this);
Console()->Chain("sv_max_clients_per_ip", ConchainMaxclientsperipUpdate, this);
Console()->Chain("mod_command", ConchainModCommandUpdate, this);
Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this);
// register console commands in sub parts
m_ServerBan.InitServerBan(Console(), Storage(), this);
m_pGameServer->OnConsoleInit();
}
int CServer::SnapNewID()
{
return m_IDPool.NewID();
}
void CServer::SnapFreeID(int ID)
{
m_IDPool.FreeID(ID);
}
void *CServer::SnapNewItem(int Type, int ID, int Size)
{
dbg_assert(Type >= 0 && Type <=0xffff, "incorrect type");
dbg_assert(ID >= 0 && ID <=0xffff, "incorrect id");
return ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size);
}
void CServer::SnapSetStaticsize(int ItemType, int Size)
{
m_SnapshotDelta.SetStaticsize(ItemType, Size);
}
static CServer *CreateServer() { return new CServer(); }
int main(int argc, const char **argv) // ignore_convention
{
#if defined(CONF_FAMILY_WINDOWS)
for(int i = 1; i < argc; i++) // ignore_convention
{
if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
break;
}
}
#endif
CServer *pServer = CreateServer();
IKernel *pKernel = IKernel::Create();
// create the components
IEngine *pEngine = CreateEngine("Teeworlds");
IEngineMap *pEngineMap = CreateEngineMap();
IGameServer *pGameServer = CreateGameServer();
IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON);
IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer();
IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention
IConfig *pConfig = CreateConfig();
pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole);
{
bool RegisterFail = false;
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap));
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig);
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both
RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer));
if(RegisterFail)
return -1;
}
pEngine->Init();
pConfig->Init();
pEngineMasterServer->Init();
pEngineMasterServer->Load();
// register all console commands
pServer->RegisterCommands();
// execute autoexec file
pConsole->ExecuteFile("autoexec.cfg");
// parse the command line arguments
if(argc > 1) // ignore_convention
pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention
// restore empty config strings to their defaults
pConfig->RestoreStrings();
pEngine->InitLogfile();
// run the server
dbg_msg("server", "starting...");
pServer->Run();
// free
delete pServer;
delete pKernel;
delete pEngineMap;
delete pGameServer;
delete pConsole;
delete pEngineMasterServer;
delete pStorage;
delete pConfig;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_2369_0 |
crossvul-cpp_data_bad_1442_2 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/User.h>
#include <znc/Config.h>
#include <znc/FileUtils.h>
#include <znc/IRCNetwork.h>
#include <znc/IRCSock.h>
#include <znc/Chan.h>
#include <znc/Query.h>
#include <math.h>
#include <time.h>
#include <algorithm>
using std::vector;
using std::set;
class CUserTimer : public CCron {
public:
CUserTimer(CUser* pUser) : CCron(), m_pUser(pUser) {
SetName("CUserTimer::" + m_pUser->GetUserName());
Start(m_pUser->GetPingSlack());
}
~CUserTimer() override {}
CUserTimer(const CUserTimer&) = delete;
CUserTimer& operator=(const CUserTimer&) = delete;
private:
protected:
void RunJob() override {
const vector<CClient*>& vUserClients = m_pUser->GetUserClients();
for (CClient* pUserClient : vUserClients) {
if (pUserClient->GetTimeSinceLastDataTransaction() >=
m_pUser->GetPingFrequency()) {
pUserClient->PutClient("PING :ZNC");
}
}
// Restart timer for the case if the period had changed. Usually this is
// noop
Start(m_pUser->GetPingSlack());
}
CUser* m_pUser;
};
CUser::CUser(const CString& sUserName)
: m_sUserName(sUserName),
m_sCleanUserName(MakeCleanUserName(sUserName)),
m_sNick(m_sCleanUserName),
m_sAltNick(""),
m_sIdent(m_sCleanUserName),
m_sRealName(""),
m_sBindHost(""),
m_sDCCBindHost(""),
m_sPass(""),
m_sPassSalt(""),
m_sStatusPrefix("*"),
m_sDefaultChanModes(""),
m_sClientEncoding(""),
m_sQuitMsg(""),
m_mssCTCPReplies(),
m_sTimestampFormat("[%H:%M:%S]"),
m_sTimezone(""),
m_eHashType(HASH_NONE),
m_sUserPath(CZNC::Get().GetUserPath() + "/" + sUserName),
m_bMultiClients(true),
m_bDenyLoadMod(false),
m_bAdmin(false),
m_bDenySetBindHost(false),
m_bAutoClearChanBuffer(true),
m_bAutoClearQueryBuffer(true),
m_bBeingDeleted(false),
m_bAppendTimestamp(false),
m_bPrependTimestamp(true),
m_bAuthOnlyViaModule(false),
m_pUserTimer(nullptr),
m_vIRCNetworks(),
m_vClients(),
m_ssAllowedHosts(),
m_uChanBufferSize(50),
m_uQueryBufferSize(50),
m_uBytesRead(0),
m_uBytesWritten(0),
m_uMaxJoinTries(10),
m_uMaxNetworks(1),
m_uMaxQueryBuffers(50),
m_uMaxJoins(0),
m_uNoTrafficTimeout(180),
m_sSkinName(""),
m_pModules(new CModules) {
m_pUserTimer = new CUserTimer(this);
CZNC::Get().GetManager().AddCron(m_pUserTimer);
}
CUser::~CUser() {
// Delete networks
while (!m_vIRCNetworks.empty()) {
delete *m_vIRCNetworks.begin();
}
// Delete clients
while (!m_vClients.empty()) {
CZNC::Get().GetManager().DelSockByAddr(m_vClients[0]);
}
m_vClients.clear();
// Delete modules (unloads all modules!)
delete m_pModules;
m_pModules = nullptr;
CZNC::Get().GetManager().DelCronByAddr(m_pUserTimer);
CZNC::Get().AddBytesRead(m_uBytesRead);
CZNC::Get().AddBytesWritten(m_uBytesWritten);
}
template <class T>
struct TOption {
const char* name;
void (CUser::*pSetter)(T);
};
bool CUser::ParseConfig(CConfig* pConfig, CString& sError) {
TOption<const CString&> StringOptions[] = {
{"nick", &CUser::SetNick},
{"quitmsg", &CUser::SetQuitMsg},
{"altnick", &CUser::SetAltNick},
{"ident", &CUser::SetIdent},
{"realname", &CUser::SetRealName},
{"chanmodes", &CUser::SetDefaultChanModes},
{"bindhost", &CUser::SetBindHost},
{"vhost", &CUser::SetBindHost},
{"dccbindhost", &CUser::SetDCCBindHost},
{"dccvhost", &CUser::SetDCCBindHost},
{"timestampformat", &CUser::SetTimestampFormat},
{"skin", &CUser::SetSkinName},
{"clientencoding", &CUser::SetClientEncoding},
};
TOption<unsigned int> UIntOptions[] = {
{"jointries", &CUser::SetJoinTries},
{"maxnetworks", &CUser::SetMaxNetworks},
{"maxquerybuffers", &CUser::SetMaxQueryBuffers},
{"maxjoins", &CUser::SetMaxJoins},
{"notraffictimeout", &CUser::SetNoTrafficTimeout},
};
TOption<bool> BoolOptions[] = {
{"keepbuffer",
&CUser::SetKeepBuffer}, // XXX compatibility crap from pre-0.207
{"autoclearchanbuffer", &CUser::SetAutoClearChanBuffer},
{"autoclearquerybuffer", &CUser::SetAutoClearQueryBuffer},
{"multiclients", &CUser::SetMultiClients},
{"denyloadmod", &CUser::SetDenyLoadMod},
{"admin", &CUser::SetAdmin},
{"denysetbindhost", &CUser::SetDenySetBindHost},
{"denysetvhost", &CUser::SetDenySetBindHost},
{"appendtimestamp", &CUser::SetTimestampAppend},
{"prependtimestamp", &CUser::SetTimestampPrepend},
{"authonlyviamodule", &CUser::SetAuthOnlyViaModule},
};
for (const auto& Option : StringOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue);
}
for (const auto& Option : UIntOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue.ToUInt());
}
for (const auto& Option : BoolOptions) {
CString sValue;
if (pConfig->FindStringEntry(Option.name, sValue))
(this->*Option.pSetter)(sValue.ToBool());
}
VCString vsList;
pConfig->FindStringVector("allow", vsList);
for (const CString& sHost : vsList) {
AddAllowedHost(sHost);
}
pConfig->FindStringVector("ctcpreply", vsList);
for (const CString& sReply : vsList) {
AddCTCPReply(sReply.Token(0), sReply.Token(1, true));
}
CString sValue;
CString sDCCLookupValue;
pConfig->FindStringEntry("dcclookupmethod", sDCCLookupValue);
if (pConfig->FindStringEntry("bouncedccs", sValue)) {
if (sValue.ToBool()) {
CUtils::PrintAction("Loading Module [bouncedcc]");
CString sModRet;
bool bModRet = GetModules().LoadModule(
"bouncedcc", "", CModInfo::UserModule, this, nullptr, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
sError = sModRet;
return false;
}
if (sDCCLookupValue.Equals("Client")) {
GetModules().FindModule("bouncedcc")->SetNV("UseClientIP", "1");
}
}
}
if (pConfig->FindStringEntry("buffer", sValue))
SetBufferCount(sValue.ToUInt(), true);
if (pConfig->FindStringEntry("chanbuffersize", sValue))
SetChanBufferSize(sValue.ToUInt(), true);
if (pConfig->FindStringEntry("querybuffersize", sValue))
SetQueryBufferSize(sValue.ToUInt(), true);
if (pConfig->FindStringEntry("awaysuffix", sValue)) {
CUtils::PrintMessage(
"WARNING: AwaySuffix has been deprecated, instead try -> "
"LoadModule = awaynick %nick%_" +
sValue);
}
if (pConfig->FindStringEntry("autocycle", sValue)) {
if (sValue.Equals("true"))
CUtils::PrintError(
"WARNING: AutoCycle has been removed, instead try -> "
"LoadModule = autocycle");
}
if (pConfig->FindStringEntry("keepnick", sValue)) {
if (sValue.Equals("true"))
CUtils::PrintError(
"WARNING: KeepNick has been deprecated, instead try -> "
"LoadModule = keepnick");
}
if (pConfig->FindStringEntry("statusprefix", sValue)) {
if (!SetStatusPrefix(sValue)) {
sError = "Invalid StatusPrefix [" + sValue +
"] Must be 1-5 chars, no spaces.";
CUtils::PrintError(sError);
return false;
}
}
if (pConfig->FindStringEntry("timezone", sValue)) {
SetTimezone(sValue);
}
if (pConfig->FindStringEntry("timezoneoffset", sValue)) {
if (fabs(sValue.ToDouble()) > 0.1) {
CUtils::PrintError(
"WARNING: TimezoneOffset has been deprecated, now you can set "
"your timezone by name");
}
}
if (pConfig->FindStringEntry("timestamp", sValue)) {
if (!sValue.Trim_n().Equals("true")) {
if (sValue.Trim_n().Equals("append")) {
SetTimestampAppend(true);
SetTimestampPrepend(false);
} else if (sValue.Trim_n().Equals("prepend")) {
SetTimestampAppend(false);
SetTimestampPrepend(true);
} else if (sValue.Trim_n().Equals("false")) {
SetTimestampAppend(false);
SetTimestampPrepend(false);
} else {
SetTimestampFormat(sValue);
}
}
}
if (pConfig->FindStringEntry("language", sValue)) {
SetLanguage(sValue);
}
pConfig->FindStringEntry("pass", sValue);
// There are different formats for this available:
// Pass = <plain text>
// Pass = <md5 hash> -
// Pass = plain#<plain text>
// Pass = <hash name>#<hash>
// Pass = <hash name>#<salted hash>#<salt>#
// 'Salted hash' means hash of 'password' + 'salt'
// Possible hashes are md5 and sha256
if (sValue.TrimSuffix("-")) {
SetPass(sValue.Trim_n(), CUser::HASH_MD5);
} else {
CString sMethod = sValue.Token(0, false, "#");
CString sPass = sValue.Token(1, true, "#");
if (sMethod == "md5" || sMethod == "sha256") {
CUser::eHashType type = CUser::HASH_MD5;
if (sMethod == "sha256") type = CUser::HASH_SHA256;
CString sSalt = sPass.Token(1, false, "#");
sPass = sPass.Token(0, false, "#");
SetPass(sPass, type, sSalt);
} else if (sMethod == "plain") {
SetPass(sPass, CUser::HASH_NONE);
} else {
SetPass(sValue, CUser::HASH_NONE);
}
}
CConfig::SubConfig subConf;
CConfig::SubConfig::const_iterator subIt;
pConfig->FindSubConfig("pass", subConf);
if (!sValue.empty() && !subConf.empty()) {
sError = "Password defined more than once";
CUtils::PrintError(sError);
return false;
}
subIt = subConf.begin();
if (subIt != subConf.end()) {
CConfig* pSubConf = subIt->second.m_pSubConfig;
CString sHash;
CString sMethod;
CString sSalt;
CUser::eHashType method;
pSubConf->FindStringEntry("hash", sHash);
pSubConf->FindStringEntry("method", sMethod);
pSubConf->FindStringEntry("salt", sSalt);
if (sMethod.empty() || sMethod.Equals("plain"))
method = CUser::HASH_NONE;
else if (sMethod.Equals("md5"))
method = CUser::HASH_MD5;
else if (sMethod.Equals("sha256"))
method = CUser::HASH_SHA256;
else {
sError = "Invalid hash method";
CUtils::PrintError(sError);
return false;
}
SetPass(sHash, method, sSalt);
if (!pSubConf->empty()) {
sError = "Unhandled lines in config!";
CUtils::PrintError(sError);
CZNC::DumpConfig(pSubConf);
return false;
}
++subIt;
}
if (subIt != subConf.end()) {
sError = "Password defined more than once";
CUtils::PrintError(sError);
return false;
}
pConfig->FindSubConfig("network", subConf);
for (subIt = subConf.begin(); subIt != subConf.end(); ++subIt) {
const CString& sNetworkName = subIt->first;
CUtils::PrintMessage("Loading network [" + sNetworkName + "]");
CIRCNetwork* pNetwork = FindNetwork(sNetworkName);
if (!pNetwork) {
pNetwork = new CIRCNetwork(this, sNetworkName);
}
if (!pNetwork->ParseConfig(subIt->second.m_pSubConfig, sError)) {
return false;
}
}
if (pConfig->FindStringVector("server", vsList, false) ||
pConfig->FindStringVector("chan", vsList, false) ||
pConfig->FindSubConfig("chan", subConf, false)) {
CIRCNetwork* pNetwork = FindNetwork("default");
if (!pNetwork) {
CString sErrorDummy;
pNetwork = AddNetwork("default", sErrorDummy);
}
if (pNetwork) {
CUtils::PrintMessage(
"NOTICE: Found deprecated config, upgrading to a network");
if (!pNetwork->ParseConfig(pConfig, sError, true)) {
return false;
}
}
}
pConfig->FindStringVector("loadmodule", vsList);
for (const CString& sMod : vsList) {
CString sModName = sMod.Token(0);
CString sNotice = "Loading user module [" + sModName + "]";
// XXX Legacy crap, added in ZNC 0.089
if (sModName == "discon_kick") {
sNotice =
"NOTICE: [discon_kick] was renamed, loading [disconkick] "
"instead";
sModName = "disconkick";
}
// XXX Legacy crap, added in ZNC 0.099
if (sModName == "fixfreenode") {
sNotice =
"NOTICE: [fixfreenode] doesn't do anything useful anymore, "
"ignoring it";
CUtils::PrintMessage(sNotice);
continue;
}
// XXX Legacy crap, added in ZNC 0.207
if (sModName == "admin") {
sNotice =
"NOTICE: [admin] module was renamed, loading [controlpanel] "
"instead";
sModName = "controlpanel";
}
// XXX Legacy crap, should have been added ZNC 0.207, but added only in
// 1.1 :(
if (sModName == "away") {
sNotice = "NOTICE: [away] was renamed, loading [awaystore] instead";
sModName = "awaystore";
}
// XXX Legacy crap, added in 1.1; fakeonline module was dropped in 1.0
// and returned in 1.1
if (sModName == "fakeonline") {
sNotice =
"NOTICE: [fakeonline] was renamed, loading [modules_online] "
"instead";
sModName = "modules_online";
}
// XXX Legacy crap, added in 1.3
if (sModName == "charset") {
CUtils::PrintAction(
"NOTICE: Charset support was moved to core, importing old "
"charset module settings");
size_t uIndex = 1;
if (sMod.Token(uIndex).Equals("-force")) {
uIndex++;
}
VCString vsClient, vsServer;
sMod.Token(uIndex).Split(",", vsClient);
sMod.Token(uIndex + 1).Split(",", vsServer);
if (vsClient.empty() || vsServer.empty()) {
CUtils::PrintStatus(
false, "charset module was loaded with wrong parameters.");
continue;
}
SetClientEncoding(vsClient[0]);
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
pNetwork->SetEncoding(vsServer[0]);
}
CUtils::PrintStatus(true, "Using [" + vsClient[0] +
"] for clients, and [" + vsServer[0] +
"] for servers");
continue;
}
CString sModRet;
CString sArgs = sMod.Token(1, true);
bool bModRet = LoadModule(sModName, sArgs, sNotice, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
// XXX The awaynick module was retired in 1.6 (still available as
// external module)
if (sModName == "awaynick") {
// load simple_away instead, unless it's already on the list
if (std::find(vsList.begin(), vsList.end(), "simple_away") ==
vsList.end()) {
sNotice = "Loading [simple_away] module instead";
sModName = "simple_away";
// not a fatal error if simple_away is not available
LoadModule(sModName, sArgs, sNotice, sModRet);
}
} else {
sError = sModRet;
return false;
}
}
continue;
}
// Move ircconnectenabled to the networks
if (pConfig->FindStringEntry("ircconnectenabled", sValue)) {
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
pNetwork->SetIRCConnectEnabled(sValue.ToBool());
}
}
return true;
}
CIRCNetwork* CUser::AddNetwork(const CString& sNetwork, CString& sErrorRet) {
if (!CIRCNetwork::IsValidNetwork(sNetwork)) {
sErrorRet =
t_s("Invalid network name. It should be alphanumeric. Not to be "
"confused with server name");
return nullptr;
} else if (FindNetwork(sNetwork)) {
sErrorRet = t_f("Network {1} already exists")(sNetwork);
return nullptr;
}
CIRCNetwork* pNetwork = new CIRCNetwork(this, sNetwork);
bool bCancel = false;
USERMODULECALL(OnAddNetwork(*pNetwork, sErrorRet), this, nullptr, &bCancel);
if (bCancel) {
RemoveNetwork(pNetwork);
delete pNetwork;
return nullptr;
}
return pNetwork;
}
bool CUser::AddNetwork(CIRCNetwork* pNetwork) {
if (FindNetwork(pNetwork->GetName())) {
return false;
}
m_vIRCNetworks.push_back(pNetwork);
return true;
}
void CUser::RemoveNetwork(CIRCNetwork* pNetwork) {
auto it = std::find(m_vIRCNetworks.begin(), m_vIRCNetworks.end(), pNetwork);
if (it != m_vIRCNetworks.end()) {
m_vIRCNetworks.erase(it);
}
}
bool CUser::DeleteNetwork(const CString& sNetwork) {
CIRCNetwork* pNetwork = FindNetwork(sNetwork);
if (pNetwork) {
bool bCancel = false;
USERMODULECALL(OnDeleteNetwork(*pNetwork), this, nullptr, &bCancel);
if (!bCancel) {
delete pNetwork;
return true;
}
}
return false;
}
CIRCNetwork* CUser::FindNetwork(const CString& sNetwork) const {
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (pNetwork->GetName().Equals(sNetwork)) {
return pNetwork;
}
}
return nullptr;
}
const vector<CIRCNetwork*>& CUser::GetNetworks() const {
return m_vIRCNetworks;
}
CString CUser::ExpandString(const CString& sStr) const {
CString sRet;
return ExpandString(sStr, sRet);
}
CString& CUser::ExpandString(const CString& sStr, CString& sRet) const {
CString sTime = CUtils::CTime(time(nullptr), m_sTimezone);
sRet = sStr;
sRet.Replace("%altnick%", GetAltNick());
sRet.Replace("%bindhost%", GetBindHost());
sRet.Replace("%defnick%", GetNick());
sRet.Replace("%ident%", GetIdent());
sRet.Replace("%nick%", GetNick());
sRet.Replace("%realname%", GetRealName());
sRet.Replace("%time%", sTime);
sRet.Replace("%uptime%", CZNC::Get().GetUptime());
sRet.Replace("%user%", GetUserName());
sRet.Replace("%version%", CZNC::GetVersion());
sRet.Replace("%vhost%", GetBindHost());
sRet.Replace("%znc%", CZNC::GetTag(false));
// Allows for escaping ExpandString if necessary, or to prevent
// defaults from kicking in if you don't want them.
sRet.Replace("%empty%", "");
// The following lines do not exist. You must be on DrUgS!
sRet.Replace("%irc%", "All your IRC are belong to ZNC");
// Chosen by fair zocchihedron dice roll by SilverLeo
sRet.Replace("%rand%", "42");
return sRet;
}
CString CUser::AddTimestamp(const CString& sStr) const {
timeval tv;
gettimeofday(&tv, nullptr);
return AddTimestamp(tv, sStr);
}
CString CUser::AddTimestamp(time_t tm, const CString& sStr) const {
timeval tv;
tv.tv_sec = tm;
tv.tv_usec = 0;
return AddTimestamp(tv, sStr);
}
CString CUser::AddTimestamp(timeval tv, const CString& sStr) const {
CString sRet = sStr;
if (!GetTimestampFormat().empty() &&
(m_bAppendTimestamp || m_bPrependTimestamp)) {
CString sTimestamp =
CUtils::FormatTime(tv, GetTimestampFormat(), m_sTimezone);
if (sTimestamp.empty()) {
return sRet;
}
if (m_bPrependTimestamp) {
sRet = sTimestamp;
sRet += " " + sStr;
}
if (m_bAppendTimestamp) {
// From http://www.mirc.com/colors.html
// The Control+O key combination in mIRC inserts ascii character 15,
// which turns off all previous attributes, including color, bold,
// underline, and italics.
//
// \x02 bold
// \x03 mIRC-compatible color
// \x04 RRGGBB color
// \x0F normal/reset (turn off bold, colors, etc.)
// \x12 reverse (weechat)
// \x16 reverse (mirc, kvirc)
// \x1D italic
// \x1F underline
// Also see http://www.visualirc.net/tech-attrs.php
//
// Keep in sync with CIRCSocket::IcuExt__UCallback
if (CString::npos !=
sRet.find_first_of("\x02\x03\x04\x0F\x12\x16\x1D\x1F")) {
sRet += "\x0F";
}
sRet += " " + sTimestamp;
}
}
return sRet;
}
void CUser::BounceAllClients() {
for (CClient* pClient : m_vClients) {
pClient->BouncedOff();
}
m_vClients.clear();
}
void CUser::UserConnected(CClient* pClient) {
if (!MultiClients()) {
BounceAllClients();
}
pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() + " :" +
t_s("Welcome to ZNC"));
m_vClients.push_back(pClient);
}
void CUser::UserDisconnected(CClient* pClient) {
auto it = std::find(m_vClients.begin(), m_vClients.end(), pClient);
if (it != m_vClients.end()) {
m_vClients.erase(it);
}
}
void CUser::CloneNetworks(const CUser& User) {
const vector<CIRCNetwork*>& vNetworks = User.GetNetworks();
for (CIRCNetwork* pUserNetwork : vNetworks) {
CIRCNetwork* pNetwork = FindNetwork(pUserNetwork->GetName());
if (pNetwork) {
pNetwork->Clone(*pUserNetwork);
} else {
new CIRCNetwork(this, *pUserNetwork);
}
}
set<CString> ssDeleteNetworks;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (!(User.FindNetwork(pNetwork->GetName()))) {
ssDeleteNetworks.insert(pNetwork->GetName());
}
}
for (const CString& sNetwork : ssDeleteNetworks) {
// The following will move all the clients to the user.
// So the clients are not disconnected. The client could
// have requested the rehash. Then when we do
// client->PutStatus("Rehashing succeeded!") we would
// crash if there was no client anymore.
const vector<CClient*>& vClients = FindNetwork(sNetwork)->GetClients();
while (vClients.begin() != vClients.end()) {
CClient* pClient = vClients.front();
// This line will remove pClient from vClients,
// because it's a reference to the internal Network's vector.
pClient->SetNetwork(nullptr);
}
DeleteNetwork(sNetwork);
}
}
bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks) {
sErrorRet.clear();
if (!User.IsValid(sErrorRet, true)) {
return false;
}
// user names can only specified for the constructor, changing it later
// on breaks too much stuff (e.g. lots of paths depend on the user name)
if (GetUserName() != User.GetUserName()) {
DEBUG("Ignoring username in CUser::Clone(), old username ["
<< GetUserName() << "]; New username [" << User.GetUserName()
<< "]");
}
if (!User.GetPass().empty()) {
SetPass(User.GetPass(), User.GetPassHashType(), User.GetPassSalt());
}
SetNick(User.GetNick(false));
SetAltNick(User.GetAltNick(false));
SetIdent(User.GetIdent(false));
SetRealName(User.GetRealName());
SetStatusPrefix(User.GetStatusPrefix());
SetBindHost(User.GetBindHost());
SetDCCBindHost(User.GetDCCBindHost());
SetQuitMsg(User.GetQuitMsg());
SetSkinName(User.GetSkinName());
SetDefaultChanModes(User.GetDefaultChanModes());
SetChanBufferSize(User.GetChanBufferSize(), true);
SetQueryBufferSize(User.GetQueryBufferSize(), true);
SetJoinTries(User.JoinTries());
SetMaxNetworks(User.MaxNetworks());
SetMaxQueryBuffers(User.MaxQueryBuffers());
SetMaxJoins(User.MaxJoins());
SetNoTrafficTimeout(User.GetNoTrafficTimeout());
SetClientEncoding(User.GetClientEncoding());
SetLanguage(User.GetLanguage());
// Allowed Hosts
m_ssAllowedHosts.clear();
const set<CString>& ssHosts = User.GetAllowedHosts();
for (const CString& sHost : ssHosts) {
AddAllowedHost(sHost);
}
for (CClient* pSock : m_vClients) {
if (!IsHostAllowed(pSock->GetRemoteIP())) {
pSock->PutStatusNotice(
t_s("You are being disconnected because your IP is no longer "
"allowed to connect to this user"));
pSock->Close();
}
}
// !Allowed Hosts
// Networks
if (bCloneNetworks) {
CloneNetworks(User);
}
// !Networks
// CTCP Replies
m_mssCTCPReplies.clear();
const MCString& msReplies = User.GetCTCPReplies();
for (const auto& it : msReplies) {
AddCTCPReply(it.first, it.second);
}
// !CTCP Replies
// Flags
SetAutoClearChanBuffer(User.AutoClearChanBuffer());
SetAutoClearQueryBuffer(User.AutoClearQueryBuffer());
SetMultiClients(User.MultiClients());
SetDenyLoadMod(User.DenyLoadMod());
SetAdmin(User.IsAdmin());
SetDenySetBindHost(User.DenySetBindHost());
SetAuthOnlyViaModule(User.AuthOnlyViaModule());
SetTimestampAppend(User.GetTimestampAppend());
SetTimestampPrepend(User.GetTimestampPrepend());
SetTimestampFormat(User.GetTimestampFormat());
SetTimezone(User.GetTimezone());
// !Flags
// Modules
set<CString> ssUnloadMods;
CModules& vCurMods = GetModules();
const CModules& vNewMods = User.GetModules();
for (CModule* pNewMod : vNewMods) {
CString sModRet;
CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName());
if (!pCurMod) {
vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
CModInfo::UserModule, this, nullptr, sModRet);
} else if (pNewMod->GetArgs() != pCurMod->GetArgs()) {
vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(),
this, nullptr, sModRet);
}
}
for (CModule* pCurMod : vCurMods) {
CModule* pNewMod = vNewMods.FindModule(pCurMod->GetModName());
if (!pNewMod) {
ssUnloadMods.insert(pCurMod->GetModName());
}
}
for (const CString& sMod : ssUnloadMods) {
vCurMods.UnloadModule(sMod);
}
// !Modules
return true;
}
const set<CString>& CUser::GetAllowedHosts() const { return m_ssAllowedHosts; }
bool CUser::AddAllowedHost(const CString& sHostMask) {
if (sHostMask.empty() ||
m_ssAllowedHosts.find(sHostMask) != m_ssAllowedHosts.end()) {
return false;
}
m_ssAllowedHosts.insert(sHostMask);
return true;
}
bool CUser::RemAllowedHost(const CString& sHostMask) {
return m_ssAllowedHosts.erase(sHostMask) > 0;
}
void CUser::ClearAllowedHosts() { m_ssAllowedHosts.clear(); }
bool CUser::IsHostAllowed(const CString& sHost) const {
if (m_ssAllowedHosts.empty()) {
return true;
}
for (const CString& sAllowedHost : m_ssAllowedHosts) {
if (CUtils::CheckCIDR(sHost, sAllowedHost)) {
return true;
}
}
return false;
}
const CString& CUser::GetTimestampFormat() const { return m_sTimestampFormat; }
bool CUser::GetTimestampAppend() const { return m_bAppendTimestamp; }
bool CUser::GetTimestampPrepend() const { return m_bPrependTimestamp; }
bool CUser::IsValidUserName(const CString& sUserName) {
// /^[a-zA-Z][a-zA-Z@._\-]*$/
const char* p = sUserName.c_str();
if (sUserName.empty()) {
return false;
}
if ((*p < 'a' || *p > 'z') && (*p < 'A' || *p > 'Z')) {
return false;
}
while (*p) {
if (*p != '@' && *p != '.' && *p != '-' && *p != '_' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
bool CUser::IsValid(CString& sErrMsg, bool bSkipPass) const {
sErrMsg.clear();
if (!bSkipPass && m_sPass.empty()) {
sErrMsg = t_s("Password is empty");
return false;
}
if (m_sUserName.empty()) {
sErrMsg = t_s("Username is empty");
return false;
}
if (!CUser::IsValidUserName(m_sUserName)) {
sErrMsg = t_s("Username is invalid");
return false;
}
return true;
}
CConfig CUser::ToConfig() const {
CConfig config;
CConfig passConfig;
CString sHash;
switch (m_eHashType) {
case HASH_NONE:
sHash = "Plain";
break;
case HASH_MD5:
sHash = "MD5";
break;
case HASH_SHA256:
sHash = "SHA256";
break;
}
passConfig.AddKeyValuePair("Salt", m_sPassSalt);
passConfig.AddKeyValuePair("Method", sHash);
passConfig.AddKeyValuePair("Hash", GetPass());
config.AddSubConfig("Pass", "password", passConfig);
config.AddKeyValuePair("Nick", GetNick());
config.AddKeyValuePair("AltNick", GetAltNick());
config.AddKeyValuePair("Ident", GetIdent());
config.AddKeyValuePair("RealName", GetRealName());
config.AddKeyValuePair("BindHost", GetBindHost());
config.AddKeyValuePair("DCCBindHost", GetDCCBindHost());
config.AddKeyValuePair("QuitMsg", GetQuitMsg());
if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
config.AddKeyValuePair("StatusPrefix", GetStatusPrefix());
config.AddKeyValuePair("Skin", GetSkinName());
config.AddKeyValuePair("ChanModes", GetDefaultChanModes());
config.AddKeyValuePair("ChanBufferSize", CString(GetChanBufferSize()));
config.AddKeyValuePair("QueryBufferSize", CString(GetQueryBufferSize()));
config.AddKeyValuePair("AutoClearChanBuffer",
CString(AutoClearChanBuffer()));
config.AddKeyValuePair("AutoClearQueryBuffer",
CString(AutoClearQueryBuffer()));
config.AddKeyValuePair("MultiClients", CString(MultiClients()));
config.AddKeyValuePair("DenyLoadMod", CString(DenyLoadMod()));
config.AddKeyValuePair("Admin", CString(IsAdmin()));
config.AddKeyValuePair("DenySetBindHost", CString(DenySetBindHost()));
config.AddKeyValuePair("TimestampFormat", GetTimestampFormat());
config.AddKeyValuePair("AppendTimestamp", CString(GetTimestampAppend()));
config.AddKeyValuePair("PrependTimestamp", CString(GetTimestampPrepend()));
config.AddKeyValuePair("AuthOnlyViaModule", CString(AuthOnlyViaModule()));
config.AddKeyValuePair("Timezone", m_sTimezone);
config.AddKeyValuePair("JoinTries", CString(m_uMaxJoinTries));
config.AddKeyValuePair("MaxNetworks", CString(m_uMaxNetworks));
config.AddKeyValuePair("MaxQueryBuffers", CString(m_uMaxQueryBuffers));
config.AddKeyValuePair("MaxJoins", CString(m_uMaxJoins));
config.AddKeyValuePair("ClientEncoding", GetClientEncoding());
config.AddKeyValuePair("Language", GetLanguage());
config.AddKeyValuePair("NoTrafficTimeout", CString(GetNoTrafficTimeout()));
// Allow Hosts
if (!m_ssAllowedHosts.empty()) {
for (const CString& sHost : m_ssAllowedHosts) {
config.AddKeyValuePair("Allow", sHost);
}
}
// CTCP Replies
if (!m_mssCTCPReplies.empty()) {
for (const auto& itb : m_mssCTCPReplies) {
config.AddKeyValuePair("CTCPReply",
itb.first.AsUpper() + " " + itb.second);
}
}
// Modules
const CModules& Mods = GetModules();
if (!Mods.empty()) {
for (CModule* pMod : Mods) {
CString sArgs = pMod->GetArgs();
if (!sArgs.empty()) {
sArgs = " " + sArgs;
}
config.AddKeyValuePair("LoadModule", pMod->GetModName() + sArgs);
}
}
// Networks
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
config.AddSubConfig("Network", pNetwork->GetName(),
pNetwork->ToConfig());
}
return config;
}
bool CUser::CheckPass(const CString& sPass) const {
if(AuthOnlyViaModule() || CZNC::Get().GetAuthOnlyViaModule()) {
return false;
}
switch (m_eHashType) {
case HASH_MD5:
return m_sPass.Equals(CUtils::SaltedMD5Hash(sPass, m_sPassSalt));
case HASH_SHA256:
return m_sPass.Equals(CUtils::SaltedSHA256Hash(sPass, m_sPassSalt));
case HASH_NONE:
default:
return (sPass == m_sPass);
}
}
/*CClient* CUser::GetClient() {
// Todo: optimize this by saving a pointer to the sock
CSockManager& Manager = CZNC::Get().GetManager();
CString sSockName = "USR::" + m_sUserName;
for (unsigned int a = 0; a < Manager.size(); a++) {
Csock* pSock = Manager[a];
if (pSock->GetSockName().Equals(sSockName)) {
if (!pSock->IsClosed()) {
return (CClient*) pSock;
}
}
}
return (CClient*) CZNC::Get().GetManager().FindSockByName(sSockName);
}*/
CString CUser::GetLocalDCCIP() const {
if (!GetDCCBindHost().empty()) return GetDCCBindHost();
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
CIRCSock* pIRCSock = pNetwork->GetIRCSock();
if (pIRCSock) {
return pIRCSock->GetLocalIP();
}
}
if (!GetAllClients().empty()) {
return GetAllClients()[0]->GetLocalIP();
}
return "";
}
bool CUser::PutUser(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutClient(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutAllUser(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
PutUser(sLine, pClient, pSkipClient);
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (pNetwork->PutUser(sLine, pClient, pSkipClient)) {
return true;
}
}
return (pClient == nullptr);
}
bool CUser::PutStatus(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
vector<CClient*> vClients = GetAllClients();
for (CClient* pEachClient : vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutStatus(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutStatusNotice(const CString& sLine, CClient* pClient,
CClient* pSkipClient) {
vector<CClient*> vClients = GetAllClients();
for (CClient* pEachClient : vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutStatusNotice(sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutModule(const CString& sModule, const CString& sLine,
CClient* pClient, CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutModule(sModule, sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
bool CUser::PutModNotice(const CString& sModule, const CString& sLine,
CClient* pClient, CClient* pSkipClient) {
for (CClient* pEachClient : m_vClients) {
if ((!pClient || pClient == pEachClient) &&
pSkipClient != pEachClient) {
pEachClient->PutModNotice(sModule, sLine);
if (pClient) {
return true;
}
}
}
return (pClient == nullptr);
}
CString CUser::MakeCleanUserName(const CString& sUserName) {
return sUserName.Token(0, false, "@").Replace_n(".", "");
}
bool CUser::IsUserAttached() const {
if (!m_vClients.empty()) {
return true;
}
for (const CIRCNetwork* pNetwork : m_vIRCNetworks) {
if (pNetwork->IsUserAttached()) {
return true;
}
}
return false;
}
bool CUser::LoadModule(const CString& sModName, const CString& sArgs,
const CString& sNotice, CString& sError) {
bool bModRet = true;
CString sModRet;
CModInfo ModInfo;
if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sModName, sModRet)) {
sError = t_f("Unable to find modinfo {1}: {2}")(sModName, sModRet);
return false;
}
CUtils::PrintAction(sNotice);
if (!ModInfo.SupportsType(CModInfo::UserModule) &&
ModInfo.SupportsType(CModInfo::NetworkModule)) {
CUtils::PrintMessage(
"NOTICE: Module [" + sModName +
"] is a network module, loading module for all networks in user.");
// Do they have old NV?
CFile fNVFile =
CFile(GetUserPath() + "/moddata/" + sModName + "/.registry");
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
// Check whether the network already has this module loaded (#954)
if (pNetwork->GetModules().FindModule(sModName)) {
continue;
}
if (fNVFile.Exists()) {
CString sNetworkModPath =
pNetwork->GetNetworkPath() + "/moddata/" + sModName;
if (!CFile::Exists(sNetworkModPath)) {
CDir::MakeDir(sNetworkModPath);
}
fNVFile.Copy(sNetworkModPath + "/.registry");
}
bModRet = pNetwork->GetModules().LoadModule(
sModName, sArgs, CModInfo::NetworkModule, this, pNetwork,
sModRet);
if (!bModRet) {
break;
}
}
} else {
bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule,
this, nullptr, sModRet);
}
if (!bModRet) {
sError = sModRet;
}
return bModRet;
}
// Setters
void CUser::SetNick(const CString& s) { m_sNick = s; }
void CUser::SetAltNick(const CString& s) { m_sAltNick = s; }
void CUser::SetIdent(const CString& s) { m_sIdent = s; }
void CUser::SetRealName(const CString& s) { m_sRealName = s; }
void CUser::SetBindHost(const CString& s) { m_sBindHost = s; }
void CUser::SetDCCBindHost(const CString& s) { m_sDCCBindHost = s; }
void CUser::SetPass(const CString& s, eHashType eHash, const CString& sSalt) {
m_sPass = s;
m_eHashType = eHash;
m_sPassSalt = sSalt;
}
void CUser::SetMultiClients(bool b) { m_bMultiClients = b; }
void CUser::SetDenyLoadMod(bool b) { m_bDenyLoadMod = b; }
void CUser::SetAdmin(bool b) { m_bAdmin = b; }
void CUser::SetDenySetBindHost(bool b) { m_bDenySetBindHost = b; }
void CUser::SetDefaultChanModes(const CString& s) { m_sDefaultChanModes = s; }
void CUser::SetClientEncoding(const CString& s) {
m_sClientEncoding = s;
for (CClient* pClient : GetAllClients()) {
pClient->SetEncoding(s);
}
}
void CUser::SetQuitMsg(const CString& s) { m_sQuitMsg = s; }
void CUser::SetAutoClearChanBuffer(bool b) {
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CChan* pChan : pNetwork->GetChans()) {
pChan->InheritAutoClearChanBuffer(b);
}
}
m_bAutoClearChanBuffer = b;
}
void CUser::SetAutoClearQueryBuffer(bool b) { m_bAutoClearQueryBuffer = b; }
bool CUser::SetBufferCount(unsigned int u, bool bForce) {
return SetChanBufferSize(u, bForce);
}
bool CUser::SetChanBufferSize(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) return false;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CChan* pChan : pNetwork->GetChans()) {
pChan->InheritBufferCount(u, bForce);
}
}
m_uChanBufferSize = u;
return true;
}
bool CUser::SetQueryBufferSize(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) return false;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CQuery* pQuery : pNetwork->GetQueries()) {
pQuery->SetBufferCount(u, bForce);
}
}
m_uQueryBufferSize = u;
return true;
}
bool CUser::AddCTCPReply(const CString& sCTCP, const CString& sReply) {
// Reject CTCP requests containing spaces
if (sCTCP.find_first_of(' ') != CString::npos) {
return false;
}
// Reject empty CTCP requests
if (sCTCP.empty()) {
return false;
}
m_mssCTCPReplies[sCTCP.AsUpper()] = sReply;
return true;
}
bool CUser::DelCTCPReply(const CString& sCTCP) {
return m_mssCTCPReplies.erase(sCTCP.AsUpper()) > 0;
}
bool CUser::SetStatusPrefix(const CString& s) {
if ((!s.empty()) && (s.length() < 6) && (!s.Contains(" "))) {
m_sStatusPrefix = (s.empty()) ? "*" : s;
return true;
}
return false;
}
bool CUser::SetLanguage(const CString& s) {
// They look like ru-RU
for (char c : s) {
if (isalpha(c) || c == '-' || c == '_') {
} else {
return false;
}
}
m_sLanguage = s;
// 1.7.0 accidentally used _ instead of -, which made language
// non-selectable. But it's possible that someone put _ to znc.conf
// manually.
// TODO: cleanup _ some time later.
m_sLanguage.Replace("_", "-");
return true;
}
// !Setters
// Getters
vector<CClient*> CUser::GetAllClients() const {
vector<CClient*> vClients;
for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
for (CClient* pClient : pNetwork->GetClients()) {
vClients.push_back(pClient);
}
}
for (CClient* pClient : m_vClients) {
vClients.push_back(pClient);
}
return vClients;
}
const CString& CUser::GetUserName() const { return m_sUserName; }
const CString& CUser::GetCleanUserName() const { return m_sCleanUserName; }
const CString& CUser::GetNick(bool bAllowDefault) const {
return (bAllowDefault && m_sNick.empty()) ? GetCleanUserName() : m_sNick;
}
const CString& CUser::GetAltNick(bool bAllowDefault) const {
return (bAllowDefault && m_sAltNick.empty()) ? GetCleanUserName()
: m_sAltNick;
}
const CString& CUser::GetIdent(bool bAllowDefault) const {
return (bAllowDefault && m_sIdent.empty()) ? GetCleanUserName() : m_sIdent;
}
CString CUser::GetRealName() const {
// Not include version number via GetTag() because of
// https://github.com/znc/znc/issues/818#issuecomment-70402820
return (!m_sRealName.Trim_n().empty()) ? m_sRealName
: "ZNC - https://znc.in";
}
const CString& CUser::GetBindHost() const { return m_sBindHost; }
const CString& CUser::GetDCCBindHost() const { return m_sDCCBindHost; }
const CString& CUser::GetPass() const { return m_sPass; }
CUser::eHashType CUser::GetPassHashType() const { return m_eHashType; }
const CString& CUser::GetPassSalt() const { return m_sPassSalt; }
bool CUser::DenyLoadMod() const { return m_bDenyLoadMod; }
bool CUser::IsAdmin() const { return m_bAdmin; }
bool CUser::DenySetBindHost() const { return m_bDenySetBindHost; }
bool CUser::MultiClients() const { return m_bMultiClients; }
bool CUser::AuthOnlyViaModule() const { return m_bAuthOnlyViaModule; }
const CString& CUser::GetStatusPrefix() const { return m_sStatusPrefix; }
const CString& CUser::GetDefaultChanModes() const {
return m_sDefaultChanModes;
}
const CString& CUser::GetClientEncoding() const { return m_sClientEncoding; }
bool CUser::HasSpaceForNewNetwork() const {
return GetNetworks().size() < MaxNetworks();
}
CString CUser::GetQuitMsg() const {
return (!m_sQuitMsg.Trim_n().empty()) ? m_sQuitMsg : "%znc%";
}
const MCString& CUser::GetCTCPReplies() const { return m_mssCTCPReplies; }
unsigned int CUser::GetBufferCount() const { return GetChanBufferSize(); }
unsigned int CUser::GetChanBufferSize() const { return m_uChanBufferSize; }
unsigned int CUser::GetQueryBufferSize() const { return m_uQueryBufferSize; }
bool CUser::AutoClearChanBuffer() const { return m_bAutoClearChanBuffer; }
bool CUser::AutoClearQueryBuffer() const { return m_bAutoClearQueryBuffer; }
// CString CUser::GetSkinName() const { return (!m_sSkinName.empty()) ?
// m_sSkinName : CZNC::Get().GetSkinName(); }
CString CUser::GetSkinName() const { return m_sSkinName; }
CString CUser::GetLanguage() const { return m_sLanguage; }
const CString& CUser::GetUserPath() const {
if (!CFile::Exists(m_sUserPath)) {
CDir::MakeDir(m_sUserPath);
}
return m_sUserPath;
}
// !Getters
unsigned long long CUser::BytesRead() const {
unsigned long long uBytes = m_uBytesRead;
for (const CIRCNetwork* pNetwork : m_vIRCNetworks) {
uBytes += pNetwork->BytesRead();
}
return uBytes;
}
unsigned long long CUser::BytesWritten() const {
unsigned long long uBytes = m_uBytesWritten;
for (const CIRCNetwork* pNetwork : m_vIRCNetworks) {
uBytes += pNetwork->BytesWritten();
}
return uBytes;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1442_2 |
crossvul-cpp_data_bad_1442_3 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/znc.h>
#include <znc/FileUtils.h>
#include <znc/IRCSock.h>
#include <znc/Server.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Config.h>
#include <time.h>
#include <tuple>
#include <algorithm>
using std::endl;
using std::cout;
using std::map;
using std::set;
using std::vector;
using std::list;
using std::tuple;
using std::make_tuple;
CZNC::CZNC()
: m_TimeStarted(time(nullptr)),
m_eConfigState(ECONFIG_NOTHING),
m_vpListeners(),
m_msUsers(),
m_msDelUsers(),
m_Manager(),
m_sCurPath(""),
m_sZNCPath(""),
m_sConfigFile(""),
m_sSkinName(""),
m_sStatusPrefix(""),
m_sPidFile(""),
m_sSSLCertFile(""),
m_sSSLKeyFile(""),
m_sSSLDHParamFile(""),
m_sSSLCiphers(""),
m_sSSLProtocols(""),
m_vsBindHosts(),
m_vsTrustedProxies(),
m_vsMotd(),
m_pLockFile(nullptr),
m_uiConnectDelay(5),
m_uiAnonIPLimit(10),
m_uiMaxBufferSize(500),
m_uDisabledSSLProtocols(Csock::EDP_SSL),
m_pModules(new CModules),
m_uBytesRead(0),
m_uBytesWritten(0),
m_lpConnectQueue(),
m_pConnectQueueTimer(nullptr),
m_uiConnectPaused(0),
m_uiForceEncoding(0),
m_sConnectThrottle(),
m_bProtectWebSessions(true),
m_bHideVersion(false),
m_bAuthOnlyViaModule(false),
m_Translation("znc"),
m_uiConfigWriteDelay(0),
m_pConfigTimer(nullptr) {
if (!InitCsocket()) {
CUtils::PrintError("Could not initialize Csocket!");
exit(-1);
}
m_sConnectThrottle.SetTTL(30000);
}
CZNC::~CZNC() {
m_pModules->UnloadAll();
for (const auto& it : m_msUsers) {
it.second->GetModules().UnloadAll();
const vector<CIRCNetwork*>& networks = it.second->GetNetworks();
for (CIRCNetwork* pNetwork : networks) {
pNetwork->GetModules().UnloadAll();
}
}
for (CListener* pListener : m_vpListeners) {
delete pListener;
}
for (const auto& it : m_msUsers) {
it.second->SetBeingDeleted(true);
}
m_pConnectQueueTimer = nullptr;
// This deletes m_pConnectQueueTimer
m_Manager.Cleanup();
DeleteUsers();
delete m_pModules;
delete m_pLockFile;
ShutdownCsocket();
DeletePidFile();
}
CString CZNC::GetVersion() {
return CString(VERSION_STR) + CString(ZNC_VERSION_EXTRA);
}
CString CZNC::GetTag(bool bIncludeVersion, bool bHTML) {
if (!Get().m_bHideVersion) {
bIncludeVersion = true;
}
CString sAddress = bHTML ? "<a href=\"https://znc.in\">https://znc.in</a>"
: "https://znc.in";
if (!bIncludeVersion) {
return "ZNC - " + sAddress;
}
CString sVersion = GetVersion();
return "ZNC " + sVersion + " - " + sAddress;
}
CString CZNC::GetCompileOptionsString() {
// Build system doesn't affect ABI
return ZNC_COMPILE_OPTIONS_STRING + CString(
", build: "
#ifdef BUILD_WITH_CMAKE
"cmake"
#else
"autoconf"
#endif
);
}
CString CZNC::GetUptime() const {
time_t now = time(nullptr);
return CString::ToTimeStr(now - TimeStarted());
}
bool CZNC::OnBoot() {
bool bFail = false;
ALLMODULECALL(OnBoot(), &bFail);
if (bFail) return false;
return true;
}
bool CZNC::HandleUserDeletion() {
if (m_msDelUsers.empty()) return false;
for (const auto& it : m_msDelUsers) {
CUser* pUser = it.second;
pUser->SetBeingDeleted(true);
if (GetModules().OnDeleteUser(*pUser)) {
pUser->SetBeingDeleted(false);
continue;
}
m_msUsers.erase(pUser->GetUserName());
CWebSock::FinishUserSessions(*pUser);
delete pUser;
}
m_msDelUsers.clear();
return true;
}
class CConfigWriteTimer : public CCron {
public:
CConfigWriteTimer(int iSecs) : CCron() {
SetName("Config write timer");
Start(iSecs);
}
protected:
void RunJob() override {
CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_WRITE);
CZNC::Get().DisableConfigTimer();
}
};
void CZNC::Loop() {
while (true) {
CString sError;
ConfigState eState = GetConfigState();
switch (eState) {
case ECONFIG_NEED_REHASH:
SetConfigState(ECONFIG_NOTHING);
if (RehashConfig(sError)) {
Broadcast("Rehashing succeeded", true);
} else {
Broadcast("Rehashing failed: " + sError, true);
Broadcast("ZNC is in some possibly inconsistent state!",
true);
}
break;
case ECONFIG_DELAYED_WRITE:
SetConfigState(ECONFIG_NOTHING);
if (GetConfigWriteDelay() > 0) {
if (m_pConfigTimer == nullptr) {
m_pConfigTimer = new CConfigWriteTimer(GetConfigWriteDelay());
GetManager().AddCron(m_pConfigTimer);
}
break;
}
/* Fall through */
case ECONFIG_NEED_WRITE:
case ECONFIG_NEED_VERBOSE_WRITE:
SetConfigState(ECONFIG_NOTHING);
// stop pending configuration timer
DisableConfigTimer();
if (!WriteConfig()) {
Broadcast("Writing the config file failed", true);
} else if (eState == ECONFIG_NEED_VERBOSE_WRITE) {
Broadcast("Writing the config succeeded", true);
}
break;
case ECONFIG_NOTHING:
break;
case ECONFIG_NEED_QUIT:
return;
}
// Check for users that need to be deleted
if (HandleUserDeletion()) {
// Also remove those user(s) from the config file
WriteConfig();
}
// Csocket wants micro seconds
// 100 msec to 5 min
m_Manager.DynamicSelectLoop(100 * 1000, 5 * 60 * 1000 * 1000);
}
}
CFile* CZNC::InitPidFile() {
if (!m_sPidFile.empty()) {
CString sFile;
// absolute path or relative to the data dir?
if (m_sPidFile[0] != '/')
sFile = GetZNCPath() + "/" + m_sPidFile;
else
sFile = m_sPidFile;
return new CFile(sFile);
}
return nullptr;
}
bool CZNC::WritePidFile(int iPid) {
CFile* File = InitPidFile();
if (File == nullptr) return false;
CUtils::PrintAction("Writing pid file [" + File->GetLongName() + "]");
bool bRet = false;
if (File->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
File->Write(CString(iPid) + "\n");
File->Close();
bRet = true;
}
delete File;
CUtils::PrintStatus(bRet);
return bRet;
}
bool CZNC::DeletePidFile() {
CFile* File = InitPidFile();
if (File == nullptr) return false;
CUtils::PrintAction("Deleting pid file [" + File->GetLongName() + "]");
bool bRet = File->Delete();
delete File;
CUtils::PrintStatus(bRet);
return bRet;
}
bool CZNC::WritePemFile() {
#ifndef HAVE_LIBSSL
CUtils::PrintError("ZNC was not compiled with ssl support.");
return false;
#else
CString sPemFile = GetPemLocation();
CUtils::PrintAction("Writing Pem file [" + sPemFile + "]");
#ifndef _WIN32
int fd = creat(sPemFile.c_str(), 0600);
if (fd == -1) {
CUtils::PrintStatus(false, "Unable to open");
return false;
}
FILE* f = fdopen(fd, "w");
#else
FILE* f = fopen(sPemFile.c_str(), "w");
#endif
if (!f) {
CUtils::PrintStatus(false, "Unable to open");
return false;
}
CUtils::GenerateCert(f, "");
fclose(f);
CUtils::PrintStatus(true);
return true;
#endif
}
void CZNC::DeleteUsers() {
for (const auto& it : m_msUsers) {
it.second->SetBeingDeleted(true);
delete it.second;
}
m_msUsers.clear();
DisableConnectQueue();
}
bool CZNC::IsHostAllowed(const CString& sHostMask) const {
for (const auto& it : m_msUsers) {
if (it.second->IsHostAllowed(sHostMask)) {
return true;
}
}
return false;
}
bool CZNC::AllowConnectionFrom(const CString& sIP) const {
if (m_uiAnonIPLimit == 0) return true;
return (GetManager().GetAnonConnectionCount(sIP) < m_uiAnonIPLimit);
}
void CZNC::InitDirs(const CString& sArgvPath, const CString& sDataDir) {
// If the bin was not ran from the current directory, we need to add that
// dir onto our cwd
CString::size_type uPos = sArgvPath.rfind('/');
if (uPos == CString::npos)
m_sCurPath = "./";
else
m_sCurPath = CDir::ChangeDir("./", sArgvPath.Left(uPos), "");
// Try to set the user's home dir, default to binpath on failure
CFile::InitHomePath(m_sCurPath);
if (sDataDir.empty()) {
m_sZNCPath = CFile::GetHomePath() + "/.znc";
} else {
m_sZNCPath = sDataDir;
}
m_sSSLCertFile = m_sZNCPath + "/znc.pem";
}
CString CZNC::GetConfPath(bool bAllowMkDir) const {
CString sConfPath = m_sZNCPath + "/configs";
if (bAllowMkDir && !CFile::Exists(sConfPath)) {
CDir::MakeDir(sConfPath);
}
return sConfPath;
}
CString CZNC::GetUserPath() const {
CString sUserPath = m_sZNCPath + "/users";
if (!CFile::Exists(sUserPath)) {
CDir::MakeDir(sUserPath);
}
return sUserPath;
}
CString CZNC::GetModPath() const {
CString sModPath = m_sZNCPath + "/modules";
return sModPath;
}
const CString& CZNC::GetCurPath() const {
if (!CFile::Exists(m_sCurPath)) {
CDir::MakeDir(m_sCurPath);
}
return m_sCurPath;
}
const CString& CZNC::GetHomePath() const { return CFile::GetHomePath(); }
const CString& CZNC::GetZNCPath() const {
if (!CFile::Exists(m_sZNCPath)) {
CDir::MakeDir(m_sZNCPath);
}
return m_sZNCPath;
}
CString CZNC::GetPemLocation() const {
return CDir::ChangeDir("", m_sSSLCertFile);
}
CString CZNC::GetKeyLocation() const {
return CDir::ChangeDir(
"", m_sSSLKeyFile.empty() ? m_sSSLCertFile : m_sSSLKeyFile);
}
CString CZNC::GetDHParamLocation() const {
return CDir::ChangeDir(
"", m_sSSLDHParamFile.empty() ? m_sSSLCertFile : m_sSSLDHParamFile);
}
CString CZNC::ExpandConfigPath(const CString& sConfigFile, bool bAllowMkDir) {
CString sRetPath;
if (sConfigFile.empty()) {
sRetPath = GetConfPath(bAllowMkDir) + "/znc.conf";
} else {
if (sConfigFile.StartsWith("./") || sConfigFile.StartsWith("../")) {
sRetPath = GetCurPath() + "/" + sConfigFile;
} else if (!sConfigFile.StartsWith("/")) {
sRetPath = GetConfPath(bAllowMkDir) + "/" + sConfigFile;
} else {
sRetPath = sConfigFile;
}
}
return sRetPath;
}
bool CZNC::WriteConfig() {
if (GetConfigFile().empty()) {
DEBUG("Config file name is empty?!");
return false;
}
// We first write to a temporary file and then move it to the right place
CFile* pFile = new CFile(GetConfigFile() + "~");
if (!pFile->Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) {
DEBUG("Could not write config to " + GetConfigFile() + "~: " +
CString(strerror(errno)));
delete pFile;
return false;
}
// We have to "transfer" our lock on the config to the new file.
// The old file (= inode) is going away and thus a lock on it would be
// useless. These lock should always succeed (races, anyone?).
if (!pFile->TryExLock()) {
DEBUG("Error while locking the new config file, errno says: " +
CString(strerror(errno)));
pFile->Delete();
delete pFile;
return false;
}
pFile->Write(MakeConfigHeader() + "\n");
CConfig config;
config.AddKeyValuePair("AnonIPLimit", CString(m_uiAnonIPLimit));
config.AddKeyValuePair("MaxBufferSize", CString(m_uiMaxBufferSize));
config.AddKeyValuePair("SSLCertFile", CString(GetPemLocation()));
config.AddKeyValuePair("SSLKeyFile", CString(GetKeyLocation()));
config.AddKeyValuePair("SSLDHParamFile", CString(GetDHParamLocation()));
config.AddKeyValuePair("ProtectWebSessions",
CString(m_bProtectWebSessions));
config.AddKeyValuePair("HideVersion", CString(m_bHideVersion));
config.AddKeyValuePair("AuthOnlyViaModule", CString(m_bAuthOnlyViaModule));
config.AddKeyValuePair("Version", CString(VERSION_STR));
config.AddKeyValuePair("ConfigWriteDelay", CString(m_uiConfigWriteDelay));
unsigned int l = 0;
for (CListener* pListener : m_vpListeners) {
CConfig listenerConfig;
listenerConfig.AddKeyValuePair("Host", pListener->GetBindHost());
listenerConfig.AddKeyValuePair("URIPrefix",
pListener->GetURIPrefix() + "/");
listenerConfig.AddKeyValuePair("Port", CString(pListener->GetPort()));
listenerConfig.AddKeyValuePair(
"IPv4", CString(pListener->GetAddrType() != ADDR_IPV6ONLY));
listenerConfig.AddKeyValuePair(
"IPv6", CString(pListener->GetAddrType() != ADDR_IPV4ONLY));
listenerConfig.AddKeyValuePair("SSL", CString(pListener->IsSSL()));
listenerConfig.AddKeyValuePair(
"AllowIRC",
CString(pListener->GetAcceptType() != CListener::ACCEPT_HTTP));
listenerConfig.AddKeyValuePair(
"AllowWeb",
CString(pListener->GetAcceptType() != CListener::ACCEPT_IRC));
config.AddSubConfig("Listener", "listener" + CString(l++),
listenerConfig);
}
config.AddKeyValuePair("ConnectDelay", CString(m_uiConnectDelay));
config.AddKeyValuePair("ServerThrottle",
CString(m_sConnectThrottle.GetTTL() / 1000));
if (!m_sPidFile.empty()) {
config.AddKeyValuePair("PidFile", m_sPidFile.FirstLine());
}
if (!m_sSkinName.empty()) {
config.AddKeyValuePair("Skin", m_sSkinName.FirstLine());
}
if (!m_sStatusPrefix.empty()) {
config.AddKeyValuePair("StatusPrefix", m_sStatusPrefix.FirstLine());
}
if (!m_sSSLCiphers.empty()) {
config.AddKeyValuePair("SSLCiphers", CString(m_sSSLCiphers));
}
if (!m_sSSLProtocols.empty()) {
config.AddKeyValuePair("SSLProtocols", m_sSSLProtocols);
}
for (const CString& sLine : m_vsMotd) {
config.AddKeyValuePair("Motd", sLine.FirstLine());
}
for (const CString& sProxy : m_vsTrustedProxies) {
config.AddKeyValuePair("TrustedProxy", sProxy.FirstLine());
}
CModules& Mods = GetModules();
for (const CModule* pMod : Mods) {
CString sName = pMod->GetModName();
CString sArgs = pMod->GetArgs();
if (!sArgs.empty()) {
sArgs = " " + sArgs.FirstLine();
}
config.AddKeyValuePair("LoadModule", sName.FirstLine() + sArgs);
}
for (const auto& it : m_msUsers) {
CString sErr;
if (!it.second->IsValid(sErr)) {
DEBUG("** Error writing config for user [" << it.first << "] ["
<< sErr << "]");
continue;
}
config.AddSubConfig("User", it.second->GetUserName(),
it.second->ToConfig());
}
config.Write(*pFile);
// If Sync() fails... well, let's hope nothing important breaks..
pFile->Sync();
if (pFile->HadError()) {
DEBUG("Error while writing the config, errno says: " +
CString(strerror(errno)));
pFile->Delete();
delete pFile;
return false;
}
// We wrote to a temporary name, move it to the right place
if (!pFile->Move(GetConfigFile(), true)) {
DEBUG(
"Error while replacing the config file with a new version, errno "
"says "
<< strerror(errno));
pFile->Delete();
delete pFile;
return false;
}
// Everything went fine, just need to update the saved path.
pFile->SetFileName(GetConfigFile());
// Make sure the lock is kept alive as long as we need it.
delete m_pLockFile;
m_pLockFile = pFile;
return true;
}
CString CZNC::MakeConfigHeader() {
return "// WARNING\n"
"//\n"
"// Do NOT edit this file while ZNC is running!\n"
"// Use webadmin or *controlpanel instead.\n"
"//\n"
"// Altering this file by hand will forfeit all support.\n"
"//\n"
"// But if you feel risky, you might want to read help on /znc "
"saveconfig and /znc rehash.\n"
"// Also check https://wiki.znc.in/Configuration\n";
}
bool CZNC::WriteNewConfig(const CString& sConfigFile) {
CString sAnswer, sUser, sNetwork;
VCString vsLines;
vsLines.push_back(MakeConfigHeader());
vsLines.push_back("Version = " + CString(VERSION_STR));
m_sConfigFile = ExpandConfigPath(sConfigFile);
if (CFile::Exists(m_sConfigFile)) {
CUtils::PrintStatus(
false, "WARNING: config [" + m_sConfigFile + "] already exists.");
}
CUtils::PrintMessage("");
CUtils::PrintMessage("-- Global settings --");
CUtils::PrintMessage("");
// Listen
#ifdef HAVE_IPV6
bool b6 = true;
#else
bool b6 = false;
#endif
CString sListenHost;
CString sURIPrefix;
bool bListenSSL = false;
unsigned int uListenPort = 0;
bool bSuccess;
do {
bSuccess = true;
while (true) {
if (!CUtils::GetNumInput("Listen on port", uListenPort, 1025,
65534)) {
continue;
}
if (uListenPort == 6667) {
CUtils::PrintStatus(false,
"WARNING: Some web browsers reject port "
"6667. If you intend to");
CUtils::PrintStatus(false,
"use ZNC's web interface, you might want "
"to use another port.");
if (!CUtils::GetBoolInput("Proceed with port 6667 anyway?",
true)) {
continue;
}
}
break;
}
#ifdef HAVE_LIBSSL
bListenSSL = CUtils::GetBoolInput("Listen using SSL", bListenSSL);
#endif
#ifdef HAVE_IPV6
b6 = CUtils::GetBoolInput("Listen using both IPv4 and IPv6", b6);
#endif
// Don't ask for listen host, it may be configured later if needed.
CUtils::PrintAction("Verifying the listener");
CListener* pListener = new CListener(
(unsigned short int)uListenPort, sListenHost, sURIPrefix,
bListenSSL, b6 ? ADDR_ALL : ADDR_IPV4ONLY, CListener::ACCEPT_ALL);
if (!pListener->Listen()) {
CUtils::PrintStatus(false, FormatBindError());
bSuccess = false;
} else
CUtils::PrintStatus(true);
delete pListener;
} while (!bSuccess);
#ifdef HAVE_LIBSSL
CString sPemFile = GetPemLocation();
if (!CFile::Exists(sPemFile)) {
CUtils::PrintMessage("Unable to locate pem file: [" + sPemFile +
"], creating it");
WritePemFile();
}
#endif
vsLines.push_back("<Listener l>");
vsLines.push_back("\tPort = " + CString(uListenPort));
vsLines.push_back("\tIPv4 = true");
vsLines.push_back("\tIPv6 = " + CString(b6));
vsLines.push_back("\tSSL = " + CString(bListenSSL));
if (!sListenHost.empty()) {
vsLines.push_back("\tHost = " + sListenHost);
}
vsLines.push_back("</Listener>");
// !Listen
set<CModInfo> ssGlobalMods;
GetModules().GetDefaultMods(ssGlobalMods, CModInfo::GlobalModule);
vector<CString> vsGlobalModNames;
for (const CModInfo& Info : ssGlobalMods) {
vsGlobalModNames.push_back(Info.GetName());
vsLines.push_back("LoadModule = " + Info.GetName());
}
CUtils::PrintMessage(
"Enabled global modules [" +
CString(", ").Join(vsGlobalModNames.begin(), vsGlobalModNames.end()) +
"]");
// User
CUtils::PrintMessage("");
CUtils::PrintMessage("-- Admin user settings --");
CUtils::PrintMessage("");
vsLines.push_back("");
CString sNick;
do {
CUtils::GetInput("Username", sUser, "", "alphanumeric");
} while (!CUser::IsValidUserName(sUser));
vsLines.push_back("<User " + sUser + ">");
CString sSalt;
sAnswer = CUtils::GetSaltedHashPass(sSalt);
vsLines.push_back("\tPass = " + CUtils::sDefaultHash + "#" + sAnswer +
"#" + sSalt + "#");
vsLines.push_back("\tAdmin = true");
CUtils::GetInput("Nick", sNick, CUser::MakeCleanUserName(sUser));
vsLines.push_back("\tNick = " + sNick);
CUtils::GetInput("Alternate nick", sAnswer, sNick + "_");
if (!sAnswer.empty()) {
vsLines.push_back("\tAltNick = " + sAnswer);
}
CUtils::GetInput("Ident", sAnswer, sUser);
vsLines.push_back("\tIdent = " + sAnswer);
CUtils::GetInput("Real name", sAnswer, "", "optional");
if (!sAnswer.empty()) {
vsLines.push_back("\tRealName = " + sAnswer);
}
CUtils::GetInput("Bind host", sAnswer, "", "optional");
if (!sAnswer.empty()) {
vsLines.push_back("\tBindHost = " + sAnswer);
}
set<CModInfo> ssUserMods;
GetModules().GetDefaultMods(ssUserMods, CModInfo::UserModule);
vector<CString> vsUserModNames;
for (const CModInfo& Info : ssUserMods) {
vsUserModNames.push_back(Info.GetName());
vsLines.push_back("\tLoadModule = " + Info.GetName());
}
CUtils::PrintMessage(
"Enabled user modules [" +
CString(", ").Join(vsUserModNames.begin(), vsUserModNames.end()) + "]");
CUtils::PrintMessage("");
if (CUtils::GetBoolInput("Set up a network?", true)) {
vsLines.push_back("");
CUtils::PrintMessage("");
CUtils::PrintMessage("-- Network settings --");
CUtils::PrintMessage("");
do {
CUtils::GetInput("Name", sNetwork, "freenode");
} while (!CIRCNetwork::IsValidNetwork(sNetwork));
vsLines.push_back("\t<Network " + sNetwork + ">");
set<CModInfo> ssNetworkMods;
GetModules().GetDefaultMods(ssNetworkMods, CModInfo::NetworkModule);
vector<CString> vsNetworkModNames;
for (const CModInfo& Info : ssNetworkMods) {
vsNetworkModNames.push_back(Info.GetName());
vsLines.push_back("\t\tLoadModule = " + Info.GetName());
}
CString sHost, sPass, sHint;
bool bSSL = false;
unsigned int uServerPort = 0;
if (sNetwork.Equals("freenode")) {
sHost = "chat.freenode.net";
#ifdef HAVE_LIBSSL
bSSL = true;
#endif
} else {
sHint = "host only";
}
while (!CUtils::GetInput("Server host", sHost, sHost, sHint) ||
!CServer::IsValidHostName(sHost))
;
#ifdef HAVE_LIBSSL
bSSL = CUtils::GetBoolInput("Server uses SSL?", bSSL);
#endif
while (!CUtils::GetNumInput("Server port", uServerPort, 1, 65535,
bSSL ? 6697 : 6667))
;
CUtils::GetInput("Server password (probably empty)", sPass);
vsLines.push_back("\t\tServer = " + sHost + ((bSSL) ? " +" : " ") +
CString(uServerPort) + " " + sPass);
CString sChans;
if (CUtils::GetInput("Initial channels", sChans)) {
vsLines.push_back("");
VCString vsChans;
sChans.Replace(",", " ");
sChans.Replace(";", " ");
sChans.Split(" ", vsChans, false, "", "", true, true);
for (const CString& sChan : vsChans) {
vsLines.push_back("\t\t<Chan " + sChan + ">");
vsLines.push_back("\t\t</Chan>");
}
}
CUtils::PrintMessage("Enabled network modules [" +
CString(", ").Join(vsNetworkModNames.begin(),
vsNetworkModNames.end()) +
"]");
vsLines.push_back("\t</Network>");
}
vsLines.push_back("</User>");
CUtils::PrintMessage("");
// !User
CFile File;
bool bFileOK, bFileOpen = false;
do {
CUtils::PrintAction("Writing config [" + m_sConfigFile + "]");
bFileOK = true;
if (CFile::Exists(m_sConfigFile)) {
if (!File.TryExLock(m_sConfigFile)) {
CUtils::PrintStatus(false,
"ZNC is currently running on this config.");
bFileOK = false;
} else {
File.Close();
CUtils::PrintStatus(false, "This config already exists.");
if (CUtils::GetBoolInput(
"Are you sure you want to overwrite it?", false))
CUtils::PrintAction("Overwriting config [" + m_sConfigFile +
"]");
else
bFileOK = false;
}
}
if (bFileOK) {
File.SetFileName(m_sConfigFile);
if (File.Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) {
bFileOpen = true;
} else {
CUtils::PrintStatus(false, "Unable to open file");
bFileOK = false;
}
}
if (!bFileOK) {
while (!CUtils::GetInput("Please specify an alternate location",
m_sConfigFile, "",
"or \"stdout\" for displaying the config"))
;
if (m_sConfigFile.Equals("stdout"))
bFileOK = true;
else
m_sConfigFile = ExpandConfigPath(m_sConfigFile);
}
} while (!bFileOK);
if (!bFileOpen) {
CUtils::PrintMessage("");
CUtils::PrintMessage("Printing the new config to stdout:");
CUtils::PrintMessage("");
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
}
for (const CString& sLine : vsLines) {
if (bFileOpen) {
File.Write(sLine + "\n");
} else {
cout << sLine << endl;
}
}
if (bFileOpen) {
File.Close();
if (File.HadError())
CUtils::PrintStatus(false,
"There was an error while writing the config");
else
CUtils::PrintStatus(true);
} else {
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
}
if (File.HadError()) {
bFileOpen = false;
CUtils::PrintMessage("Printing the new config to stdout instead:");
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
for (const CString& sLine : vsLines) {
cout << sLine << endl;
}
cout << endl << "------------------------------------------------------"
"----------------------" << endl << endl;
}
const CString sProtocol(bListenSSL ? "https" : "http");
const CString sSSL(bListenSSL ? "+" : "");
CUtils::PrintMessage("");
CUtils::PrintMessage(
"To connect to this ZNC you need to connect to it as your IRC server",
true);
CUtils::PrintMessage(
"using the port that you supplied. You have to supply your login info",
true);
CUtils::PrintMessage(
"as the IRC server password like this: user/network:pass.", true);
CUtils::PrintMessage("");
CUtils::PrintMessage("Try something like this in your IRC client...", true);
CUtils::PrintMessage("/server <znc_server_ip> " + sSSL +
CString(uListenPort) + " " + sUser + ":<pass>",
true);
CUtils::PrintMessage("");
CUtils::PrintMessage(
"To manage settings, users and networks, point your web browser to",
true);
CUtils::PrintMessage(
sProtocol + "://<znc_server_ip>:" + CString(uListenPort) + "/", true);
CUtils::PrintMessage("");
File.UnLock();
bool bWantLaunch = bFileOpen;
if (bWantLaunch) {
// "export ZNC_NO_LAUNCH_AFTER_MAKECONF=1" would cause znc --makeconf to
// not offer immediate launch.
// Useful for distros which want to create config when znc package is
// installed.
// See https://github.com/znc/znc/pull/257
char* szNoLaunch = getenv("ZNC_NO_LAUNCH_AFTER_MAKECONF");
if (szNoLaunch && *szNoLaunch == '1') {
bWantLaunch = false;
}
}
if (bWantLaunch) {
bWantLaunch = CUtils::GetBoolInput("Launch ZNC now?", true);
}
return bWantLaunch;
}
void CZNC::BackupConfigOnce(const CString& sSuffix) {
static bool didBackup = false;
if (didBackup) return;
didBackup = true;
CUtils::PrintAction("Creating a config backup");
CString sBackup = CDir::ChangeDir(m_sConfigFile, "../znc.conf." + sSuffix);
if (CFile::Copy(m_sConfigFile, sBackup))
CUtils::PrintStatus(true, sBackup);
else
CUtils::PrintStatus(false, strerror(errno));
}
bool CZNC::ParseConfig(const CString& sConfig, CString& sError) {
m_sConfigFile = ExpandConfigPath(sConfig, false);
CConfig config;
if (!ReadConfig(config, sError)) return false;
if (!LoadGlobal(config, sError)) return false;
if (!LoadUsers(config, sError)) return false;
return true;
}
bool CZNC::ReadConfig(CConfig& config, CString& sError) {
sError.clear();
CUtils::PrintAction("Opening config [" + m_sConfigFile + "]");
if (!CFile::Exists(m_sConfigFile)) {
sError = "No such file";
CUtils::PrintStatus(false, sError);
CUtils::PrintMessage(
"Restart ZNC with the --makeconf option if you wish to create this "
"config.");
return false;
}
if (!CFile::IsReg(m_sConfigFile)) {
sError = "Not a file";
CUtils::PrintStatus(false, sError);
return false;
}
CFile* pFile = new CFile(m_sConfigFile);
// need to open the config file Read/Write for fcntl()
// exclusive locking to work properly!
if (!pFile->Open(m_sConfigFile, O_RDWR)) {
sError = "Can not open config file";
CUtils::PrintStatus(false, sError);
delete pFile;
return false;
}
if (!pFile->TryExLock()) {
sError = "ZNC is already running on this config.";
CUtils::PrintStatus(false, sError);
delete pFile;
return false;
}
// (re)open the config file
delete m_pLockFile;
m_pLockFile = pFile;
CFile& File = *pFile;
if (!config.Parse(File, sError)) {
CUtils::PrintStatus(false, sError);
return false;
}
CUtils::PrintStatus(true);
// check if config is from old ZNC version and
// create a backup file if necessary
CString sSavedVersion;
config.FindStringEntry("version", sSavedVersion);
if (sSavedVersion.empty()) {
CUtils::PrintError(
"Config does not contain a version identifier. It may be be too "
"old or corrupt.");
return false;
}
tuple<unsigned int, unsigned int> tSavedVersion =
make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(),
sSavedVersion.Token(1, false, ".").ToUInt());
tuple<unsigned int, unsigned int> tCurrentVersion =
make_tuple(VERSION_MAJOR, VERSION_MINOR);
if (tSavedVersion < tCurrentVersion) {
CUtils::PrintMessage("Found old config from ZNC " + sSavedVersion +
". Saving a backup of it.");
BackupConfigOnce("pre-" + CString(VERSION_STR));
} else if (tSavedVersion > tCurrentVersion) {
CUtils::PrintError("Config was saved from ZNC " + sSavedVersion +
". It may or may not work with current ZNC " +
GetVersion());
}
return true;
}
bool CZNC::RehashConfig(CString& sError) {
ALLMODULECALL(OnPreRehash(), NOTHING);
CConfig config;
if (!ReadConfig(config, sError)) return false;
if (!LoadGlobal(config, sError)) return false;
// do not reload users - it's dangerous!
ALLMODULECALL(OnPostRehash(), NOTHING);
return true;
}
bool CZNC::LoadGlobal(CConfig& config, CString& sError) {
sError.clear();
MCString msModules; // Modules are queued for later loading
VCString vsList;
config.FindStringVector("loadmodule", vsList);
for (const CString& sModLine : vsList) {
CString sModName = sModLine.Token(0);
CString sArgs = sModLine.Token(1, true);
// compatibility for pre-1.0 configs
CString sSavedVersion;
config.FindStringEntry("version", sSavedVersion);
tuple<unsigned int, unsigned int> tSavedVersion =
make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(),
sSavedVersion.Token(1, false, ".").ToUInt());
if (sModName == "saslauth" && tSavedVersion < make_tuple(0, 207)) {
CUtils::PrintMessage(
"saslauth module was renamed to cyrusauth. Loading cyrusauth "
"instead.");
sModName = "cyrusauth";
}
// end-compatibility for pre-1.0 configs
if (msModules.find(sModName) != msModules.end()) {
sError = "Module [" + sModName + "] already loaded";
CUtils::PrintError(sError);
return false;
}
CString sModRet;
CModule* pOldMod;
pOldMod = GetModules().FindModule(sModName);
if (!pOldMod) {
CUtils::PrintAction("Loading global module [" + sModName + "]");
bool bModRet =
GetModules().LoadModule(sModName, sArgs, CModInfo::GlobalModule,
nullptr, nullptr, sModRet);
CUtils::PrintStatus(bModRet, bModRet ? "" : sModRet);
if (!bModRet) {
sError = sModRet;
return false;
}
} else if (pOldMod->GetArgs() != sArgs) {
CUtils::PrintAction("Reloading global module [" + sModName + "]");
bool bModRet = GetModules().ReloadModule(sModName, sArgs, nullptr,
nullptr, sModRet);
CUtils::PrintStatus(bModRet, sModRet);
if (!bModRet) {
sError = sModRet;
return false;
}
} else
CUtils::PrintMessage("Module [" + sModName + "] already loaded.");
msModules[sModName] = sArgs;
}
m_vsMotd.clear();
config.FindStringVector("motd", vsList);
for (const CString& sMotd : vsList) {
AddMotd(sMotd);
}
if (config.FindStringVector("bindhost", vsList)) {
CUtils::PrintStatus(false,
"WARNING: the global BindHost list is deprecated. "
"Ignoring the following lines:");
for (const CString& sHost : vsList) {
CUtils::PrintStatus(false, "BindHost = " + sHost);
}
}
if (config.FindStringVector("vhost", vsList)) {
CUtils::PrintStatus(false,
"WARNING: the global vHost list is deprecated. "
"Ignoring the following lines:");
for (const CString& sHost : vsList) {
CUtils::PrintStatus(false, "vHost = " + sHost);
}
}
m_vsTrustedProxies.clear();
config.FindStringVector("trustedproxy", vsList);
for (const CString& sProxy : vsList) {
AddTrustedProxy(sProxy);
}
CString sVal;
if (config.FindStringEntry("pidfile", sVal)) m_sPidFile = sVal;
if (config.FindStringEntry("statusprefix", sVal)) m_sStatusPrefix = sVal;
if (config.FindStringEntry("sslcertfile", sVal)) m_sSSLCertFile = sVal;
if (config.FindStringEntry("sslkeyfile", sVal)) m_sSSLKeyFile = sVal;
if (config.FindStringEntry("ssldhparamfile", sVal))
m_sSSLDHParamFile = sVal;
if (config.FindStringEntry("sslciphers", sVal)) m_sSSLCiphers = sVal;
if (config.FindStringEntry("skin", sVal)) SetSkinName(sVal);
if (config.FindStringEntry("connectdelay", sVal))
SetConnectDelay(sVal.ToUInt());
if (config.FindStringEntry("serverthrottle", sVal))
m_sConnectThrottle.SetTTL(sVal.ToUInt() * 1000);
if (config.FindStringEntry("anoniplimit", sVal))
m_uiAnonIPLimit = sVal.ToUInt();
if (config.FindStringEntry("maxbuffersize", sVal))
m_uiMaxBufferSize = sVal.ToUInt();
if (config.FindStringEntry("protectwebsessions", sVal))
m_bProtectWebSessions = sVal.ToBool();
if (config.FindStringEntry("hideversion", sVal))
m_bHideVersion = sVal.ToBool();
if (config.FindStringEntry("authonlyviamodule", sVal))
m_bAuthOnlyViaModule = sVal.ToBool();
if (config.FindStringEntry("sslprotocols", sVal)) {
if (!SetSSLProtocols(sVal)) {
VCString vsProtocols = GetAvailableSSLProtocols();
CUtils::PrintError("Invalid SSLProtocols value [" + sVal + "]");
CUtils::PrintError(
"The syntax is [SSLProtocols = [+|-]<protocol> ...]");
CUtils::PrintError(
"Available protocols are [" +
CString(", ").Join(vsProtocols.begin(), vsProtocols.end()) +
"]");
return false;
}
}
if (config.FindStringEntry("configwritedelay", sVal))
m_uiConfigWriteDelay = sVal.ToUInt();
UnloadRemovedModules(msModules);
if (!LoadListeners(config, sError)) return false;
return true;
}
bool CZNC::LoadUsers(CConfig& config, CString& sError) {
sError.clear();
m_msUsers.clear();
CConfig::SubConfig subConf;
config.FindSubConfig("user", subConf);
for (const auto& subIt : subConf) {
const CString& sUserName = subIt.first;
CConfig* pSubConf = subIt.second.m_pSubConfig;
CUtils::PrintMessage("Loading user [" + sUserName + "]");
std::unique_ptr<CUser> pUser(new CUser(sUserName));
if (!m_sStatusPrefix.empty()) {
if (!pUser->SetStatusPrefix(m_sStatusPrefix)) {
sError = "Invalid StatusPrefix [" + m_sStatusPrefix +
"] Must be 1-5 chars, no spaces.";
CUtils::PrintError(sError);
return false;
}
}
if (!pUser->ParseConfig(pSubConf, sError)) {
CUtils::PrintError(sError);
return false;
}
if (!pSubConf->empty()) {
sError = "Unhandled lines in config for User [" + sUserName + "]!";
CUtils::PrintError(sError);
DumpConfig(pSubConf);
return false;
}
CString sErr;
if (!AddUser(pUser.release(), sErr, true)) {
sError = "Invalid user [" + sUserName + "] " + sErr;
}
if (!sError.empty()) {
CUtils::PrintError(sError);
pUser->SetBeingDeleted(true);
return false;
}
}
if (m_msUsers.empty()) {
sError = "You must define at least one user in your config.";
CUtils::PrintError(sError);
return false;
}
return true;
}
bool CZNC::LoadListeners(CConfig& config, CString& sError) {
sError.clear();
// Delete all listeners
while (!m_vpListeners.empty()) {
delete m_vpListeners[0];
m_vpListeners.erase(m_vpListeners.begin());
}
// compatibility for pre-1.0 configs
const char* szListenerEntries[] = {"listen", "listen6", "listen4",
"listener", "listener6", "listener4"};
VCString vsList;
config.FindStringVector("loadmodule", vsList);
// This has to be after SSLCertFile is handled since it uses that value
for (const char* szEntry : szListenerEntries) {
config.FindStringVector(szEntry, vsList);
for (const CString& sListener : vsList) {
if (!AddListener(szEntry + CString(" ") + sListener, sError))
return false;
}
}
// end-compatibility for pre-1.0 configs
CConfig::SubConfig subConf;
config.FindSubConfig("listener", subConf);
for (const auto& subIt : subConf) {
CConfig* pSubConf = subIt.second.m_pSubConfig;
if (!AddListener(pSubConf, sError)) return false;
if (!pSubConf->empty()) {
sError = "Unhandled lines in Listener config!";
CUtils::PrintError(sError);
CZNC::DumpConfig(pSubConf);
return false;
}
}
if (m_vpListeners.empty()) {
sError = "You must supply at least one Listener in your config.";
CUtils::PrintError(sError);
return false;
}
return true;
}
void CZNC::UnloadRemovedModules(const MCString& msModules) {
// unload modules which are no longer in the config
set<CString> ssUnload;
for (CModule* pCurMod : GetModules()) {
if (msModules.find(pCurMod->GetModName()) == msModules.end())
ssUnload.insert(pCurMod->GetModName());
}
for (const CString& sMod : ssUnload) {
if (GetModules().UnloadModule(sMod))
CUtils::PrintMessage("Unloaded global module [" + sMod + "]");
else
CUtils::PrintMessage("Could not unload [" + sMod + "]");
}
}
void CZNC::DumpConfig(const CConfig* pConfig) {
CConfig::EntryMapIterator eit = pConfig->BeginEntries();
for (; eit != pConfig->EndEntries(); ++eit) {
const CString& sKey = eit->first;
const VCString& vsList = eit->second;
VCString::const_iterator it = vsList.begin();
for (; it != vsList.end(); ++it) {
CUtils::PrintError(sKey + " = " + *it);
}
}
CConfig::SubConfigMapIterator sit = pConfig->BeginSubConfigs();
for (; sit != pConfig->EndSubConfigs(); ++sit) {
const CString& sKey = sit->first;
const CConfig::SubConfig& sSub = sit->second;
CConfig::SubConfig::const_iterator it = sSub.begin();
for (; it != sSub.end(); ++it) {
CUtils::PrintError("SubConfig [" + sKey + " " + it->first + "]:");
DumpConfig(it->second.m_pSubConfig);
}
}
}
void CZNC::ClearTrustedProxies() { m_vsTrustedProxies.clear(); }
bool CZNC::AddTrustedProxy(const CString& sHost) {
if (sHost.empty()) {
return false;
}
for (const CString& sTrustedProxy : m_vsTrustedProxies) {
if (sTrustedProxy.Equals(sHost)) {
return false;
}
}
m_vsTrustedProxies.push_back(sHost);
return true;
}
bool CZNC::RemTrustedProxy(const CString& sHost) {
VCString::iterator it;
for (it = m_vsTrustedProxies.begin(); it != m_vsTrustedProxies.end();
++it) {
if (sHost.Equals(*it)) {
m_vsTrustedProxies.erase(it);
return true;
}
}
return false;
}
void CZNC::Broadcast(const CString& sMessage, bool bAdminOnly, CUser* pSkipUser,
CClient* pSkipClient) {
for (const auto& it : m_msUsers) {
if (bAdminOnly && !it.second->IsAdmin()) continue;
if (it.second != pSkipUser) {
// TODO: translate message to user's language
CString sMsg = sMessage;
bool bContinue = false;
USERMODULECALL(OnBroadcast(sMsg), it.second, nullptr, &bContinue);
if (bContinue) continue;
it.second->PutStatusNotice("*** " + sMsg, nullptr, pSkipClient);
}
}
}
CModule* CZNC::FindModule(const CString& sModName, const CString& sUsername) {
if (sUsername.empty()) {
return CZNC::Get().GetModules().FindModule(sModName);
}
CUser* pUser = FindUser(sUsername);
return (!pUser) ? nullptr : pUser->GetModules().FindModule(sModName);
}
CModule* CZNC::FindModule(const CString& sModName, CUser* pUser) {
if (pUser) {
return pUser->GetModules().FindModule(sModName);
}
return CZNC::Get().GetModules().FindModule(sModName);
}
bool CZNC::UpdateModule(const CString& sModule) {
CModule* pModule;
map<CUser*, CString> musLoaded;
map<CIRCNetwork*, CString> mnsLoaded;
// Unload the module for every user and network
for (const auto& it : m_msUsers) {
CUser* pUser = it.second;
pModule = pUser->GetModules().FindModule(sModule);
if (pModule) {
musLoaded[pUser] = pModule->GetArgs();
pUser->GetModules().UnloadModule(sModule);
}
// See if the user has this module loaded to a network
vector<CIRCNetwork*> vNetworks = pUser->GetNetworks();
for (CIRCNetwork* pNetwork : vNetworks) {
pModule = pNetwork->GetModules().FindModule(sModule);
if (pModule) {
mnsLoaded[pNetwork] = pModule->GetArgs();
pNetwork->GetModules().UnloadModule(sModule);
}
}
}
// Unload the global module
bool bGlobal = false;
CString sGlobalArgs;
pModule = GetModules().FindModule(sModule);
if (pModule) {
bGlobal = true;
sGlobalArgs = pModule->GetArgs();
GetModules().UnloadModule(sModule);
}
// Lets reload everything
bool bError = false;
CString sErr;
// Reload the global module
if (bGlobal) {
if (!GetModules().LoadModule(sModule, sGlobalArgs,
CModInfo::GlobalModule, nullptr, nullptr,
sErr)) {
DEBUG("Failed to reload [" << sModule << "] globally [" << sErr
<< "]");
bError = true;
}
}
// Reload the module for all users
for (const auto& it : musLoaded) {
CUser* pUser = it.first;
const CString& sArgs = it.second;
if (!pUser->GetModules().LoadModule(
sModule, sArgs, CModInfo::UserModule, pUser, nullptr, sErr)) {
DEBUG("Failed to reload [" << sModule << "] for ["
<< pUser->GetUserName() << "] [" << sErr
<< "]");
bError = true;
}
}
// Reload the module for all networks
for (const auto& it : mnsLoaded) {
CIRCNetwork* pNetwork = it.first;
const CString& sArgs = it.second;
if (!pNetwork->GetModules().LoadModule(
sModule, sArgs, CModInfo::NetworkModule, pNetwork->GetUser(),
pNetwork, sErr)) {
DEBUG("Failed to reload ["
<< sModule << "] for [" << pNetwork->GetUser()->GetUserName()
<< "/" << pNetwork->GetName() << "] [" << sErr << "]");
bError = true;
}
}
return !bError;
}
CUser* CZNC::FindUser(const CString& sUsername) {
map<CString, CUser*>::iterator it = m_msUsers.find(sUsername);
if (it != m_msUsers.end()) {
return it->second;
}
return nullptr;
}
bool CZNC::DeleteUser(const CString& sUsername) {
CUser* pUser = FindUser(sUsername);
if (!pUser) {
return false;
}
m_msDelUsers[pUser->GetUserName()] = pUser;
return true;
}
bool CZNC::AddUser(CUser* pUser, CString& sErrorRet, bool bStartup) {
if (FindUser(pUser->GetUserName()) != nullptr) {
sErrorRet = t_s("User already exists");
DEBUG("User [" << pUser->GetUserName() << "] - already exists");
return false;
}
if (!pUser->IsValid(sErrorRet)) {
DEBUG("Invalid user [" << pUser->GetUserName() << "] - [" << sErrorRet
<< "]");
return false;
}
bool bFailed = false;
// do not call OnAddUser hook during ZNC startup
if (!bStartup) {
GLOBALMODULECALL(OnAddUser(*pUser, sErrorRet), &bFailed);
}
if (bFailed) {
DEBUG("AddUser [" << pUser->GetUserName() << "] aborted by a module ["
<< sErrorRet << "]");
return false;
}
m_msUsers[pUser->GetUserName()] = pUser;
return true;
}
CListener* CZNC::FindListener(u_short uPort, const CString& sBindHost,
EAddrType eAddr) {
for (CListener* pListener : m_vpListeners) {
if (pListener->GetPort() != uPort) continue;
if (pListener->GetBindHost() != sBindHost) continue;
if (pListener->GetAddrType() != eAddr) continue;
return pListener;
}
return nullptr;
}
bool CZNC::AddListener(const CString& sLine, CString& sError) {
CString sName = sLine.Token(0);
CString sValue = sLine.Token(1, true);
EAddrType eAddr = ADDR_ALL;
if (sName.Equals("Listen4") || sName.Equals("Listen") ||
sName.Equals("Listener4")) {
eAddr = ADDR_IPV4ONLY;
}
if (sName.Equals("Listener6")) {
eAddr = ADDR_IPV6ONLY;
}
CListener::EAcceptType eAccept = CListener::ACCEPT_ALL;
if (sValue.TrimPrefix("irc_only "))
eAccept = CListener::ACCEPT_IRC;
else if (sValue.TrimPrefix("web_only "))
eAccept = CListener::ACCEPT_HTTP;
bool bSSL = false;
CString sPort;
CString sBindHost;
if (ADDR_IPV4ONLY == eAddr) {
sValue.Replace(":", " ");
}
if (sValue.Contains(" ")) {
sBindHost = sValue.Token(0, false, " ");
sPort = sValue.Token(1, true, " ");
} else {
sPort = sValue;
}
if (sPort.TrimPrefix("+")) {
bSSL = true;
}
// No support for URIPrefix for old-style configs.
CString sURIPrefix;
unsigned short uPort = sPort.ToUShort();
return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept,
sError);
}
bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost,
const CString& sURIPrefixRaw, bool bSSL, EAddrType eAddr,
CListener::EAcceptType eAccept, CString& sError) {
CString sHostComment;
if (!sBindHost.empty()) {
sHostComment = " on host [" + sBindHost + "]";
}
CString sIPV6Comment;
switch (eAddr) {
case ADDR_ALL:
sIPV6Comment = "";
break;
case ADDR_IPV4ONLY:
sIPV6Comment = " using ipv4";
break;
case ADDR_IPV6ONLY:
sIPV6Comment = " using ipv6";
}
CUtils::PrintAction("Binding to port [" + CString((bSSL) ? "+" : "") +
CString(uPort) + "]" + sHostComment + sIPV6Comment);
#ifndef HAVE_IPV6
if (ADDR_IPV6ONLY == eAddr) {
sError = t_s("IPv6 is not enabled");
CUtils::PrintStatus(false, sError);
return false;
}
#endif
#ifndef HAVE_LIBSSL
if (bSSL) {
sError = t_s("SSL is not enabled");
CUtils::PrintStatus(false, sError);
return false;
}
#else
CString sPemFile = GetPemLocation();
if (bSSL && !CFile::Exists(sPemFile)) {
sError = t_f("Unable to locate pem file: {1}")(sPemFile);
CUtils::PrintStatus(false, sError);
// If stdin is e.g. /dev/null and we call GetBoolInput(),
// we are stuck in an endless loop!
if (isatty(0) &&
CUtils::GetBoolInput("Would you like to create a new pem file?",
true)) {
sError.clear();
WritePemFile();
} else {
return false;
}
CUtils::PrintAction("Binding to port [+" + CString(uPort) + "]" +
sHostComment + sIPV6Comment);
}
#endif
if (!uPort) {
sError = t_s("Invalid port");
CUtils::PrintStatus(false, sError);
return false;
}
// URIPrefix must start with a slash and end without one.
CString sURIPrefix = CString(sURIPrefixRaw);
if (!sURIPrefix.empty()) {
if (!sURIPrefix.StartsWith("/")) {
sURIPrefix = "/" + sURIPrefix;
}
if (sURIPrefix.EndsWith("/")) {
sURIPrefix.TrimRight("/");
}
}
CListener* pListener =
new CListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept);
if (!pListener->Listen()) {
sError = FormatBindError();
CUtils::PrintStatus(false, sError);
delete pListener;
return false;
}
m_vpListeners.push_back(pListener);
CUtils::PrintStatus(true);
return true;
}
bool CZNC::AddListener(CConfig* pConfig, CString& sError) {
CString sBindHost;
CString sURIPrefix;
bool bSSL;
bool b4;
#ifdef HAVE_IPV6
bool b6 = true;
#else
bool b6 = false;
#endif
bool bIRC;
bool bWeb;
unsigned short uPort;
if (!pConfig->FindUShortEntry("port", uPort)) {
sError = "No port given";
CUtils::PrintError(sError);
return false;
}
pConfig->FindStringEntry("host", sBindHost);
pConfig->FindBoolEntry("ssl", bSSL, false);
pConfig->FindBoolEntry("ipv4", b4, true);
pConfig->FindBoolEntry("ipv6", b6, b6);
pConfig->FindBoolEntry("allowirc", bIRC, true);
pConfig->FindBoolEntry("allowweb", bWeb, true);
pConfig->FindStringEntry("uriprefix", sURIPrefix);
EAddrType eAddr;
if (b4 && b6) {
eAddr = ADDR_ALL;
} else if (b4 && !b6) {
eAddr = ADDR_IPV4ONLY;
} else if (!b4 && b6) {
eAddr = ADDR_IPV6ONLY;
} else {
sError = "No address family given";
CUtils::PrintError(sError);
return false;
}
CListener::EAcceptType eAccept;
if (bIRC && bWeb) {
eAccept = CListener::ACCEPT_ALL;
} else if (bIRC && !bWeb) {
eAccept = CListener::ACCEPT_IRC;
} else if (!bIRC && bWeb) {
eAccept = CListener::ACCEPT_HTTP;
} else {
sError = "Either Web or IRC or both should be selected";
CUtils::PrintError(sError);
return false;
}
return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept,
sError);
}
bool CZNC::AddListener(CListener* pListener) {
if (!pListener->GetRealListener()) {
// Listener doesn't actually listen
delete pListener;
return false;
}
// We don't check if there is an identical listener already listening
// since one can't listen on e.g. the same port multiple times
m_vpListeners.push_back(pListener);
return true;
}
bool CZNC::DelListener(CListener* pListener) {
auto it = std::find(m_vpListeners.begin(), m_vpListeners.end(), pListener);
if (it != m_vpListeners.end()) {
m_vpListeners.erase(it);
delete pListener;
return true;
}
return false;
}
CString CZNC::FormatBindError() {
CString sError = (errno == 0 ? t_s(("unknown error, check the host name"))
: CString(strerror(errno)));
return t_f("Unable to bind: {1}")(sError);
}
static CZNC* s_pZNC = nullptr;
void CZNC::CreateInstance() {
if (s_pZNC) abort();
s_pZNC = new CZNC();
}
CZNC& CZNC::Get() { return *s_pZNC; }
void CZNC::DestroyInstance() {
delete s_pZNC;
s_pZNC = nullptr;
}
CZNC::TrafficStatsMap CZNC::GetTrafficStats(TrafficStatsPair& Users,
TrafficStatsPair& ZNC,
TrafficStatsPair& Total) {
TrafficStatsMap ret;
unsigned long long uiUsers_in, uiUsers_out, uiZNC_in, uiZNC_out;
const map<CString, CUser*>& msUsers = CZNC::Get().GetUserMap();
uiUsers_in = uiUsers_out = 0;
uiZNC_in = BytesRead();
uiZNC_out = BytesWritten();
for (const auto& it : msUsers) {
ret[it.first] =
TrafficStatsPair(it.second->BytesRead(), it.second->BytesWritten());
uiUsers_in += it.second->BytesRead();
uiUsers_out += it.second->BytesWritten();
}
for (Csock* pSock : m_Manager) {
CUser* pUser = nullptr;
if (pSock->GetSockName().StartsWith("IRC::")) {
pUser = ((CIRCSock*)pSock)->GetNetwork()->GetUser();
} else if (pSock->GetSockName().StartsWith("USR::")) {
pUser = ((CClient*)pSock)->GetUser();
}
if (pUser) {
ret[pUser->GetUserName()].first += pSock->GetBytesRead();
ret[pUser->GetUserName()].second += pSock->GetBytesWritten();
uiUsers_in += pSock->GetBytesRead();
uiUsers_out += pSock->GetBytesWritten();
} else {
uiZNC_in += pSock->GetBytesRead();
uiZNC_out += pSock->GetBytesWritten();
}
}
Users = TrafficStatsPair(uiUsers_in, uiUsers_out);
ZNC = TrafficStatsPair(uiZNC_in, uiZNC_out);
Total = TrafficStatsPair(uiUsers_in + uiZNC_in, uiUsers_out + uiZNC_out);
return ret;
}
CZNC::TrafficStatsMap CZNC::GetNetworkTrafficStats(const CString& sUsername,
TrafficStatsPair& Total) {
TrafficStatsMap Networks;
CUser* pUser = FindUser(sUsername);
if (pUser) {
for (const CIRCNetwork* pNetwork : pUser->GetNetworks()) {
Networks[pNetwork->GetName()].first = pNetwork->BytesRead();
Networks[pNetwork->GetName()].second = pNetwork->BytesWritten();
Total.first += pNetwork->BytesRead();
Total.second += pNetwork->BytesWritten();
}
for (Csock* pSock : m_Manager) {
CIRCNetwork* pNetwork = nullptr;
if (pSock->GetSockName().StartsWith("IRC::")) {
pNetwork = ((CIRCSock*)pSock)->GetNetwork();
} else if (pSock->GetSockName().StartsWith("USR::")) {
pNetwork = ((CClient*)pSock)->GetNetwork();
}
if (pNetwork && pNetwork->GetUser() == pUser) {
Networks[pNetwork->GetName()].first = pSock->GetBytesRead();
Networks[pNetwork->GetName()].second = pSock->GetBytesWritten();
Total.first += pSock->GetBytesRead();
Total.second += pSock->GetBytesWritten();
}
}
}
return Networks;
}
void CZNC::AuthUser(std::shared_ptr<CAuthBase> AuthClass) {
// TODO unless the auth module calls it, CUser::IsHostAllowed() is not
// honoured
bool bReturn = false;
GLOBALMODULECALL(OnLoginAttempt(AuthClass), &bReturn);
if (bReturn) return;
CUser* pUser = FindUser(AuthClass->GetUsername());
if (!pUser || !pUser->CheckPass(AuthClass->GetPassword())) {
AuthClass->RefuseLogin("Invalid Password");
return;
}
CString sHost = AuthClass->GetRemoteIP();
if (!pUser->IsHostAllowed(sHost)) {
AuthClass->RefuseLogin("Your host [" + sHost + "] is not allowed");
return;
}
AuthClass->AcceptLogin(*pUser);
}
class CConnectQueueTimer : public CCron {
public:
CConnectQueueTimer(int iSecs) : CCron() {
SetName("Connect users");
Start(iSecs);
// Don't wait iSecs seconds for first timer run
m_bRunOnNextCall = true;
}
~CConnectQueueTimer() override {
// This is only needed when ZNC shuts down:
// CZNC::~CZNC() sets its CConnectQueueTimer pointer to nullptr and
// calls the manager's Cleanup() which destroys all sockets and
// timers. If something calls CZNC::EnableConnectQueue() here
// (e.g. because a CIRCSock is destroyed), the socket manager
// deletes that timer almost immediately, but CZNC now got a
// dangling pointer to this timer which can crash later on.
//
// Unlikely but possible ;)
CZNC::Get().LeakConnectQueueTimer(this);
}
protected:
void RunJob() override {
list<CIRCNetwork*> ConnectionQueue;
list<CIRCNetwork*>& RealConnectionQueue =
CZNC::Get().GetConnectionQueue();
// Problem: If a network can't connect right now because e.g. it
// is throttled, it will re-insert itself into the connection
// queue. However, we must only give each network a single
// chance during this timer run.
//
// Solution: We move the connection queue to our local list at
// the beginning and work from that.
ConnectionQueue.swap(RealConnectionQueue);
while (!ConnectionQueue.empty()) {
CIRCNetwork* pNetwork = ConnectionQueue.front();
ConnectionQueue.pop_front();
if (pNetwork->Connect()) {
break;
}
}
/* Now re-insert anything that is left in our local list into
* the real connection queue.
*/
RealConnectionQueue.splice(RealConnectionQueue.begin(),
ConnectionQueue);
if (RealConnectionQueue.empty()) {
DEBUG("ConnectQueueTimer done");
CZNC::Get().DisableConnectQueue();
}
}
};
void CZNC::SetConnectDelay(unsigned int i) {
if (i < 1) {
// Don't hammer server with our failed connects
i = 1;
}
if (m_uiConnectDelay != i && m_pConnectQueueTimer != nullptr) {
m_pConnectQueueTimer->Start(i);
}
m_uiConnectDelay = i;
}
VCString CZNC::GetAvailableSSLProtocols() {
// NOTE: keep in sync with SetSSLProtocols()
return {"SSLv2", "SSLv3", "TLSv1", "TLSV1.1", "TLSv1.2"};
}
bool CZNC::SetSSLProtocols(const CString& sProtocols) {
VCString vsProtocols;
sProtocols.Split(" ", vsProtocols, false, "", "", true, true);
unsigned int uDisabledProtocols = Csock::EDP_SSL;
for (CString& sProtocol : vsProtocols) {
unsigned int uFlag = 0;
bool bEnable = sProtocol.TrimPrefix("+");
bool bDisable = sProtocol.TrimPrefix("-");
// NOTE: keep in sync with GetAvailableSSLProtocols()
if (sProtocol.Equals("All")) {
uFlag = ~0;
} else if (sProtocol.Equals("SSLv2")) {
uFlag = Csock::EDP_SSLv2;
} else if (sProtocol.Equals("SSLv3")) {
uFlag = Csock::EDP_SSLv3;
} else if (sProtocol.Equals("TLSv1")) {
uFlag = Csock::EDP_TLSv1;
} else if (sProtocol.Equals("TLSv1.1")) {
uFlag = Csock::EDP_TLSv1_1;
} else if (sProtocol.Equals("TLSv1.2")) {
uFlag = Csock::EDP_TLSv1_2;
} else {
return false;
}
if (bEnable) {
uDisabledProtocols &= ~uFlag;
} else if (bDisable) {
uDisabledProtocols |= uFlag;
} else {
uDisabledProtocols = ~uFlag;
}
}
m_sSSLProtocols = sProtocols;
m_uDisabledSSLProtocols = uDisabledProtocols;
return true;
}
void CZNC::EnableConnectQueue() {
if (!m_pConnectQueueTimer && !m_uiConnectPaused &&
!m_lpConnectQueue.empty()) {
m_pConnectQueueTimer = new CConnectQueueTimer(m_uiConnectDelay);
GetManager().AddCron(m_pConnectQueueTimer);
}
}
void CZNC::DisableConnectQueue() {
if (m_pConnectQueueTimer) {
// This will kill the cron
m_pConnectQueueTimer->Stop();
m_pConnectQueueTimer = nullptr;
}
}
void CZNC::PauseConnectQueue() {
DEBUG("Connection queue paused");
m_uiConnectPaused++;
if (m_pConnectQueueTimer) {
m_pConnectQueueTimer->Pause();
}
}
void CZNC::ResumeConnectQueue() {
DEBUG("Connection queue resumed");
m_uiConnectPaused--;
EnableConnectQueue();
if (m_pConnectQueueTimer) {
m_pConnectQueueTimer->UnPause();
}
}
void CZNC::ForceEncoding() {
m_uiForceEncoding++;
#ifdef HAVE_ICU
for (Csock* pSock : GetManager()) {
if (pSock->GetEncoding().empty()) {
pSock->SetEncoding("UTF-8");
}
}
#endif
}
void CZNC::UnforceEncoding() { m_uiForceEncoding--; }
bool CZNC::IsForcingEncoding() const { return m_uiForceEncoding; }
CString CZNC::FixupEncoding(const CString& sEncoding) const {
if (sEncoding.empty() && m_uiForceEncoding) {
return "UTF-8";
}
return sEncoding;
}
void CZNC::AddNetworkToQueue(CIRCNetwork* pNetwork) {
// Make sure we are not already in the queue
if (std::find(m_lpConnectQueue.begin(), m_lpConnectQueue.end(), pNetwork) !=
m_lpConnectQueue.end()) {
return;
}
m_lpConnectQueue.push_back(pNetwork);
EnableConnectQueue();
}
void CZNC::LeakConnectQueueTimer(CConnectQueueTimer* pTimer) {
if (m_pConnectQueueTimer == pTimer) m_pConnectQueueTimer = nullptr;
}
bool CZNC::WaitForChildLock() { return m_pLockFile && m_pLockFile->ExLock(); }
void CZNC::DisableConfigTimer() {
if (m_pConfigTimer) {
m_pConfigTimer->Stop();
m_pConfigTimer = nullptr;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1442_3 |
crossvul-cpp_data_good_847_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/mbstring/ext_mbstring.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/ini-setting.h"
#include "hphp/runtime/base/request-event-handler.h"
#include "hphp/runtime/base/string-buffer.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/runtime/base/zend-url.h"
#include "hphp/runtime/ext/mbstring/php_unicode.h"
#include "hphp/runtime/ext/mbstring/unicode_data.h"
#include "hphp/runtime/ext/std/ext_std_output.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "hphp/util/rds-local.h"
#include <map>
extern "C" {
#include <mbfl/mbfl_convert.h>
#include <mbfl/mbfilter.h>
#include <mbfl/mbfilter_pass.h>
#include <oniguruma.h>
}
#define php_mb_re_pattern_buffer re_pattern_buffer
#define php_mb_regex_t regex_t
#define php_mb_re_registers re_registers
extern void mbfl_memory_device_unput(mbfl_memory_device *device);
#define PARSE_POST 0
#define PARSE_GET 1
#define PARSE_COOKIE 2
#define PARSE_STRING 3
#define PARSE_ENV 4
#define PARSE_SERVER 5
#define PARSE_SESSION 6
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// statics
#define PHP_MBSTR_STACK_BLOCK_SIZE 32
typedef struct _php_mb_nls_ident_list {
mbfl_no_language lang;
mbfl_no_encoding* list;
int list_size;
} php_mb_nls_ident_list;
static mbfl_no_encoding php_mb_default_identify_list_ja[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_jis,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_jp,
mbfl_no_encoding_sjis
};
static mbfl_no_encoding php_mb_default_identify_list_cn[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_cn,
mbfl_no_encoding_cp936
};
static mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_tw,
mbfl_no_encoding_big5
};
static mbfl_no_encoding php_mb_default_identify_list_kr[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_euc_kr,
mbfl_no_encoding_uhc
};
static mbfl_no_encoding php_mb_default_identify_list_ru[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_koi8r,
mbfl_no_encoding_cp1251,
mbfl_no_encoding_cp866
};
static mbfl_no_encoding php_mb_default_identify_list_hy[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_armscii8
};
static mbfl_no_encoding php_mb_default_identify_list_tr[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8,
mbfl_no_encoding_8859_9
};
static mbfl_no_encoding php_mb_default_identify_list_neut[] = {
mbfl_no_encoding_ascii,
mbfl_no_encoding_utf8
};
static php_mb_nls_ident_list php_mb_default_identify_list[] = {
{ mbfl_no_language_japanese, php_mb_default_identify_list_ja,
sizeof(php_mb_default_identify_list_ja) /
sizeof(php_mb_default_identify_list_ja[0]) },
{ mbfl_no_language_korean, php_mb_default_identify_list_kr,
sizeof(php_mb_default_identify_list_kr) /
sizeof(php_mb_default_identify_list_kr[0]) },
{ mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk,
sizeof(php_mb_default_identify_list_tw_hk) /
sizeof(php_mb_default_identify_list_tw_hk[0]) },
{ mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn,
sizeof(php_mb_default_identify_list_cn) /
sizeof(php_mb_default_identify_list_cn[0]) },
{ mbfl_no_language_russian, php_mb_default_identify_list_ru,
sizeof(php_mb_default_identify_list_ru) /
sizeof(php_mb_default_identify_list_ru[0]) },
{ mbfl_no_language_armenian, php_mb_default_identify_list_hy,
sizeof(php_mb_default_identify_list_hy) /
sizeof(php_mb_default_identify_list_hy[0]) },
{ mbfl_no_language_turkish, php_mb_default_identify_list_tr,
sizeof(php_mb_default_identify_list_tr) /
sizeof(php_mb_default_identify_list_tr[0]) },
{ mbfl_no_language_neutral, php_mb_default_identify_list_neut,
sizeof(php_mb_default_identify_list_neut) /
sizeof(php_mb_default_identify_list_neut[0]) }
};
///////////////////////////////////////////////////////////////////////////////
// globals
typedef std::map<std::string, php_mb_regex_t *> RegexCache;
struct MBGlobals final : RequestEventHandler {
mbfl_no_language language;
mbfl_no_language current_language;
mbfl_encoding *internal_encoding;
mbfl_encoding *current_internal_encoding;
mbfl_encoding *http_output_encoding;
mbfl_encoding *current_http_output_encoding;
mbfl_encoding *http_input_identify;
mbfl_encoding *http_input_identify_get;
mbfl_encoding *http_input_identify_post;
mbfl_encoding *http_input_identify_cookie;
mbfl_encoding *http_input_identify_string;
mbfl_encoding **http_input_list;
int http_input_list_size;
mbfl_encoding **detect_order_list;
int detect_order_list_size;
mbfl_encoding **current_detect_order_list;
int current_detect_order_list_size;
mbfl_no_encoding *default_detect_order_list;
int default_detect_order_list_size;
int filter_illegal_mode;
int filter_illegal_substchar;
int current_filter_illegal_mode;
int current_filter_illegal_substchar;
bool encoding_translation;
long strict_detection;
long illegalchars;
mbfl_buffer_converter *outconv;
OnigEncoding default_mbctype;
OnigEncoding current_mbctype;
RegexCache ht_rc;
std::string search_str;
unsigned int search_pos;
php_mb_regex_t *search_re;
OnigRegion *search_regs;
OnigOptionType regex_default_options;
OnigSyntaxType *regex_default_syntax;
MBGlobals() :
language(mbfl_no_language_uni),
current_language(mbfl_no_language_uni),
internal_encoding((mbfl_encoding*) mbfl_no2encoding(mbfl_no_encoding_utf8)),
current_internal_encoding(internal_encoding),
http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass),
current_http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass),
http_input_identify(nullptr),
http_input_identify_get(nullptr),
http_input_identify_post(nullptr),
http_input_identify_cookie(nullptr),
http_input_identify_string(nullptr),
http_input_list(nullptr),
http_input_list_size(0),
detect_order_list(nullptr),
detect_order_list_size(0),
current_detect_order_list(nullptr),
current_detect_order_list_size(0),
default_detect_order_list
((mbfl_no_encoding *)php_mb_default_identify_list_neut),
default_detect_order_list_size
(sizeof(php_mb_default_identify_list_neut) /
sizeof(php_mb_default_identify_list_neut[0])),
filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR),
filter_illegal_substchar(0x3f), /* '?' */
current_filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR),
current_filter_illegal_substchar(0x3f), /* '?' */
encoding_translation(0),
strict_detection(0),
illegalchars(0),
outconv(nullptr),
default_mbctype(ONIG_ENCODING_UTF8),
current_mbctype(ONIG_ENCODING_UTF8),
search_pos(0),
search_re((php_mb_regex_t*)nullptr),
search_regs((OnigRegion*)nullptr),
regex_default_options(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE),
regex_default_syntax(ONIG_SYNTAX_RUBY) {
}
void requestInit() override {
current_language = language;
current_internal_encoding = internal_encoding;
current_http_output_encoding = http_output_encoding;
current_filter_illegal_mode = filter_illegal_mode;
current_filter_illegal_substchar = filter_illegal_substchar;
if (!encoding_translation) {
illegalchars = 0;
}
mbfl_encoding **entry = nullptr;
int n = 0;
if (current_detect_order_list) {
return;
}
if (detect_order_list && detect_order_list_size > 0) {
n = detect_order_list_size;
entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*));
std::copy(detect_order_list,
detect_order_list + (n * sizeof(mbfl_encoding*)), entry);
} else {
mbfl_no_encoding *src = default_detect_order_list;
n = default_detect_order_list_size;
entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*));
for (int i = 0; i < n; i++) {
entry[i] = (mbfl_encoding*) mbfl_no2encoding(src[i]);
}
}
current_detect_order_list = entry;
current_detect_order_list_size = n;
}
void requestShutdown() override {
if (current_detect_order_list != nullptr) {
req::free(current_detect_order_list);
current_detect_order_list = nullptr;
current_detect_order_list_size = 0;
}
if (outconv != nullptr) {
illegalchars += mbfl_buffer_illegalchars(outconv);
mbfl_buffer_converter_delete(outconv);
outconv = nullptr;
}
/* clear http input identification. */
http_input_identify = nullptr;
http_input_identify_post = nullptr;
http_input_identify_get = nullptr;
http_input_identify_cookie = nullptr;
http_input_identify_string = nullptr;
current_mbctype = default_mbctype;
search_str.clear();
search_pos = 0;
if (search_regs != nullptr) {
onig_region_free(search_regs, 1);
search_regs = (OnigRegion *)nullptr;
}
for (RegexCache::const_iterator it = ht_rc.begin(); it != ht_rc.end();
++it) {
onig_free(it->second);
}
ht_rc.clear();
}
};
IMPLEMENT_STATIC_REQUEST_LOCAL(MBGlobals, s_mb_globals);
#define MBSTRG(name) s_mb_globals->name
///////////////////////////////////////////////////////////////////////////////
// unicode functions
/*
* A simple array of 32-bit masks for lookup.
*/
static unsigned long masks32[32] = {
0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020,
0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800,
0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000,
0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000,
0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000,
0x40000000, 0x80000000
};
static int prop_lookup(unsigned long code, unsigned long n) {
long l, r, m;
/*
* There is an extra node on the end of the offsets to allow this routine
* to work right. If the index is 0xffff, then there are no nodes for the
* property.
*/
if ((l = _ucprop_offsets[n]) == 0xffff)
return 0;
/*
* Locate the next offset that is not 0xffff. The sentinel at the end of
* the array is the max index value.
*/
for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++)
;
r = _ucprop_offsets[n + m] - 1;
while (l <= r) {
/*
* Determine a "mid" point and adjust to make sure the mid point is at
* the beginning of a range pair.
*/
m = (l + r) >> 1;
m -= (m & 1);
if (code > _ucprop_ranges[m + 1])
l = m + 2;
else if (code < _ucprop_ranges[m])
r = m - 2;
else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1])
return 1;
}
return 0;
}
static int php_unicode_is_prop(unsigned long code, unsigned long mask1,
unsigned long mask2) {
unsigned long i;
if (mask1 == 0 && mask2 == 0)
return 0;
for (i = 0; mask1 && i < 32; i++) {
if ((mask1 & masks32[i]) && prop_lookup(code, i))
return 1;
}
for (i = 32; mask2 && i < _ucprop_size; i++) {
if ((mask2 & masks32[i & 31]) && prop_lookup(code, i))
return 1;
}
return 0;
}
static unsigned long case_lookup(unsigned long code, long l, long r,
int field) {
long m;
/*
* Do the binary search.
*/
while (l <= r) {
/*
* Determine a "mid" point and adjust to make sure the mid point is at
* the beginning of a case mapping triple.
*/
m = (l + r) >> 1;
m -= (m % 3);
if (code > _uccase_map[m])
l = m + 3;
else if (code < _uccase_map[m])
r = m - 3;
else if (code == _uccase_map[m])
return _uccase_map[m + field];
}
return code;
}
static unsigned long php_turkish_toupper(unsigned long code, long l, long r,
int field) {
if (code == 0x0069L) {
return 0x0130L;
}
return case_lookup(code, l, r, field);
}
static unsigned long php_turkish_tolower(unsigned long code, long l, long r,
int field) {
if (code == 0x0049L) {
return 0x0131L;
}
return case_lookup(code, l, r, field);
}
static unsigned long php_unicode_toupper(unsigned long code,
enum mbfl_no_encoding enc) {
int field;
long l, r;
if (php_unicode_is_upper(code))
return code;
if (php_unicode_is_lower(code)) {
/*
* The character is lower case.
*/
field = 2;
l = _uccase_len[0];
r = (l + _uccase_len[1]) - 3;
if (enc == mbfl_no_encoding_8859_9) {
return php_turkish_toupper(code, l, r, field);
}
} else {
/*
* The character is title case.
*/
field = 1;
l = _uccase_len[0] + _uccase_len[1];
r = _uccase_size - 3;
}
return case_lookup(code, l, r, field);
}
static unsigned long php_unicode_tolower(unsigned long code,
enum mbfl_no_encoding enc) {
int field;
long l, r;
if (php_unicode_is_lower(code))
return code;
if (php_unicode_is_upper(code)) {
/*
* The character is upper case.
*/
field = 1;
l = 0;
r = _uccase_len[0] - 3;
if (enc == mbfl_no_encoding_8859_9) {
return php_turkish_tolower(code, l, r, field);
}
} else {
/*
* The character is title case.
*/
field = 2;
l = _uccase_len[0] + _uccase_len[1];
r = _uccase_size - 3;
}
return case_lookup(code, l, r, field);
}
static unsigned long
php_unicode_totitle(unsigned long code, enum mbfl_no_encoding /*enc*/) {
int field;
long l, r;
if (php_unicode_is_title(code))
return code;
/*
* The offset will always be the same for converting to title case.
*/
field = 2;
if (php_unicode_is_upper(code)) {
/*
* The character is upper case.
*/
l = 0;
r = _uccase_len[0] - 3;
} else {
/*
* The character is lower case.
*/
l = _uccase_len[0];
r = (l + _uccase_len[1]) - 3;
}
return case_lookup(code, l, r, field);
}
#define BE_ARY_TO_UINT32(ptr) (\
((unsigned char*)(ptr))[0]<<24 |\
((unsigned char*)(ptr))[1]<<16 |\
((unsigned char*)(ptr))[2]<< 8 |\
((unsigned char*)(ptr))[3] )
#define UINT32_TO_BE_ARY(ptr,val) { \
unsigned int v = val; \
((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\
((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\
((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\
((unsigned char*)(ptr))[3] = (v ) & 0xff;\
}
/**
* Return 0 if input contains any illegal encoding, otherwise 1.
* Even if any illegal encoding is detected the result may contain a list
* of parsed encodings.
*/
static int php_mb_parse_encoding_list(const char* value, int value_length,
mbfl_encoding*** return_list,
int* return_size, int /*persistent*/) {
int n, l, size, bauto, ret = 1;
char *p, *p1, *p2, *endp, *tmpstr;
mbfl_encoding *encoding;
mbfl_no_encoding *src;
mbfl_encoding **entry, **list;
list = nullptr;
if (value == nullptr || value_length <= 0) {
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
return 0;
} else {
mbfl_no_encoding *identify_list;
int identify_list_size;
identify_list = MBSTRG(default_detect_order_list);
identify_list_size = MBSTRG(default_detect_order_list_size);
/* copy the value string for work */
if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) {
tmpstr = req::strndup(value + 1, value_length - 2);
} else {
tmpstr = req::strndup(value, value_length);
}
value_length = tmpstr ? strlen(tmpstr) : 0;
if (!value_length) {
req::free(tmpstr);
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
return 0;
}
/* count the number of listed encoding names */
endp = tmpstr + value_length;
n = 1;
p1 = tmpstr;
while ((p2 = (char*)string_memnstr(p1, ",", 1, endp)) != nullptr) {
p1 = p2 + 1;
n++;
}
size = n + identify_list_size;
/* make list */
list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*));
if (list != nullptr) {
entry = list;
n = 0;
bauto = 0;
p1 = tmpstr;
do {
p2 = p = (char*)string_memnstr(p1, ",", 1, endp);
if (p == nullptr) {
p = endp;
}
*p = '\0';
/* trim spaces */
while (p1 < p && (*p1 == ' ' || *p1 == '\t')) {
p1++;
}
p--;
while (p > p1 && (*p == ' ' || *p == '\t')) {
*p = '\0';
p--;
}
/* convert to the encoding number and check encoding */
if (strcasecmp(p1, "auto") == 0) {
if (!bauto) {
bauto = 1;
l = identify_list_size;
src = identify_list;
for (int i = 0; i < l; i++) {
*entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++);
n++;
}
}
} else {
encoding = (mbfl_encoding*) mbfl_name2encoding(p1);
if (encoding != nullptr) {
*entry++ = encoding;
n++;
} else {
ret = 0;
}
}
p1 = p2 + 1;
} while (n < size && p2 != nullptr);
if (n > 0) {
if (return_list) {
*return_list = list;
} else {
req::free(list);
}
} else {
req::free(list);
if (return_list) {
*return_list = nullptr;
}
ret = 0;
}
if (return_size) {
*return_size = n;
}
} else {
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
ret = 0;
}
req::free(tmpstr);
}
return ret;
}
static char *php_mb_convert_encoding(const char *input, size_t length,
const char *_to_encoding,
const char *_from_encodings,
unsigned int *output_len) {
mbfl_string string, result, *ret;
mbfl_encoding *from_encoding, *to_encoding;
mbfl_buffer_converter *convd;
int size;
mbfl_encoding **list;
char *output = nullptr;
if (output_len) {
*output_len = 0;
}
if (!input) {
return nullptr;
}
/* new encoding */
if (_to_encoding && strlen(_to_encoding)) {
to_encoding = (mbfl_encoding*) mbfl_name2encoding(_to_encoding);
if (to_encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", _to_encoding);
return nullptr;
}
} else {
to_encoding = MBSTRG(current_internal_encoding);
}
/* initialize string */
mbfl_string_init(&string);
mbfl_string_init(&result);
from_encoding = MBSTRG(current_internal_encoding);
string.no_encoding = from_encoding->no_encoding;
string.no_language = MBSTRG(current_language);
string.val = (unsigned char *)input;
string.len = length;
/* pre-conversion encoding */
if (_from_encodings) {
list = nullptr;
size = 0;
php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings),
&list, &size, 0);
if (size == 1) {
from_encoding = *list;
string.no_encoding = from_encoding->no_encoding;
} else if (size > 1) {
/* auto detect */
from_encoding = (mbfl_encoding*) mbfl_identify_encoding2(&string,
(const mbfl_encoding**) list,
size, MBSTRG(strict_detection));
if (from_encoding != nullptr) {
string.no_encoding = from_encoding->no_encoding;
} else {
raise_warning("Unable to detect character encoding");
from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
to_encoding = from_encoding;
string.no_encoding = from_encoding->no_encoding;
}
} else {
raise_warning("Illegal character encoding specified");
}
if (list != nullptr) {
req::free(list);
}
}
/* initialize converter */
convd = mbfl_buffer_converter_new2(from_encoding, to_encoding, string.len);
if (convd == nullptr) {
raise_warning("Unable to create character encoding converter");
return nullptr;
}
mbfl_buffer_converter_illegal_mode
(convd, MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(convd, MBSTRG(current_filter_illegal_substchar));
/* do it */
ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
if (ret) {
if (output_len) {
*output_len = ret->len;
}
output = (char *)ret->val;
}
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
return output;
}
static char *php_unicode_convert_case(int case_mode, const char *srcstr,
size_t srclen, unsigned int *ret_len,
const char *src_encoding) {
char *unicode, *newstr;
unsigned int unicode_len;
unsigned char *unicode_ptr;
size_t i;
enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding);
unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding,
&unicode_len);
if (unicode == nullptr)
return nullptr;
unicode_ptr = (unsigned char *)unicode;
switch(case_mode) {
case PHP_UNICODE_CASE_UPPER:
for (i = 0; i < unicode_len; i+=4) {
UINT32_TO_BE_ARY(&unicode_ptr[i],
php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
}
break;
case PHP_UNICODE_CASE_LOWER:
for (i = 0; i < unicode_len; i+=4) {
UINT32_TO_BE_ARY(&unicode_ptr[i],
php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
}
break;
case PHP_UNICODE_CASE_TITLE:
{
int mode = 0;
for (i = 0; i < unicode_len; i+=4) {
int res = php_unicode_is_prop
(BE_ARY_TO_UINT32(&unicode_ptr[i]),
UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0);
if (mode) {
if (res) {
UINT32_TO_BE_ARY
(&unicode_ptr[i],
php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
} else {
mode = 0;
}
} else {
if (res) {
mode = 1;
UINT32_TO_BE_ARY
(&unicode_ptr[i],
php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]),
_src_encoding));
}
}
}
}
break;
}
newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding,
"UCS-4BE", ret_len);
free(unicode);
return newstr;
}
///////////////////////////////////////////////////////////////////////////////
// helpers
/**
* Return 0 if input contains any illegal encoding, otherwise 1.
* Even if any illegal encoding is detected the result may contain a list
* of parsed encodings.
*/
static int
php_mb_parse_encoding_array(const Array& array, mbfl_encoding*** return_list,
int* return_size, int /*persistent*/) {
int n, l, size, bauto,ret = 1;
mbfl_encoding *encoding;
mbfl_no_encoding *src;
mbfl_encoding **list, **entry;
list = nullptr;
mbfl_no_encoding *identify_list = MBSTRG(default_detect_order_list);
int identify_list_size = MBSTRG(default_detect_order_list_size);
size = array.size() + identify_list_size;
list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*));
if (list != nullptr) {
entry = list;
bauto = 0;
n = 0;
for (ArrayIter iter(array); iter; ++iter) {
auto const hash_entry = iter.second().toString();
if (strcasecmp(hash_entry.data(), "auto") == 0) {
if (!bauto) {
bauto = 1;
l = identify_list_size;
src = identify_list;
for (int j = 0; j < l; j++) {
*entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++);
n++;
}
}
} else {
encoding = (mbfl_encoding*) mbfl_name2encoding(hash_entry.data());
if (encoding != nullptr) {
*entry++ = encoding;
n++;
} else {
ret = 0;
}
}
}
if (n > 0) {
if (return_list) {
*return_list = list;
} else {
req::free(list);
}
} else {
req::free(list);
if (return_list) {
*return_list = nullptr;
}
ret = 0;
}
if (return_size) {
*return_size = n;
}
} else {
if (return_list) {
*return_list = nullptr;
}
if (return_size) {
*return_size = 0;
}
ret = 0;
}
return ret;
}
static bool php_mb_parse_encoding(const Variant& encoding,
mbfl_encoding ***return_list,
int *return_size, bool persistent) {
bool ret;
if (encoding.isArray()) {
ret = php_mb_parse_encoding_array(encoding.toArray(),
return_list, return_size,
persistent ? 1 : 0);
} else {
String enc = encoding.toString();
ret = php_mb_parse_encoding_list(enc.data(), enc.size(),
return_list, return_size,
persistent ? 1 : 0);
}
if (!ret) {
if (return_list && *return_list) {
req::free(*return_list);
*return_list = nullptr;
}
return_size = 0;
}
return ret;
}
static int php_mb_nls_get_default_detect_order_list(mbfl_no_language lang,
mbfl_no_encoding **plist,
int* plist_size) {
size_t i;
*plist = (mbfl_no_encoding *) php_mb_default_identify_list_neut;
*plist_size = sizeof(php_mb_default_identify_list_neut) /
sizeof(php_mb_default_identify_list_neut[0]);
for (i = 0; i < sizeof(php_mb_default_identify_list) /
sizeof(php_mb_default_identify_list[0]); i++) {
if (php_mb_default_identify_list[i].lang == lang) {
*plist = php_mb_default_identify_list[i].list;
*plist_size = php_mb_default_identify_list[i].list_size;
return 1;
}
}
return 0;
}
static size_t php_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc) {
if (enc != nullptr) {
if (enc->flag & MBFL_ENCTYPE_MBCS) {
if (enc->mblen_table != nullptr) {
if (s != nullptr) return enc->mblen_table[*(unsigned char *)s];
}
} else if (enc->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) {
return 2;
} else if (enc->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) {
return 4;
}
}
return 1;
}
static int php_mb_stripos(int mode,
const char *old_haystack, int old_haystack_len,
const char *old_needle, int old_needle_len,
long offset, const char *from_encoding) {
int n;
mbfl_string haystack, needle;
n = -1;
mbfl_string_init(&haystack);
mbfl_string_init(&needle);
haystack.no_language = MBSTRG(current_language);
haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
needle.no_language = MBSTRG(current_language);
needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
do {
haystack.val = (unsigned char *)php_unicode_convert_case
(PHP_UNICODE_CASE_UPPER, old_haystack, (size_t)old_haystack_len,
&haystack.len, from_encoding);
if (!haystack.val) {
break;
}
if (haystack.len <= 0) {
break;
}
needle.val = (unsigned char *)php_unicode_convert_case
(PHP_UNICODE_CASE_UPPER, old_needle, (size_t)old_needle_len,
&needle.len, from_encoding);
if (!needle.val) {
break;
}
if (needle.len <= 0) {
break;
}
haystack.no_encoding = needle.no_encoding =
mbfl_name2no_encoding(from_encoding);
if (haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", from_encoding);
break;
}
int haystack_char_len = mbfl_strlen(&haystack);
if (mode) {
if ((offset > 0 && offset > haystack_char_len) ||
(offset < 0 && -offset > haystack_char_len)) {
raise_warning("Offset is greater than the length of haystack string");
break;
}
} else {
if (offset < 0 || offset > haystack_char_len) {
raise_warning("Offset not contained in string.");
break;
}
}
n = mbfl_strpos(&haystack, &needle, offset, mode);
} while(0);
if (haystack.val) {
free(haystack.val);
}
if (needle.val) {
free(needle.val);
}
return n;
}
///////////////////////////////////////////////////////////////////////////////
static String convertArg(const Variant& arg) {
return arg.isNull() ? null_string : arg.toString();
}
Array HHVM_FUNCTION(mb_list_encodings) {
Array ret;
int i = 0;
const mbfl_encoding **encodings = mbfl_get_supported_encodings();
const mbfl_encoding *encoding;
while ((encoding = encodings[i++]) != nullptr) {
ret.append(String(encoding->name, CopyString));
}
return ret;
}
Variant HHVM_FUNCTION(mb_encoding_aliases, const String& name) {
const mbfl_encoding *encoding;
int i = 0;
encoding = mbfl_name2encoding(name.data());
if (!encoding) {
raise_warning("mb_encoding_aliases(): Unknown encoding \"%s\"",
name.data());
return false;
}
Array ret = Array::Create();
if (encoding->aliases != nullptr) {
while ((*encoding->aliases)[i] != nullptr) {
ret.append((*encoding->aliases)[i]);
i++;
}
}
return ret;
}
Variant HHVM_FUNCTION(mb_list_encodings_alias_names,
const Variant& opt_name) {
const String name = convertArg(opt_name);
const mbfl_encoding **encodings;
const mbfl_encoding *encoding;
mbfl_no_encoding no_encoding;
int i, j;
Array ret;
if (name.isNull()) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
Array row;
if (encoding->aliases != nullptr) {
j = 0;
while ((*encoding->aliases)[j] != nullptr) {
row.append(String((*encoding->aliases)[j], CopyString));
j++;
}
}
ret.set(String(encoding->name, CopyString), row);
}
} else {
no_encoding = mbfl_name2no_encoding(name.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", name.data());
return false;
}
char *encodingName = (char *)mbfl_no_encoding2name(no_encoding);
if (encodingName != nullptr) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
if (strcmp(encoding->name, encodingName) != 0) continue;
if (encoding->aliases != nullptr) {
j = 0;
while ((*encoding->aliases)[j] != nullptr) {
ret.append(String((*encoding->aliases)[j], CopyString));
j++;
}
}
break;
}
} else {
return false;
}
}
return ret;
}
Variant HHVM_FUNCTION(mb_list_mime_names,
const Variant& opt_name) {
const String name = convertArg(opt_name);
const mbfl_encoding **encodings;
const mbfl_encoding *encoding;
mbfl_no_encoding no_encoding;
int i;
Array ret;
if (name.isNull()) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
if (encoding->mime_name != nullptr) {
ret.set(String(encoding->name, CopyString),
String(encoding->mime_name, CopyString));
} else{
ret.set(String(encoding->name, CopyString), "");
}
}
} else {
no_encoding = mbfl_name2no_encoding(name.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", name.data());
return false;
}
char *encodingName = (char *)mbfl_no_encoding2name(no_encoding);
if (encodingName != nullptr) {
i = 0;
encodings = mbfl_get_supported_encodings();
while ((encoding = encodings[i++]) != nullptr) {
if (strcmp(encoding->name, encodingName) != 0) continue;
if (encoding->mime_name != nullptr) {
return String(encoding->mime_name, CopyString);
}
break;
}
return empty_string_variant();
} else {
return false;
}
}
return ret;
}
bool HHVM_FUNCTION(mb_check_encoding,
const Variant& opt_var,
const Variant& opt_encoding) {
const String var = convertArg(opt_var);
const String encoding = convertArg(opt_encoding);
mbfl_buffer_converter *convd;
mbfl_no_encoding no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbfl_string string, result, *ret = nullptr;
long illegalchars = 0;
if (var.isNull()) {
return MBSTRG(illegalchars) == 0;
}
if (!encoding.isNull()) {
no_encoding = mbfl_name2no_encoding(encoding.data());
if (no_encoding == mbfl_no_encoding_invalid ||
no_encoding == mbfl_no_encoding_pass) {
raise_warning("Invalid encoding \"%s\"", encoding.data());
return false;
}
}
convd = mbfl_buffer_converter_new(no_encoding, no_encoding, 0);
if (convd == nullptr) {
raise_warning("Unable to create converter");
return false;
}
mbfl_buffer_converter_illegal_mode
(convd, MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE);
mbfl_buffer_converter_illegal_substchar
(convd, 0);
/* initialize string */
mbfl_string_init_set(&string, mbfl_no_language_neutral, no_encoding);
mbfl_string_init(&result);
string.val = (unsigned char *)var.data();
string.len = var.size();
ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
illegalchars = mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
if (ret != nullptr) {
MBSTRG(illegalchars) += illegalchars;
if (illegalchars == 0 && string.len == ret->len &&
memcmp((const char *)string.val, (const char *)ret->val,
string.len) == 0) {
mbfl_string_clear(&result);
return true;
} else {
mbfl_string_clear(&result);
return false;
}
} else {
return false;
}
}
Variant HHVM_FUNCTION(mb_convert_case,
const String& str,
int mode,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
const char *enc = nullptr;
if (encoding.empty()) {
enc = MBSTRG(current_internal_encoding)->mime_name;
} else {
enc = encoding.data();
}
unsigned int ret_len;
char *newstr = php_unicode_convert_case(mode, str.data(), str.size(),
&ret_len, enc);
if (newstr) {
return String(newstr, ret_len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_convert_encoding,
const String& str,
const String& to_encoding,
const Variant& from_encoding /* = uninit_variant */) {
String encoding = from_encoding.toString();
if (from_encoding.isArray()) {
StringBuffer _from_encodings;
Array encs = from_encoding.toArray();
for (ArrayIter iter(encs); iter; ++iter) {
if (!_from_encodings.empty()) {
_from_encodings.append(",");
}
_from_encodings.append(iter.second().toString());
}
encoding = _from_encodings.detach();
}
unsigned int size;
char *ret = php_mb_convert_encoding(str.data(), str.size(),
to_encoding.data(),
(!encoding.empty() ?
encoding.data() : nullptr),
&size);
if (ret != nullptr) {
return String(ret, size, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_convert_kana,
const String& str,
const Variant& opt_option,
const Variant& opt_encoding) {
const String option = convertArg(opt_option);
const String encoding = convertArg(opt_encoding);
mbfl_string string, result, *ret;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
int opt = 0x900;
if (!option.empty()) {
const char *p = option.data();
int n = option.size();
int i = 0;
opt = 0;
while (i < n) {
i++;
switch (*p++) {
case 'A': opt |= 0x1; break;
case 'a': opt |= 0x10; break;
case 'R': opt |= 0x2; break;
case 'r': opt |= 0x20; break;
case 'N': opt |= 0x4; break;
case 'n': opt |= 0x40; break;
case 'S': opt |= 0x8; break;
case 's': opt |= 0x80; break;
case 'K': opt |= 0x100; break;
case 'k': opt |= 0x1000; break;
case 'H': opt |= 0x200; break;
case 'h': opt |= 0x2000; break;
case 'V': opt |= 0x800; break;
case 'C': opt |= 0x10000; break;
case 'c': opt |= 0x20000; break;
case 'M': opt |= 0x100000; break;
case 'm': opt |= 0x200000; break;
}
}
}
/* encoding */
if (!encoding.empty()) {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
ret = mbfl_ja_jp_hantozen(&string, &result, opt);
if (ret != nullptr) {
if (ret->len > StringData::MaxSize) {
raise_warning("String too long, max is %d", StringData::MaxSize);
return false;
}
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
static bool php_mbfl_encoding_detect(const Variant& var,
mbfl_encoding_detector *identd,
mbfl_string *string) {
if (var.isArray() || var.is(KindOfObject)) {
Array items = var.toArray();
for (ArrayIter iter(items); iter; ++iter) {
if (php_mbfl_encoding_detect(iter.second(), identd, string)) {
return true;
}
}
} else if (var.isString()) {
String svar = var.toString();
string->val = (unsigned char *)svar.data();
string->len = svar.size();
if (mbfl_encoding_detector_feed(identd, string)) {
return true;
}
}
return false;
}
static Variant php_mbfl_convert(const Variant& var,
mbfl_buffer_converter *convd,
mbfl_string *string,
mbfl_string *result) {
if (var.isArray()) {
Array ret = empty_array();
Array items = var.toArray();
for (ArrayIter iter(items); iter; ++iter) {
ret.set(iter.first(),
php_mbfl_convert(iter.second(), convd, string, result));
}
return ret;
}
if (var.is(KindOfObject)) {
Object obj = var.toObject();
Array items = var.toArray();
for (ArrayIter iter(items); iter; ++iter) {
obj->o_set(iter.first().toString(),
php_mbfl_convert(iter.second(), convd, string, result));
}
return var; // which still has obj
}
if (var.isString()) {
String svar = var.toString();
string->val = (unsigned char *)svar.data();
string->len = svar.size();
mbfl_string *ret =
mbfl_buffer_converter_feed_result(convd, string, result);
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return var;
}
Variant HHVM_FUNCTION(mb_convert_variables,
const String& to_encoding,
const Variant& from_encoding,
Variant& vars,
const Array& args /* = null_array */) {
mbfl_string string, result;
mbfl_encoding *_from_encoding, *_to_encoding;
mbfl_encoding_detector *identd;
mbfl_buffer_converter *convd;
int elistsz;
mbfl_encoding **elist;
char *name;
/* new encoding */
_to_encoding = (mbfl_encoding*) mbfl_name2encoding(to_encoding.data());
if (_to_encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", to_encoding.data());
return false;
}
/* initialize string */
mbfl_string_init(&string);
mbfl_string_init(&result);
_from_encoding = MBSTRG(current_internal_encoding);
string.no_encoding = _from_encoding->no_encoding;
string.no_language = MBSTRG(current_language);
/* pre-conversion encoding */
elist = nullptr;
elistsz = 0;
php_mb_parse_encoding(from_encoding, &elist, &elistsz, false);
if (elistsz <= 0) {
_from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
} else if (elistsz == 1) {
_from_encoding = *elist;
} else {
/* auto detect */
_from_encoding = nullptr;
identd = mbfl_encoding_detector_new2((const mbfl_encoding**) elist, elistsz,
MBSTRG(strict_detection));
if (identd != nullptr) {
for (int n = -1; n < args.size(); n++) {
if (php_mbfl_encoding_detect(n < 0 ? vars : args[n],
identd, &string)) {
break;
}
}
_from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd);
mbfl_encoding_detector_delete(identd);
}
if (_from_encoding == nullptr) {
raise_warning("Unable to detect encoding");
_from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
}
}
if (elist != nullptr) {
req::free(elist);
}
/* create converter */
convd = nullptr;
if (_from_encoding != &mbfl_encoding_pass) {
convd = mbfl_buffer_converter_new2(_from_encoding, _to_encoding, 0);
if (convd == nullptr) {
raise_warning("Unable to create converter");
return false;
}
mbfl_buffer_converter_illegal_mode
(convd, MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(convd, MBSTRG(current_filter_illegal_substchar));
}
/* convert */
if (convd != nullptr) {
vars = php_mbfl_convert(vars, convd, &string, &result);
for (int n = 0; n < args.size(); n++) {
const_cast<Array&>(args).set(n, php_mbfl_convert(args[n], convd,
&string, &result));
}
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
}
if (_from_encoding != nullptr) {
name = (char*) _from_encoding->name;
if (name != nullptr) {
return String(name, CopyString);
}
}
return false;
}
Variant HHVM_FUNCTION(mb_decode_mimeheader,
const String& str) {
mbfl_string string, result, *ret;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
mbfl_string_init(&result);
ret = mbfl_mime_header_decode(&string, &result,
MBSTRG(current_internal_encoding)->no_encoding);
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
static Variant php_mb_numericentity_exec(const String& str,
const Variant& convmap,
const String& encoding,
bool is_hex, int type) {
int mapsize=0;
mbfl_string string, result, *ret;
mbfl_no_encoding no_encoding;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
if (type == 0 && is_hex) {
type = 2; /* output in hex format */
}
/* encoding */
if (!encoding.empty()) {
no_encoding = mbfl_name2no_encoding(encoding.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
} else {
string.no_encoding = no_encoding;
}
}
/* conversion map */
int *iconvmap = nullptr;
if (convmap.isArray()) {
Array convs = convmap.toArray();
mapsize = convs.size();
if (mapsize > 0) {
iconvmap = (int*)req::malloc_noptrs(mapsize * sizeof(int));
int *mapelm = iconvmap;
for (ArrayIter iter(convs); iter; ++iter) {
*mapelm++ = iter.second().toInt32();
}
}
}
if (iconvmap == nullptr) {
return false;
}
mapsize /= 4;
ret = mbfl_html_numeric_entity(&string, &result, iconvmap, mapsize, type);
req::free(iconvmap);
if (ret != nullptr) {
if (ret->len > StringData::MaxSize) {
raise_warning("String too long, max is %d", StringData::MaxSize);
return false;
}
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_decode_numericentity,
const String& str,
const Variant& convmap,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
return php_mb_numericentity_exec(str, convmap, encoding, false, 1);
}
Variant HHVM_FUNCTION(mb_detect_encoding,
const String& str,
const Variant& encoding_list /* = uninit_variant */,
const Variant& strict /* = uninit_variant */) {
mbfl_string string;
mbfl_encoding *ret;
mbfl_encoding **elist, **list;
int size;
/* make encoding list */
list = nullptr;
size = 0;
php_mb_parse_encoding(encoding_list, &list, &size, false);
if (size > 0 && list != nullptr) {
elist = list;
} else {
elist = MBSTRG(current_detect_order_list);
size = MBSTRG(current_detect_order_list_size);
}
long nstrict = 0;
if (!strict.isNull()) {
nstrict = strict.toInt64();
} else {
nstrict = MBSTRG(strict_detection);
}
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.val = (unsigned char *)str.data();
string.len = str.size();
ret = (mbfl_encoding*) mbfl_identify_encoding2(&string,
(const mbfl_encoding**) elist,
size, nstrict);
req::free(list);
if (ret != nullptr) {
return String(ret->name, CopyString);
}
return false;
}
Variant HHVM_FUNCTION(mb_detect_order,
const Variant& encoding_list /* = uninit_variant */) {
int n, size;
mbfl_encoding **list, **entry;
if (encoding_list.isNull()) {
Array ret;
entry = MBSTRG(current_detect_order_list);
n = MBSTRG(current_detect_order_list_size);
while (n > 0) {
char *name = (char*) (*entry)->name;
if (name) {
ret.append(String(name, CopyString));
}
entry++;
n--;
}
return ret;
}
list = nullptr;
size = 0;
if (!php_mb_parse_encoding(encoding_list, &list, &size, false) ||
list == nullptr) {
return false;
}
if (MBSTRG(current_detect_order_list)) {
req::free(MBSTRG(current_detect_order_list));
}
MBSTRG(current_detect_order_list) = list;
MBSTRG(current_detect_order_list_size) = size;
return true;
}
Variant HHVM_FUNCTION(mb_encode_mimeheader,
const String& str,
const Variant& opt_charset,
const Variant& opt_transfer_encoding,
const String& linefeed /* = "\r\n" */,
int indent /* = 0 */) {
const String charset = convertArg(opt_charset);
const String transfer_encoding = convertArg(opt_transfer_encoding);
mbfl_no_encoding charsetenc, transenc;
mbfl_string string, result, *ret;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
charsetenc = mbfl_no_encoding_pass;
transenc = mbfl_no_encoding_base64;
if (!charset.empty()) {
charsetenc = mbfl_name2no_encoding(charset.data());
if (charsetenc == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", charset.data());
return false;
}
} else {
const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language));
if (lang != nullptr) {
charsetenc = lang->mail_charset;
transenc = lang->mail_header_encoding;
}
}
if (!transfer_encoding.empty()) {
char ch = *transfer_encoding.data();
if (ch == 'B' || ch == 'b') {
transenc = mbfl_no_encoding_base64;
} else if (ch == 'Q' || ch == 'q') {
transenc = mbfl_no_encoding_qprint;
}
}
mbfl_string_init(&result);
ret = mbfl_mime_header_encode(&string, &result, charsetenc, transenc,
linefeed.data(), indent);
if (ret != nullptr) {
if (ret->len > StringData::MaxSize) {
raise_warning("String too long, max is %d", StringData::MaxSize);
return false;
}
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_encode_numericentity,
const String& str,
const Variant& convmap,
const Variant& opt_encoding /* = uninit_variant */,
bool is_hex /* = false */) {
const String encoding = convertArg(opt_encoding);
return php_mb_numericentity_exec(str, convmap, encoding, is_hex, 0);
}
const StaticString
s_internal_encoding("internal_encoding"),
s_http_input("http_input"),
s_http_output("http_output"),
s_mail_charset("mail_charset"),
s_mail_header_encoding("mail_header_encoding"),
s_mail_body_encoding("mail_body_encoding"),
s_illegal_chars("illegal_chars"),
s_encoding_translation("encoding_translation"),
s_On("On"),
s_Off("Off"),
s_language("language"),
s_detect_order("detect_order"),
s_substitute_character("substitute_character"),
s_strict_detection("strict_detection"),
s_none("none"),
s_long("long"),
s_entity("entity");
Variant HHVM_FUNCTION(mb_get_info,
const Variant& opt_type) {
const String type = convertArg(opt_type);
const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language));
mbfl_encoding **entry;
int n;
char *name;
if (type.empty() || strcasecmp(type.data(), "all") == 0) {
Array ret;
if (MBSTRG(current_internal_encoding) != nullptr &&
(name = (char *) MBSTRG(current_internal_encoding)->name) != nullptr) {
ret.set(s_internal_encoding, String(name, CopyString));
}
if (MBSTRG(http_input_identify) != nullptr &&
(name = (char *)MBSTRG(http_input_identify)->name) != nullptr) {
ret.set(s_http_input, String(name, CopyString));
}
if (MBSTRG(current_http_output_encoding) != nullptr &&
(name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) {
ret.set(s_http_output, String(name, CopyString));
}
if (lang != nullptr) {
if ((name = (char *)mbfl_no_encoding2name
(lang->mail_charset)) != nullptr) {
ret.set(s_mail_charset, String(name, CopyString));
}
if ((name = (char *)mbfl_no_encoding2name
(lang->mail_header_encoding)) != nullptr) {
ret.set(s_mail_header_encoding, String(name, CopyString));
}
if ((name = (char *)mbfl_no_encoding2name
(lang->mail_body_encoding)) != nullptr) {
ret.set(s_mail_body_encoding, String(name, CopyString));
}
}
ret.set(s_illegal_chars, MBSTRG(illegalchars));
ret.set(s_encoding_translation,
MBSTRG(encoding_translation) ? s_On : s_Off);
if ((name = (char *)mbfl_no_language2name
(MBSTRG(current_language))) != nullptr) {
ret.set(s_language, String(name, CopyString));
}
n = MBSTRG(current_detect_order_list_size);
entry = MBSTRG(current_detect_order_list);
if (n > 0) {
Array row;
while (n > 0) {
if ((name = (char *)(*entry)->name) != nullptr) {
row.append(String(name, CopyString));
}
entry++;
n--;
}
ret.set(s_detect_order, row);
}
switch (MBSTRG(current_filter_illegal_mode)) {
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE:
ret.set(s_substitute_character, s_none);
break;
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG:
ret.set(s_substitute_character, s_long);
break;
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY:
ret.set(s_substitute_character, s_entity);
break;
default:
ret.set(s_substitute_character,
MBSTRG(current_filter_illegal_substchar));
}
ret.set(s_strict_detection, MBSTRG(strict_detection) ? s_On : s_Off);
return ret;
} else if (strcasecmp(type.data(), "internal_encoding") == 0) {
if (MBSTRG(current_internal_encoding) != nullptr &&
(name = (char *)MBSTRG(current_internal_encoding)->name) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "http_input") == 0) {
if (MBSTRG(http_input_identify) != nullptr &&
(name = (char *)MBSTRG(http_input_identify)->name) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "http_output") == 0) {
if (MBSTRG(current_http_output_encoding) != nullptr &&
(name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "mail_charset") == 0) {
if (lang != nullptr &&
(name = (char *)mbfl_no_encoding2name
(lang->mail_charset)) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "mail_header_encoding") == 0) {
if (lang != nullptr &&
(name = (char *)mbfl_no_encoding2name
(lang->mail_header_encoding)) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "mail_body_encoding") == 0) {
if (lang != nullptr &&
(name = (char *)mbfl_no_encoding2name
(lang->mail_body_encoding)) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "illegal_chars") == 0) {
return MBSTRG(illegalchars);
} else if (strcasecmp(type.data(), "encoding_translation") == 0) {
return MBSTRG(encoding_translation) ? "On" : "Off";
} else if (strcasecmp(type.data(), "language") == 0) {
if ((name = (char *)mbfl_no_language2name
(MBSTRG(current_language))) != nullptr) {
return String(name, CopyString);
}
} else if (strcasecmp(type.data(), "detect_order") == 0) {
n = MBSTRG(current_detect_order_list_size);
entry = MBSTRG(current_detect_order_list);
if (n > 0) {
Array ret;
while (n > 0) {
name = (char *)(*entry)->name;
if (name) {
ret.append(String(name, CopyString));
}
entry++;
n--;
}
}
} else if (strcasecmp(type.data(), "substitute_character") == 0) {
if (MBSTRG(current_filter_illegal_mode) ==
MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) {
return s_none;
} else if (MBSTRG(current_filter_illegal_mode) ==
MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) {
return s_long;
} else if (MBSTRG(current_filter_illegal_mode) ==
MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) {
return s_entity;
} else {
return MBSTRG(current_filter_illegal_substchar);
}
} else if (strcasecmp(type.data(), "strict_detection") == 0) {
return MBSTRG(strict_detection) ? s_On : s_Off;
}
return false;
}
Variant HHVM_FUNCTION(mb_http_input,
const Variant& opt_type) {
const String type = convertArg(opt_type);
int n;
char *name;
mbfl_encoding **entry;
mbfl_encoding *result = nullptr;
if (type.empty()) {
result = MBSTRG(http_input_identify);
} else {
switch (*type.data()) {
case 'G': case 'g': result = MBSTRG(http_input_identify_get); break;
case 'P': case 'p': result = MBSTRG(http_input_identify_post); break;
case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break;
case 'S': case 's': result = MBSTRG(http_input_identify_string); break;
case 'I': case 'i':
{
Array ret;
entry = MBSTRG(http_input_list);
n = MBSTRG(http_input_list_size);
while (n > 0) {
name = (char *)(*entry)->name;
if (name) {
ret.append(String(name, CopyString));
}
entry++;
n--;
}
return ret;
}
case 'L': case 'l':
{
entry = MBSTRG(http_input_list);
n = MBSTRG(http_input_list_size);
StringBuffer list;
while (n > 0) {
name = (char *)(*entry)->name;
if (name) {
if (list.empty()) {
list.append(name);
} else {
list.append(',');
list.append(name);
}
}
entry++;
n--;
}
if (list.empty()) {
return false;
}
return list.detach();
}
default:
result = MBSTRG(http_input_identify);
break;
}
}
if (result != nullptr &&
(name = (char *)(result)->name) != nullptr) {
return String(name, CopyString);
}
return false;
}
Variant HHVM_FUNCTION(mb_http_output,
const Variant& opt_encoding) {
const String encoding_name = convertArg(opt_encoding);
if (encoding_name.empty()) {
char *name = (char *)(MBSTRG(current_http_output_encoding)->name);
if (name != nullptr) {
return String(name, CopyString);
}
return false;
}
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_name2encoding(encoding_name.data());
if (encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", encoding_name.data());
return false;
}
MBSTRG(current_http_output_encoding) = encoding;
return true;
}
Variant HHVM_FUNCTION(mb_internal_encoding,
const Variant& opt_encoding) {
const String encoding_name = convertArg(opt_encoding);
if (encoding_name.empty()) {
char *name = (char *)(MBSTRG(current_internal_encoding)->name);
if (name != nullptr) {
return String(name, CopyString);
}
return false;
}
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_name2encoding(encoding_name.data());
if (encoding == nullptr) {
raise_warning("Unknown encoding \"%s\"", encoding_name.data());
return false;
}
MBSTRG(current_internal_encoding) = encoding;
return true;
}
Variant HHVM_FUNCTION(mb_language,
const Variant& opt_language) {
const String language = convertArg(opt_language);
if (language.empty()) {
return String(mbfl_no_language2name(MBSTRG(current_language)), CopyString);
}
mbfl_no_language no_language = mbfl_name2no_language(language.data());
if (no_language == mbfl_no_language_invalid) {
raise_warning("Unknown language \"%s\"", language.data());
return false;
}
php_mb_nls_get_default_detect_order_list
(no_language, &MBSTRG(default_detect_order_list),
&MBSTRG(default_detect_order_list_size));
MBSTRG(current_language) = no_language;
return true;
}
String HHVM_FUNCTION(mb_output_handler,
const String& contents,
int status) {
mbfl_string string, result;
int last_feed;
mbfl_encoding *encoding = MBSTRG(current_http_output_encoding);
/* start phase only */
if (status & k_PHP_OUTPUT_HANDLER_START) {
/* delete the converter just in case. */
if (MBSTRG(outconv)) {
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
mbfl_buffer_converter_delete(MBSTRG(outconv));
MBSTRG(outconv) = nullptr;
}
if (encoding == nullptr) {
return contents;
}
/* analyze mime type */
String mimetype = g_context->getMimeType();
if (!mimetype.empty()) {
const char *charset = encoding->mime_name;
if (charset) {
g_context->setContentType(mimetype, charset);
}
/* activate the converter */
MBSTRG(outconv) = mbfl_buffer_converter_new2
(MBSTRG(current_internal_encoding), encoding, 0);
}
}
/* just return if the converter is not activated. */
if (MBSTRG(outconv) == nullptr) {
return contents;
}
/* flag */
last_feed = ((status & k_PHP_OUTPUT_HANDLER_END) != 0);
/* mode */
mbfl_buffer_converter_illegal_mode
(MBSTRG(outconv), MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar));
/* feed the string */
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)contents.data();
string.len = contents.size();
mbfl_buffer_converter_feed(MBSTRG(outconv), &string);
if (last_feed) {
mbfl_buffer_converter_flush(MBSTRG(outconv));
}
/* get the converter output, and return it */
mbfl_buffer_converter_result(MBSTRG(outconv), &result);
/* delete the converter if it is the last feed. */
if (last_feed) {
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
mbfl_buffer_converter_delete(MBSTRG(outconv));
MBSTRG(outconv) = nullptr;
}
return String(reinterpret_cast<char*>(result.val), result.len, AttachString);
}
typedef struct _php_mb_encoding_handler_info_t {
int data_type;
const char *separator;
unsigned int force_register_globals: 1;
unsigned int report_errors: 1;
enum mbfl_no_language to_language;
mbfl_encoding *to_encoding;
enum mbfl_no_language from_language;
int num_from_encodings;
mbfl_encoding **from_encodings;
} php_mb_encoding_handler_info_t;
static mbfl_encoding* _php_mb_encoding_handler_ex
(const php_mb_encoding_handler_info_t *info, Array& arg, char *res) {
char *var, *val;
const char *s1, *s2;
char *strtok_buf = nullptr, **val_list = nullptr;
int n, num, *len_list = nullptr;
unsigned int val_len;
mbfl_string string, resvar, resval;
mbfl_encoding *from_encoding = nullptr;
mbfl_encoding_detector *identd = nullptr;
mbfl_buffer_converter *convd = nullptr;
mbfl_string_init_set(&string, info->to_language,
info->to_encoding->no_encoding);
mbfl_string_init_set(&resvar, info->to_language,
info->to_encoding->no_encoding);
mbfl_string_init_set(&resval, info->to_language,
info->to_encoding->no_encoding);
if (!res || *res == '\0') {
goto out;
}
/* count the variables(separators) contained in the "res".
* separator may contain multiple separator chars.
*/
num = 1;
for (s1=res; *s1 != '\0'; s1++) {
for (s2=info->separator; *s2 != '\0'; s2++) {
if (*s1 == *s2) {
num++;
}
}
}
num *= 2; /* need space for variable name and value */
val_list = (char **)req::calloc_noptrs(num, sizeof(char *));
len_list = (int *)req::calloc_noptrs(num, sizeof(int));
/* split and decode the query */
n = 0;
strtok_buf = nullptr;
var = strtok_r(res, info->separator, &strtok_buf);
while (var) {
val = strchr(var, '=');
if (val) { /* have a value */
len_list[n] = url_decode_ex(var, val-var);
val_list[n] = var;
n++;
*val++ = '\0';
val_list[n] = val;
len_list[n] = url_decode_ex(val, strlen(val));
} else {
len_list[n] = url_decode_ex(var, strlen(var));
val_list[n] = var;
n++;
val_list[n] = const_cast<char*>("");
len_list[n] = 0;
}
n++;
var = strtok_r(nullptr, info->separator, &strtok_buf);
}
num = n; /* make sure to process initilized vars only */
/* initialize converter */
if (info->num_from_encodings <= 0) {
from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
} else if (info->num_from_encodings == 1) {
from_encoding = info->from_encodings[0];
} else {
/* auto detect */
from_encoding = nullptr;
identd = mbfl_encoding_detector_new
((enum mbfl_no_encoding *)info->from_encodings,
info->num_from_encodings, MBSTRG(strict_detection));
if (identd) {
n = 0;
while (n < num) {
string.val = (unsigned char *)val_list[n];
string.len = len_list[n];
if (mbfl_encoding_detector_feed(identd, &string)) {
break;
}
n++;
}
from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd);
mbfl_encoding_detector_delete(identd);
}
if (from_encoding == nullptr) {
if (info->report_errors) {
raise_warning("Unable to detect encoding");
}
from_encoding = (mbfl_encoding*) &mbfl_encoding_pass;
}
}
convd = nullptr;
if (from_encoding != (mbfl_encoding*) &mbfl_encoding_pass) {
convd = mbfl_buffer_converter_new2(from_encoding, info->to_encoding, 0);
if (convd != nullptr) {
mbfl_buffer_converter_illegal_mode
(convd, MBSTRG(current_filter_illegal_mode));
mbfl_buffer_converter_illegal_substchar
(convd, MBSTRG(current_filter_illegal_substchar));
} else {
if (info->report_errors) {
raise_warning("Unable to create converter");
}
goto out;
}
}
/* convert encoding */
string.no_encoding = from_encoding->no_encoding;
n = 0;
while (n < num) {
string.val = (unsigned char *)val_list[n];
string.len = len_list[n];
if (convd != nullptr &&
mbfl_buffer_converter_feed_result(convd, &string, &resvar) != nullptr) {
var = (char *)resvar.val;
} else {
var = val_list[n];
}
n++;
string.val = (unsigned char *)val_list[n];
string.len = len_list[n];
if (convd != nullptr &&
mbfl_buffer_converter_feed_result(convd, &string, &resval) != nullptr) {
val = (char *)resval.val;
val_len = resval.len;
} else {
val = val_list[n];
val_len = len_list[n];
}
n++;
if (val_len > 0) {
arg.set(String(var, CopyString), String(val, val_len, CopyString));
}
if (convd != nullptr) {
mbfl_string_clear(&resvar);
mbfl_string_clear(&resval);
}
}
out:
if (convd != nullptr) {
MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
mbfl_buffer_converter_delete(convd);
}
if (val_list != nullptr) {
req::free((void *)val_list);
}
if (len_list != nullptr) {
req::free((void *)len_list);
}
return from_encoding;
}
bool HHVM_FUNCTION(mb_parse_str,
const String& encoded_string,
Array& result) {
php_mb_encoding_handler_info_t info;
info.data_type = PARSE_STRING;
info.separator = "&";
info.force_register_globals = false;
info.report_errors = 1;
info.to_encoding = MBSTRG(current_internal_encoding);
info.to_language = MBSTRG(current_language);
info.from_encodings = MBSTRG(http_input_list);
info.num_from_encodings = MBSTRG(http_input_list_size);
info.from_language = MBSTRG(current_language);
char *encstr = req::strndup(encoded_string.data(), encoded_string.size());
result = Array::Create();
mbfl_encoding *detected =
_php_mb_encoding_handler_ex(&info, result, encstr);
req::free(encstr);
MBSTRG(http_input_identify) = detected;
return detected != nullptr;
}
Variant HHVM_FUNCTION(mb_preferred_mime_name,
const String& encoding) {
mbfl_no_encoding no_encoding = mbfl_name2no_encoding(encoding.data());
if (no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding);
if (preferred_name == nullptr || *preferred_name == '\0') {
raise_warning("No MIME preferred name corresponding to \"%s\"",
encoding.data());
return false;
}
return String(preferred_name, CopyString);
}
static Variant php_mb_substr(const String& str, int from,
const Variant& vlen,
const String& encoding, bool substr) {
mbfl_string string;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
if (!encoding.empty()) {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
int len = vlen.toInt64();
int size = 0;
if (substr) {
int size_tmp = -1;
if (vlen.isNull() || len == 0x7FFFFFFF) {
size_tmp = mbfl_strlen(&string);
len = size_tmp;
}
if (from < 0 || len < 0) {
size = size_tmp < 0 ? mbfl_strlen(&string) : size_tmp;
}
} else {
size = str.size();
if (vlen.isNull() || len == 0x7FFFFFFF) {
len = size;
}
}
/* if "from" position is negative, count start position from the end
* of the string
*/
if (from < 0) {
from = size + from;
if (from < 0) {
from = 0;
}
}
/* if "length" position is negative, set it to the length
* needed to stop that many chars from the end of the string
*/
if (len < 0) {
len = (size - from) + len;
if (len < 0) {
len = 0;
}
}
if (!substr && from > size) {
return false;
}
mbfl_string result;
mbfl_string *ret;
if (substr) {
ret = mbfl_substr(&string, &result, from, len);
} else {
ret = mbfl_strcut(&string, &result, from, len);
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_substr,
const String& str,
int start,
const Variant& length /*= uninit_null() */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
return php_mb_substr(str, start, length, encoding, true);
}
Variant HHVM_FUNCTION(mb_strcut,
const String& str,
int start,
const Variant& length /*= uninit_null() */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
return php_mb_substr(str, start, length, encoding, false);
}
Variant HHVM_FUNCTION(mb_strimwidth,
const String& str,
int start,
int width,
const Variant& opt_trimmarker,
const Variant& opt_encoding) {
const String trimmarker = convertArg(opt_trimmarker);
const String encoding = convertArg(opt_encoding);
mbfl_string string, result, marker, *ret;
mbfl_string_init(&string);
mbfl_string_init(&marker);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
marker.no_language = MBSTRG(current_language);
marker.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
marker.val = nullptr;
marker.len = 0;
if (!encoding.empty()) {
string.no_encoding = marker.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
string.val = (unsigned char *)str.data();
string.len = str.size();
if (start < 0 || start > str.size()) {
raise_warning("Start position is out of reange");
return false;
}
if (width < 0) {
raise_warning("Width is negative value");
return false;
}
marker.val = (unsigned char *)trimmarker.data();
marker.len = trimmarker.size();
ret = mbfl_strimwidth(&string, &marker, &result, start, width);
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_stripos,
const String& haystack,
const String& needle,
int offset /* = 0 */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
if (needle.empty()) {
raise_warning("Empty delimiter");
return false;
}
int n = php_mb_stripos(0, haystack.data(), haystack.size(),
needle.data(), needle.size(), offset, from_encoding);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_strripos,
const String& haystack,
const String& needle,
int offset /* = 0 */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
int n = php_mb_stripos(1, haystack.data(), haystack.size(),
needle.data(), needle.size(), offset, from_encoding);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_stristr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!mbs_needle.len) {
raise_warning("Empty delimiter.");
return false;
}
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(from_encoding);
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", from_encoding);
return false;
}
int n = php_mb_stripos(0, (const char*)mbs_haystack.val, mbs_haystack.len,
(const char *)mbs_needle.val, mbs_needle.len,
0, from_encoding);
if (n < 0) {
return false;
}
int mblen = mbfl_strlen(&mbs_haystack);
mbfl_string result, *ret = nullptr;
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strlen,
const String& str,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string string;
mbfl_string_init(&string);
string.val = (unsigned char *)str.data();
string.len = str.size();
string.no_language = MBSTRG(current_language);
if (encoding.empty()) {
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
} else {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
int n = mbfl_strlen(&string);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_strpos,
const String& haystack,
const String& needle,
int offset /* = 0 */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (offset < 0 || offset > mbfl_strlen(&mbs_haystack)) {
raise_warning("Offset not contained in string.");
return false;
}
if (mbs_needle.len == 0) {
raise_warning("Empty delimiter.");
return false;
}
int reverse = 0;
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, offset, reverse);
if (n >= 0) {
return n;
}
switch (-n) {
case 1:
break;
case 2:
raise_warning("Needle has not positive length.");
break;
case 4:
raise_warning("Unknown encoding or conversion error.");
break;
case 8:
raise_warning("Argument is empty.");
break;
default:
raise_warning("Unknown error in mb_strpos.");
break;
}
return false;
}
Variant HHVM_FUNCTION(mb_strrpos,
const String& haystack,
const String& needle,
const Variant& offset /* = 0LL */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
// This hack is so that if the caller puts the encoding in the offset field we
// attempt to detect it and use that as the encoding. Ick.
const char *enc_name = encoding.data();
long noffset = 0;
String soffset = offset.toString();
if (offset.isString()) {
enc_name = soffset.data();
int str_flg = 1;
if (enc_name != nullptr) {
switch (*enc_name) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case ' ': case '-': case '.':
break;
default :
str_flg = 0;
break;
}
}
if (str_flg) {
noffset = offset.toInt32();
enc_name = encoding.data();
}
} else {
noffset = offset.toInt32();
}
if (enc_name != nullptr && *enc_name) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(enc_name);
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", enc_name);
return false;
}
}
if (mbs_haystack.len <= 0) {
return false;
}
if (mbs_needle.len <= 0) {
return false;
}
if ((noffset > 0 && noffset > mbfl_strlen(&mbs_haystack)) ||
(noffset < 0 && -noffset > mbfl_strlen(&mbs_haystack))) {
raise_notice("Offset is greater than the length of haystack string");
return false;
}
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, noffset, 1);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_strrchr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (mbs_haystack.len <= 0) {
return false;
}
if (mbs_needle.len <= 0) {
return false;
}
mbfl_string result, *ret = nullptr;
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 1);
if (n >= 0) {
int mblen = mbfl_strlen(&mbs_haystack);
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strrichr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(from_encoding);
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", from_encoding);
return false;
}
int n = php_mb_stripos(1, (const char*)mbs_haystack.val, mbs_haystack.len,
(const char*)mbs_needle.val, mbs_needle.len,
0, from_encoding);
if (n < 0) {
return false;
}
mbfl_string result, *ret = nullptr;
int mblen = mbfl_strlen(&mbs_haystack);
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strstr,
const String& haystack,
const String& needle,
bool part /* = false */,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (mbs_needle.len <= 0) {
raise_warning("Empty delimiter.");
return false;
}
mbfl_string result, *ret = nullptr;
int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 0);
if (n >= 0) {
int mblen = mbfl_strlen(&mbs_haystack);
if (part) {
ret = mbfl_substr(&mbs_haystack, &result, 0, n);
} else {
int len = (mblen - n);
ret = mbfl_substr(&mbs_haystack, &result, n, len);
}
}
if (ret != nullptr) {
return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString);
}
return false;
}
const StaticString s_utf_8("utf-8");
/**
* Fast check for the most common form of the UTF-8 encoding identifier.
*/
ALWAYS_INLINE
static bool isUtf8(const Variant& encoding) {
return encoding.getStringDataOrNull() == s_utf_8.get();
}
/**
* Given a byte sequence, return
* 0 if it contains bytes >= 128 (thus non-ASCII), else
* -1 if it contains any upper-case character ('A'-'Z'), else
* 1 (and thus is a lower-case ASCII string).
*/
ALWAYS_INLINE
static int isUtf8AsciiLower(folly::StringPiece s) {
const auto bytelen = s.size();
bool caseOK = true;
for (uint32_t i = 0; i < bytelen; ++i) {
uint8_t byte = s[i];
if (byte >= 128) {
return 0;
} else if (byte <= 'Z' && byte >= 'A') {
caseOK = false;
}
}
return caseOK ? 1 : -1;
}
/**
* Return a string containing the lower-case of a given ASCII string.
*/
ALWAYS_INLINE
static StringData* asciiToLower(const StringData* s) {
const auto size = s->size();
auto ret = StringData::Make(s, CopyString);
auto output = ret->mutableData();
for (int i = 0; i < size; ++i) {
auto& c = output[i];
if (c <= 'Z' && c >= 'A') {
c |= 0x20;
}
}
ret->invalidateHash(); // We probably modified it.
return ret;
}
/* Like isUtf8AsciiLower, but with upper/lower swapped. */
ALWAYS_INLINE
static int isUtf8AsciiUpper(folly::StringPiece s) {
const auto bytelen = s.size();
bool caseOK = true;
for (uint32_t i = 0; i < bytelen; ++i) {
uint8_t byte = s[i];
if (byte >= 128) {
return 0;
} else if (byte >= 'a' && byte <= 'z') {
caseOK = false;
}
}
return caseOK ? 1 : -1;
}
/* Like asciiToLower, but with upper/lower swapped. */
ALWAYS_INLINE
static StringData* asciiToUpper(const StringData* s) {
const auto size = s->size();
auto ret = StringData::Make(s, CopyString);
auto output = ret->mutableData();
for (int i = 0; i < size; ++i) {
auto& c = output[i];
if (c >= 'a' && c <= 'z') {
c -= (char)0x20;
}
}
ret->invalidateHash(); // We probably modified it.
return ret;
}
Variant HHVM_FUNCTION(mb_strtolower,
const String& str,
const Variant& opt_encoding) {
/* Fast-case for empty static string without dereferencing any pointers. */
if (str.get() == staticEmptyString()) return empty_string_variant();
if (LIKELY(isUtf8(opt_encoding))) {
/* Fast-case for ASCII. */
if (auto sd = str.get()) {
auto sl = sd->slice();
auto r = isUtf8AsciiLower(sl);
if (r > 0) {
return str;
} else if (r < 0) {
return String::attach(asciiToLower(sd));
}
}
}
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
unsigned int ret_len;
char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_LOWER,
str.data(), str.size(),
&ret_len, from_encoding);
if (newstr) {
return String(newstr, ret_len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strtoupper,
const String& str,
const Variant& opt_encoding) {
/* Fast-case for empty static string without dereferencing any pointers. */
if (str.get() == staticEmptyString()) return empty_string_variant();
if (LIKELY(isUtf8(opt_encoding))) {
/* Fast-case for ASCII. */
if (auto sd = str.get()) {
auto sl = sd->slice();
auto r = isUtf8AsciiUpper(sl);
if (r > 0) {
return str;
} else if (r < 0) {
return String::attach(asciiToUpper(sd));
}
}
}
const String encoding = convertArg(opt_encoding);
const char *from_encoding;
if (encoding.empty()) {
from_encoding = MBSTRG(current_internal_encoding)->mime_name;
} else {
from_encoding = encoding.data();
}
unsigned int ret_len;
char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_UPPER,
str.data(), str.size(),
&ret_len, from_encoding);
if (newstr) {
return String(newstr, ret_len, AttachString);
}
return false;
}
Variant HHVM_FUNCTION(mb_strwidth,
const String& str,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string string;
mbfl_string_init(&string);
string.no_language = MBSTRG(current_language);
string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
string.val = (unsigned char *)str.data();
string.len = str.size();
if (!encoding.empty()) {
string.no_encoding = mbfl_name2no_encoding(encoding.data());
if (string.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
int n = mbfl_strwidth(&string);
if (n >= 0) {
return n;
}
return false;
}
Variant HHVM_FUNCTION(mb_substitute_character,
const Variant& substrchar /* = uninit_variant */) {
if (substrchar.isNull()) {
switch (MBSTRG(current_filter_illegal_mode)) {
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE:
return "none";
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG:
return "long";
case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY:
return "entity";
default:
return MBSTRG(current_filter_illegal_substchar);
}
}
if (substrchar.isString()) {
String s = substrchar.toString();
if (strcasecmp("none", s.data()) == 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE;
return true;
}
if (strcasecmp("long", s.data()) == 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG;
return true;
}
if (strcasecmp("entity", s.data()) == 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY;
return true;
}
}
int64_t n = substrchar.toInt64();
if (n < 0xffff && n > 0) {
MBSTRG(current_filter_illegal_mode) =
MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
MBSTRG(current_filter_illegal_substchar) = n;
} else {
raise_warning("Unknown character.");
return false;
}
return true;
}
Variant HHVM_FUNCTION(mb_substr_count,
const String& haystack,
const String& needle,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
mbfl_string mbs_haystack;
mbfl_string_init(&mbs_haystack);
mbs_haystack.no_language = MBSTRG(current_language);
mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_haystack.val = (unsigned char *)haystack.data();
mbs_haystack.len = haystack.size();
mbfl_string mbs_needle;
mbfl_string_init(&mbs_needle);
mbs_needle.no_language = MBSTRG(current_language);
mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
mbs_needle.val = (unsigned char *)needle.data();
mbs_needle.len = needle.size();
if (!encoding.empty()) {
mbs_haystack.no_encoding = mbs_needle.no_encoding =
mbfl_name2no_encoding(encoding.data());
if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
}
if (mbs_needle.len <= 0) {
raise_warning("Empty substring.");
return false;
}
int n = mbfl_substr_count(&mbs_haystack, &mbs_needle);
if (n >= 0) {
return n;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// regex helpers
typedef struct _php_mb_regex_enc_name_map_t {
const char *names;
OnigEncoding code;
} php_mb_regex_enc_name_map_t;
static php_mb_regex_enc_name_map_t enc_name_map[] ={
{
"EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0",
ONIG_ENCODING_EUC_JP
},
{
"UTF-8\0UTF8\0",
ONIG_ENCODING_UTF8
},
{
"UTF-16\0UTF-16BE\0",
ONIG_ENCODING_UTF16_BE
},
{
"UTF-16LE\0",
ONIG_ENCODING_UTF16_LE
},
{
"UCS-4\0UTF-32\0UTF-32BE\0",
ONIG_ENCODING_UTF32_BE
},
{
"UCS-4LE\0UTF-32LE\0",
ONIG_ENCODING_UTF32_LE
},
{
"SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0",
ONIG_ENCODING_SJIS
},
{
"BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0",
ONIG_ENCODING_BIG5
},
{
"EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0",
ONIG_ENCODING_EUC_CN
},
{
"EUC-TW\0EUCTW\0EUC_TW\0",
ONIG_ENCODING_EUC_TW
},
{
"EUC-KR\0EUCKR\0EUC_KR\0",
ONIG_ENCODING_EUC_KR
},
{
"KOI8R\0KOI8-R\0KOI-8R\0",
ONIG_ENCODING_KOI8_R
},
{
"ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0",
ONIG_ENCODING_ISO_8859_1
},
{
"ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0",
ONIG_ENCODING_ISO_8859_2
},
{
"ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0",
ONIG_ENCODING_ISO_8859_3
},
{
"ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0",
ONIG_ENCODING_ISO_8859_4
},
{
"ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0",
ONIG_ENCODING_ISO_8859_5
},
{
"ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0",
ONIG_ENCODING_ISO_8859_6
},
{
"ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0",
ONIG_ENCODING_ISO_8859_7
},
{
"ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0",
ONIG_ENCODING_ISO_8859_8
},
{
"ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0",
ONIG_ENCODING_ISO_8859_9
},
{
"ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0",
ONIG_ENCODING_ISO_8859_10
},
{
"ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0",
ONIG_ENCODING_ISO_8859_11
},
{
"ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0",
ONIG_ENCODING_ISO_8859_13
},
{
"ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0",
ONIG_ENCODING_ISO_8859_14
},
{
"ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0",
ONIG_ENCODING_ISO_8859_15
},
{
"ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0",
ONIG_ENCODING_ISO_8859_16
},
{
"ASCII\0US-ASCII\0US_ASCII\0ISO646\0",
ONIG_ENCODING_ASCII
},
{ nullptr, ONIG_ENCODING_UNDEF }
};
static OnigEncoding php_mb_regex_name2mbctype(const char *pname) {
const char *p;
php_mb_regex_enc_name_map_t *mapping;
if (pname == nullptr) {
return ONIG_ENCODING_UNDEF;
}
for (mapping = enc_name_map; mapping->names != nullptr; mapping++) {
for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) {
if (strcasecmp(p, pname) == 0) {
return mapping->code;
}
}
}
return ONIG_ENCODING_UNDEF;
}
static const char *php_mb_regex_mbctype2name(OnigEncoding mbctype) {
php_mb_regex_enc_name_map_t *mapping;
for (mapping = enc_name_map; mapping->names != nullptr; mapping++) {
if (mapping->code == mbctype) {
return mapping->names;
}
}
return nullptr;
}
/*
* regex cache
*/
static php_mb_regex_t *php_mbregex_compile_pattern(const String& pattern,
OnigOptionType options,
OnigEncoding enc,
OnigSyntaxType *syntax) {
int err_code = 0;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
php_mb_regex_t *rc = nullptr;
std::string spattern = std::string(pattern.data(), pattern.size());
RegexCache &cache = MBSTRG(ht_rc);
RegexCache::const_iterator it =
cache.find(spattern);
if (it != cache.end()) {
rc = it->second;
}
if (!rc || onig_get_options(rc) != options || onig_get_encoding(rc) != enc ||
onig_get_syntax(rc) != syntax) {
if (rc) {
onig_free(rc);
rc = nullptr;
}
if ((err_code = onig_new(&rc, (OnigUChar *)pattern.data(),
(OnigUChar *)(pattern.data() + pattern.size()),
options,enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
raise_warning("mbregex compile err: %s", err_str);
return nullptr;
}
MBSTRG(ht_rc)[spattern] = rc;
}
return rc;
}
static size_t _php_mb_regex_get_option_string(char *str, size_t len,
OnigOptionType option,
OnigSyntaxType *syntax) {
size_t len_left = len;
size_t len_req = 0;
char *p = str;
char c;
if ((option & ONIG_OPTION_IGNORECASE) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'i';
}
++len_req;
}
if ((option & ONIG_OPTION_EXTEND) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'x';
}
++len_req;
}
if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) ==
(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) {
if (len_left > 0) {
--len_left;
*(p++) = 'p';
}
++len_req;
} else {
if ((option & ONIG_OPTION_MULTILINE) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'm';
}
++len_req;
}
if ((option & ONIG_OPTION_SINGLELINE) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 's';
}
++len_req;
}
}
if ((option & ONIG_OPTION_FIND_LONGEST) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'l';
}
++len_req;
}
if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) {
if (len_left > 0) {
--len_left;
*(p++) = 'n';
}
++len_req;
}
c = 0;
if (syntax == ONIG_SYNTAX_JAVA) {
c = 'j';
} else if (syntax == ONIG_SYNTAX_GNU_REGEX) {
c = 'u';
} else if (syntax == ONIG_SYNTAX_GREP) {
c = 'g';
} else if (syntax == ONIG_SYNTAX_EMACS) {
c = 'c';
} else if (syntax == ONIG_SYNTAX_RUBY) {
c = 'r';
} else if (syntax == ONIG_SYNTAX_PERL) {
c = 'z';
} else if (syntax == ONIG_SYNTAX_POSIX_BASIC) {
c = 'b';
} else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) {
c = 'd';
}
if (c != 0) {
if (len_left > 0) {
--len_left;
*(p++) = c;
}
++len_req;
}
if (len_left > 0) {
--len_left;
*(p++) = '\0';
}
++len_req;
if (len < len_req) {
return len_req;
}
return 0;
}
static void _php_mb_regex_init_options(const char *parg, int narg,
OnigOptionType *option,
OnigSyntaxType **syntax, int *eval) {
int n;
char c;
int optm = 0;
*syntax = ONIG_SYNTAX_RUBY;
if (parg != nullptr) {
n = 0;
while (n < narg) {
c = parg[n++];
switch (c) {
case 'i': optm |= ONIG_OPTION_IGNORECASE; break;
case 'x': optm |= ONIG_OPTION_EXTEND; break;
case 'm': optm |= ONIG_OPTION_MULTILINE; break;
case 's': optm |= ONIG_OPTION_SINGLELINE; break;
case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break;
case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break;
case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break;
case 'j': *syntax = ONIG_SYNTAX_JAVA; break;
case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break;
case 'g': *syntax = ONIG_SYNTAX_GREP; break;
case 'c': *syntax = ONIG_SYNTAX_EMACS; break;
case 'r': *syntax = ONIG_SYNTAX_RUBY; break;
case 'z': *syntax = ONIG_SYNTAX_PERL; break;
case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break;
case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break;
case 'e':
if (eval != nullptr) *eval = 1;
break;
default:
break;
}
}
if (option != nullptr) *option|=optm;
}
}
///////////////////////////////////////////////////////////////////////////////
// regex functions
bool HHVM_FUNCTION(mb_ereg_match,
const String& pattern,
const String& str,
const Variant& opt_option) {
const String option = convertArg(opt_option);
OnigSyntaxType *syntax;
OnigOptionType noption = 0;
if (!option.empty()) {
_php_mb_regex_init_options(option.data(), option.size(), &noption,
&syntax, nullptr);
} else {
noption |= MBSTRG(regex_default_options);
syntax = MBSTRG(regex_default_syntax);
}
php_mb_regex_t *re;
if ((re = php_mbregex_compile_pattern
(pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) {
return false;
}
/* match */
int err = onig_match(re, (OnigUChar *)str.data(),
(OnigUChar *)(str.data() + str.size()),
(OnigUChar *)str.data(), nullptr, 0);
return err >= 0;
}
static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern,
const String& replacement,
const String& str,
const String& option,
OnigOptionType options) {
const char *p;
php_mb_regex_t *re;
OnigSyntaxType *syntax;
OnigRegion *regs = nullptr;
StringBuffer out_buf;
int i, err, eval, n;
OnigUChar *pos;
OnigUChar *string_lim;
char pat_buf[2];
const mbfl_encoding *enc;
{
const char *current_enc_name;
current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype));
if (current_enc_name == nullptr ||
(enc = mbfl_name2encoding(current_enc_name)) == nullptr) {
raise_warning("Unknown error");
return false;
}
}
eval = 0;
{
if (!option.empty()) {
_php_mb_regex_init_options(option.data(), option.size(),
&options, &syntax, &eval);
} else {
options |= MBSTRG(regex_default_options);
syntax = MBSTRG(regex_default_syntax);
}
}
String spattern;
if (pattern.isString()) {
spattern = pattern.toString();
} else {
/* FIXME: this code is not multibyte aware! */
pat_buf[0] = pattern.toByte();
pat_buf[1] = '\0';
spattern = String(pat_buf, 1, CopyString);
}
/* create regex pattern buffer */
re = php_mbregex_compile_pattern(spattern, options,
MBSTRG(current_mbctype), syntax);
if (re == nullptr) {
return false;
}
if (eval) {
throw_not_supported("ereg_replace", "dynamic coding");
}
/* do the actual work */
err = 0;
pos = (OnigUChar*)str.data();
string_lim = (OnigUChar*)(str.data() + str.size());
regs = onig_region_new();
while (err >= 0) {
err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim,
pos, (OnigUChar *)string_lim, regs, 0);
if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
raise_warning("mbregex search failure: %s", err_str);
break;
}
if (err >= 0) {
#if moriyoshi_0
if (regs->beg[0] == regs->end[0]) {
raise_warning("Empty regular expression");
break;
}
#endif
/* copy the part of the string before the match */
out_buf.append((const char *)pos,
(OnigUChar *)(str.data() + regs->beg[0]) - pos);
/* copy replacement and backrefs */
i = 0;
p = replacement.data();
while (i < replacement.size()) {
int fwd = (int)php_mb_mbchar_bytes_ex(p, enc);
n = -1;
auto const remaining = replacement.size() - i;
if (remaining >= 2 && fwd == 1 &&
p[0] == '\\' && p[1] >= '0' && p[1] <= '9') {
n = p[1] - '0';
}
if (n >= 0 && n < regs->num_regs) {
if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] &&
regs->end[n] <= str.size()) {
out_buf.append(str.data() + regs->beg[n],
regs->end[n] - regs->beg[n]);
}
p += 2;
i += 2;
} else if (remaining >= fwd) {
out_buf.append(p, fwd);
p += fwd;
i += fwd;
} else {
raise_warning("Replacement ends with unterminated %s: 0x%hhx",
enc->name, *p);
break;
}
}
n = regs->end[0];
if ((pos - (OnigUChar *)str.data()) < n) {
pos = (OnigUChar *)(str.data() + n);
} else {
if (pos < string_lim) {
out_buf.append((const char *)pos, 1);
}
pos++;
}
} else { /* nomatch */
/* stick that last bit of string on our output */
if (string_lim - pos > 0) {
out_buf.append((const char *)pos, string_lim - pos);
}
}
onig_region_free(regs, 0);
}
if (regs != nullptr) {
onig_region_free(regs, 1);
}
if (err <= -2) {
return false;
}
return out_buf.detach();
}
Variant HHVM_FUNCTION(mb_ereg_replace,
const Variant& pattern,
const String& replacement,
const String& str,
const Variant& opt_option) {
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_replace_exec(pattern, replacement,
str, option, 0);
}
Variant HHVM_FUNCTION(mb_eregi_replace,
const Variant& pattern,
const String& replacement,
const String& str,
const Variant& opt_option) {
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_replace_exec(pattern, replacement,
str, option, ONIG_OPTION_IGNORECASE);
}
int64_t HHVM_FUNCTION(mb_ereg_search_getpos) {
return MBSTRG(search_pos);
}
bool HHVM_FUNCTION(mb_ereg_search_setpos,
int position) {
if (position < 0 || position >= (int)MBSTRG(search_str).size()) {
raise_warning("Position is out of range");
MBSTRG(search_pos) = 0;
return false;
}
MBSTRG(search_pos) = position;
return true;
}
Variant HHVM_FUNCTION(mb_ereg_search_getregs) {
OnigRegion *search_regs = MBSTRG(search_regs);
if (search_regs && !MBSTRG(search_str).empty()) {
Array ret;
OnigUChar *str = (OnigUChar *)MBSTRG(search_str).data();
int len = MBSTRG(search_str).size();
int n = search_regs->num_regs;
for (int i = 0; i < n; i++) {
int beg = search_regs->beg[i];
int end = search_regs->end[i];
if (beg >= 0 && beg <= end && end <= len) {
ret.append(String((const char *)(str + beg), end - beg, CopyString));
} else {
ret.append(false);
}
}
return ret;
}
return false;
}
bool HHVM_FUNCTION(mb_ereg_search_init,
const String& str,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
OnigOptionType noption = MBSTRG(regex_default_options);
OnigSyntaxType *syntax = MBSTRG(regex_default_syntax);
if (!option.empty()) {
noption = 0;
_php_mb_regex_init_options(option.data(), option.size(),
&noption, &syntax, nullptr);
}
if (!pattern.empty()) {
if ((MBSTRG(search_re) = php_mbregex_compile_pattern
(pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) {
return false;
}
}
MBSTRG(search_str) = std::string(str.data(), str.size());
MBSTRG(search_pos) = 0;
if (MBSTRG(search_regs) != nullptr) {
onig_region_free(MBSTRG(search_regs), 1);
MBSTRG(search_regs) = (OnigRegion *)nullptr;
}
return true;
}
/* regex search */
static Variant _php_mb_regex_ereg_search_exec(const String& pattern,
const String& option,
int mode) {
int n, i, err, pos, len, beg, end;
OnigUChar *str;
OnigSyntaxType *syntax = MBSTRG(regex_default_syntax);
OnigOptionType noption;
noption = MBSTRG(regex_default_options);
if (!option.empty()) {
noption = 0;
_php_mb_regex_init_options(option.data(), option.size(),
&noption, &syntax, nullptr);
}
if (!pattern.empty()) {
if ((MBSTRG(search_re) = php_mbregex_compile_pattern
(pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) {
return false;
}
}
pos = MBSTRG(search_pos);
str = nullptr;
len = 0;
if (!MBSTRG(search_str).empty()) {
str = (OnigUChar *)MBSTRG(search_str).data();
len = MBSTRG(search_str).size();
}
if (MBSTRG(search_re) == nullptr) {
raise_warning("No regex given");
return false;
}
if (str == nullptr) {
raise_warning("No string given");
return false;
}
if (MBSTRG(search_regs)) {
onig_region_free(MBSTRG(search_regs), 1);
}
MBSTRG(search_regs) = onig_region_new();
err = onig_search(MBSTRG(search_re), str, str + len, str + pos, str + len,
MBSTRG(search_regs), 0);
Variant ret;
if (err == ONIG_MISMATCH) {
MBSTRG(search_pos) = len;
ret = false;
} else if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
raise_warning("mbregex search failure in mbregex_search(): %s", err_str);
ret = false;
} else {
if (MBSTRG(search_regs)->beg[0] == MBSTRG(search_regs)->end[0]) {
raise_warning("Empty regular expression");
}
switch (mode) {
case 1:
{
beg = MBSTRG(search_regs)->beg[0];
end = MBSTRG(search_regs)->end[0];
ret = make_packed_array(beg, end - beg);
}
break;
case 2:
n = MBSTRG(search_regs)->num_regs;
ret = Variant(Array::Create());
for (i = 0; i < n; i++) {
beg = MBSTRG(search_regs)->beg[i];
end = MBSTRG(search_regs)->end[i];
if (beg >= 0 && beg <= end && end <= len) {
ret.toArrRef().append(
String((const char *)(str + beg), end - beg, CopyString));
} else {
ret.toArrRef().append(false);
}
}
break;
default:
ret = true;
break;
}
end = MBSTRG(search_regs)->end[0];
if (pos < end) {
MBSTRG(search_pos) = end;
} else {
MBSTRG(search_pos) = pos + 1;
}
}
if (err < 0) {
onig_region_free(MBSTRG(search_regs), 1);
MBSTRG(search_regs) = (OnigRegion *)nullptr;
}
return ret;
}
Variant HHVM_FUNCTION(mb_ereg_search,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_search_exec(pattern, option, 0);
}
Variant HHVM_FUNCTION(mb_ereg_search_pos,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_search_exec(pattern, option, 1);
}
Variant HHVM_FUNCTION(mb_ereg_search_regs,
const Variant& opt_pattern,
const Variant& opt_option) {
const String pattern = convertArg(opt_pattern);
const String option = convertArg(opt_option);
return _php_mb_regex_ereg_search_exec(pattern, option, 2);
}
static Variant _php_mb_regex_ereg_exec(const Variant& pattern, const String& str,
Variant *regs, int icase) {
php_mb_regex_t *re;
OnigRegion *regions = nullptr;
int i, match_len, beg, end;
OnigOptionType options;
options = MBSTRG(regex_default_options);
if (icase) {
options |= ONIG_OPTION_IGNORECASE;
}
/* compile the regular expression from the supplied regex */
String spattern;
if (!pattern.isString()) {
/* we convert numbers to integers and treat them as a string */
if (pattern.is(KindOfDouble)) {
spattern = String(pattern.toInt64()); /* get rid of decimal places */
} else {
spattern = pattern.toString();
}
} else {
spattern = pattern.toString();
}
re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype),
MBSTRG(regex_default_syntax));
if (re == nullptr) {
return false;
}
regions = onig_region_new();
/* actually execute the regular expression */
if (onig_search(re, (OnigUChar *)str.data(),
(OnigUChar *)(str.data() + str.size()),
(OnigUChar *)str.data(),
(OnigUChar *)(str.data() + str.size()),
regions, 0) < 0) {
onig_region_free(regions, 1);
return false;
}
const char *s = str.data();
int string_len = str.size();
match_len = regions->end[0] - regions->beg[0];
PackedArrayInit regsPai(regions->num_regs);
for (i = 0; i < regions->num_regs; i++) {
beg = regions->beg[i];
end = regions->end[i];
if (beg >= 0 && beg < end && end <= string_len) {
regsPai.append(String(s + beg, end - beg, CopyString));
} else {
regsPai.append(false);
}
}
if (regs) *regs = regsPai.toArray();
if (match_len == 0) {
match_len = 1;
}
if (regions != nullptr) {
onig_region_free(regions, 1);
}
return match_len;
}
Variant HHVM_FUNCTION(mb_ereg,
const Variant& pattern,
const String& str,
Variant& regs) {
return _php_mb_regex_ereg_exec(pattern, str, ®s, 0);
}
Variant HHVM_FUNCTION(mb_eregi,
const Variant& pattern,
const String& str,
Variant& regs) {
return _php_mb_regex_ereg_exec(pattern, str, ®s, 1);
}
Variant HHVM_FUNCTION(mb_regex_encoding,
const Variant& opt_encoding) {
const String encoding = convertArg(opt_encoding);
if (encoding.empty()) {
const char *retval = php_mb_regex_mbctype2name(MBSTRG(current_mbctype));
if (retval != nullptr) {
return String(retval, CopyString);
}
return false;
}
OnigEncoding mbctype = php_mb_regex_name2mbctype(encoding.data());
if (mbctype == ONIG_ENCODING_UNDEF) {
raise_warning("Unknown encoding \"%s\"", encoding.data());
return false;
}
MBSTRG(current_mbctype) = mbctype;
return true;
}
static void php_mb_regex_set_options(OnigOptionType options,
OnigSyntaxType *syntax,
OnigOptionType *prev_options,
OnigSyntaxType **prev_syntax) {
if (prev_options != nullptr) {
*prev_options = MBSTRG(regex_default_options);
}
if (prev_syntax != nullptr) {
*prev_syntax = MBSTRG(regex_default_syntax);
}
MBSTRG(regex_default_options) = options;
MBSTRG(regex_default_syntax) = syntax;
}
String HHVM_FUNCTION(mb_regex_set_options,
const Variant& opt_options) {
const String options = convertArg(opt_options);
OnigOptionType opt;
OnigSyntaxType *syntax;
char buf[16];
if (!options.empty()) {
opt = 0;
syntax = nullptr;
_php_mb_regex_init_options(options.data(), options.size(),
&opt, &syntax, nullptr);
php_mb_regex_set_options(opt, syntax, nullptr, nullptr);
} else {
opt = MBSTRG(regex_default_options);
syntax = MBSTRG(regex_default_syntax);
}
_php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax);
return String(buf, CopyString);
}
Variant HHVM_FUNCTION(mb_split,
const String& pattern,
const String& str,
int count /* = -1 */) {
php_mb_regex_t *re;
OnigRegion *regs = nullptr;
int n, err;
if (count == 0) {
count = 1;
}
/* create regex pattern buffer */
if ((re = php_mbregex_compile_pattern(pattern,
MBSTRG(regex_default_options),
MBSTRG(current_mbctype),
MBSTRG(regex_default_syntax)))
== nullptr) {
return false;
}
Array ret;
OnigUChar *pos0 = (OnigUChar *)str.data();
OnigUChar *pos_end = (OnigUChar *)(str.data() + str.size());
OnigUChar *pos = pos0;
err = 0;
regs = onig_region_new();
/* churn through str, generating array entries as we go */
while ((--count != 0) &&
(err = onig_search(re, pos0, pos_end, pos, pos_end, regs, 0)) >= 0) {
if (regs->beg[0] == regs->end[0]) {
raise_warning("Empty regular expression");
break;
}
/* add it to the array */
if (regs->beg[0] < str.size() && regs->beg[0] >= (pos - pos0)) {
ret.append(String((const char *)pos,
((OnigUChar *)(str.data() + regs->beg[0]) - pos),
CopyString));
} else {
err = -2;
break;
}
/* point at our new starting point */
n = regs->end[0];
if ((pos - pos0) < n) {
pos = pos0 + n;
}
if (count < 0) {
count = 0;
}
onig_region_free(regs, 0);
}
onig_region_free(regs, 1);
/* see if we encountered an error */
if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
raise_warning("mbregex search failure in mbsplit(): %s", err_str);
return false;
}
/* otherwise we just have one last element to add to the array */
n = pos_end - pos;
if (n > 0) {
ret.append(String((const char *)pos, n, CopyString));
} else {
ret.append("");
}
return ret;
}
///////////////////////////////////////////////////////////////////////////////
#define SKIP_LONG_HEADER_SEP_MBSTRING(str, pos) \
if (str[pos] == '\r' && str[pos + 1] == '\n' && \
(str[pos + 2] == ' ' || str[pos + 2] == '\t')) { \
pos += 2; \
while (str[pos + 1] == ' ' || str[pos + 1] == '\t') { \
pos++; \
} \
continue; \
}
static int _php_mbstr_parse_mail_headers(Array &ht, const char *str,
size_t str_len) {
const char *ps;
size_t icnt;
int state = 0;
int crlf_state = -1;
StringBuffer token;
String fld_name, fld_val;
ps = str;
icnt = str_len;
/*
* C o n t e n t - T y p e : t e x t / h t m l \r\n
* ^ ^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^^^
* state 0 1 2 3
*
* C o n t e n t - T y p e : t e x t / h t m l \r\n
* ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^
* crlf_state -1 0 1 -1
*
*/
while (icnt > 0) {
switch (*ps) {
case ':':
if (crlf_state == 1) {
token.append('\r');
}
if (state == 0 || state == 1) {
fld_name = token.detach();
state = 2;
} else {
token.append(*ps);
}
crlf_state = 0;
break;
case '\n':
if (crlf_state == -1) {
goto out;
}
crlf_state = -1;
break;
case '\r':
if (crlf_state == 1) {
token.append('\r');
} else {
crlf_state = 1;
}
break;
case ' ': case '\t':
if (crlf_state == -1) {
if (state == 3) {
/* continuing from the previous line */
state = 4;
} else {
/* simply skipping this new line */
state = 5;
}
} else {
if (crlf_state == 1) {
token.append('\r');
}
if (state == 1 || state == 3) {
token.append(*ps);
}
}
crlf_state = 0;
break;
default:
switch (state) {
case 0:
token.clear();
state = 1;
break;
case 2:
if (crlf_state != -1) {
token.clear();
state = 3;
break;
}
/* break is missing intentionally */
case 3:
if (crlf_state == -1) {
fld_val = token.detach();
if (!fld_name.empty() && !fld_val.empty()) {
/* FIXME: some locale free implementation is
* really required here,,, */
ht.set(HHVM_FN(strtoupper)(fld_name), fld_val);
}
state = 1;
}
break;
case 4:
token.append(' ');
state = 3;
break;
}
if (crlf_state == 1) {
token.append('\r');
}
token.append(*ps);
crlf_state = 0;
break;
}
ps++, icnt--;
}
out:
if (state == 2) {
token.clear();
state = 3;
}
if (state == 3) {
fld_val = token.detach();
if (!fld_name.empty() && !fld_val.empty()) {
/* FIXME: some locale free implementation is
* really required here,,, */
ht.set(HHVM_FN(strtoupper)(fld_name), fld_val);
}
}
return state;
}
static int php_mail(const char *to, const char *subject, const char *message,
const char *headers, const char *extra_cmd) {
const char *sendmail_path = "/usr/sbin/sendmail -t -i";
String sendmail_cmd = sendmail_path;
if (extra_cmd != nullptr) {
sendmail_cmd += " ";
sendmail_cmd += extra_cmd;
}
/* Since popen() doesn't indicate if the internal fork() doesn't work
* (e.g. the shell can't be executed) we explicitly set it to 0 to be
* sure we don't catch any older errno value. */
errno = 0;
FILE *sendmail = popen(sendmail_cmd.data(), "w");
if (sendmail == nullptr) {
raise_warning("Could not execute mail delivery program '%s'",
sendmail_path);
return 0;
}
if (EACCES == errno) {
raise_warning("Permission denied: unable to execute shell to run "
"mail delivery binary '%s'", sendmail_path);
pclose(sendmail);
return 0;
}
fprintf(sendmail, "To: %s\n", to);
fprintf(sendmail, "Subject: %s\n", subject);
if (headers != nullptr) {
fprintf(sendmail, "%s\n", headers);
}
fprintf(sendmail, "\n%s\n", message);
int ret = pclose(sendmail);
#if defined(EX_TEMPFAIL)
if ((ret != EX_OK) && (ret != EX_TEMPFAIL)) return 0;
#elif defined(EX_OK)
if (ret != EX_OK) return 0;
#else
if (ret != 0) return 0;
#endif
return 1;
}
bool HHVM_FUNCTION(mb_send_mail,
const String& to,
const String& subject,
const String& message,
const Variant& opt_headers,
const Variant& opt_extra_cmd) {
const String headers = convertArg(opt_headers);
const String extra_cmd = convertArg(opt_extra_cmd);
/* initialize */
/* automatic allocateable buffer for additional header */
mbfl_memory_device device;
mbfl_memory_device_init(&device, 0, 0);
mbfl_string orig_str, conv_str;
mbfl_string_init(&orig_str);
mbfl_string_init(&conv_str);
/* character-set, transfer-encoding */
mbfl_no_encoding
tran_cs, /* transfar text charset */
head_enc, /* header transfar encoding */
body_enc; /* body transfar encoding */
tran_cs = mbfl_no_encoding_utf8;
head_enc = mbfl_no_encoding_base64;
body_enc = mbfl_no_encoding_base64;
const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language));
if (lang != nullptr) {
tran_cs = lang->mail_charset;
head_enc = lang->mail_header_encoding;
body_enc = lang->mail_body_encoding;
}
Array ht_headers;
if (!headers.empty()) {
_php_mbstr_parse_mail_headers(ht_headers, headers.data(), headers.size());
}
struct {
unsigned int cnt_type:1;
unsigned int cnt_trans_enc:1;
} suppressed_hdrs = { 0, 0 };
static const StaticString s_CONTENT_TYPE("CONTENT-TYPE");
String s = ht_headers[s_CONTENT_TYPE].toString();
if (!s.isNull()) {
char *tmp;
char *param_name;
char *charset = nullptr;
char *p = const_cast<char*>(strchr(s.data(), ';'));
if (p != nullptr) {
/* skipping the padded spaces */
do {
++p;
} while (*p == ' ' || *p == '\t');
if (*p != '\0') {
if ((param_name = strtok_r(p, "= ", &tmp)) != nullptr) {
if (strcasecmp(param_name, "charset") == 0) {
mbfl_no_encoding _tran_cs = tran_cs;
charset = strtok_r(nullptr, "= ", &tmp);
if (charset != nullptr) {
_tran_cs = mbfl_name2no_encoding(charset);
}
if (_tran_cs == mbfl_no_encoding_invalid) {
raise_warning("Unsupported charset \"%s\" - "
"will be regarded as ascii", charset);
_tran_cs = mbfl_no_encoding_ascii;
}
tran_cs = _tran_cs;
}
}
}
}
suppressed_hdrs.cnt_type = 1;
}
static const StaticString
s_CONTENT_TRANSFER_ENCODING("CONTENT-TRANSFER-ENCODING");
s = ht_headers[s_CONTENT_TRANSFER_ENCODING].toString();
if (!s.isNull()) {
mbfl_no_encoding _body_enc = mbfl_name2no_encoding(s.data());
switch (_body_enc) {
case mbfl_no_encoding_base64:
case mbfl_no_encoding_7bit:
case mbfl_no_encoding_8bit:
body_enc = _body_enc;
break;
default:
raise_warning("Unsupported transfer encoding \"%s\" - "
"will be regarded as 8bit", s.data());
body_enc = mbfl_no_encoding_8bit;
break;
}
suppressed_hdrs.cnt_trans_enc = 1;
}
/* To: */
char *to_r = nullptr;
int err = 0;
if (auto to_len = strlen(to.data())) { // not to.size()
to_r = req::strndup(to.data(), to_len);
for (; to_len; to_len--) {
if (!isspace((unsigned char)to_r[to_len - 1])) {
break;
}
to_r[to_len - 1] = '\0';
}
for (size_t i = 0; to_r[i]; i++) {
if (iscntrl((unsigned char)to_r[i])) {
/**
* According to RFC 822, section 3.1.1 long headers may be
* separated into parts using CRLF followed at least one
* linear-white-space character ('\t' or ' ').
* To prevent these separators from being replaced with a space,
* we use the SKIP_LONG_HEADER_SEP_MBSTRING to skip over them.
*/
SKIP_LONG_HEADER_SEP_MBSTRING(to_r, i);
to_r[i] = ' ';
}
}
} else {
raise_warning("Missing To: field");
err = 1;
}
/* Subject: */
String encoded_subject;
if (!subject.isNull()) {
orig_str.no_language = MBSTRG(current_language);
orig_str.val = (unsigned char *)subject.data();
orig_str.len = subject.size();
orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
if (orig_str.no_encoding == mbfl_no_encoding_invalid
|| orig_str.no_encoding == mbfl_no_encoding_pass) {
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_identify_encoding2(&orig_str,
(const mbfl_encoding**) MBSTRG(current_detect_order_list),
MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection));
orig_str.no_encoding = encoding != nullptr
? encoding->no_encoding
: mbfl_no_encoding_invalid;
}
mbfl_string *pstr = mbfl_mime_header_encode
(&orig_str, &conv_str, tran_cs, head_enc,
"\n", sizeof("Subject: [PHP-jp nnnnnnnn]"));
if (pstr != nullptr) {
encoded_subject = String(reinterpret_cast<char*>(pstr->val),
pstr->len,
AttachString);
}
} else {
raise_warning("Missing Subject: field");
err = 1;
}
/* message body */
String encoded_message;
if (!message.empty()) {
orig_str.no_language = MBSTRG(current_language);
orig_str.val = (unsigned char*)message.data();
orig_str.len = message.size();
orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding;
if (orig_str.no_encoding == mbfl_no_encoding_invalid
|| orig_str.no_encoding == mbfl_no_encoding_pass) {
mbfl_encoding *encoding =
(mbfl_encoding*) mbfl_identify_encoding2(&orig_str,
(const mbfl_encoding**) MBSTRG(current_detect_order_list),
MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection));
orig_str.no_encoding = encoding != nullptr
? encoding->no_encoding
: mbfl_no_encoding_invalid;
}
mbfl_string *pstr = nullptr;
{
mbfl_string tmpstr;
if (mbfl_convert_encoding(&orig_str, &tmpstr, tran_cs) != nullptr) {
tmpstr.no_encoding = mbfl_no_encoding_8bit;
pstr = mbfl_convert_encoding(&tmpstr, &conv_str, body_enc);
free(tmpstr.val);
}
}
if (pstr != nullptr) {
encoded_message = String(reinterpret_cast<char*>(pstr->val),
pstr->len,
AttachString);
}
} else {
/* this is not really an error, so it is allowed. */
raise_warning("Empty message body");
}
/* other headers */
#define PHP_MBSTR_MAIL_MIME_HEADER1 "Mime-Version: 1.0"
#define PHP_MBSTR_MAIL_MIME_HEADER2 "Content-Type: text/plain"
#define PHP_MBSTR_MAIL_MIME_HEADER3 "; charset="
#define PHP_MBSTR_MAIL_MIME_HEADER4 "Content-Transfer-Encoding: "
if (!headers.empty()) {
const char *p = headers.data();
int n = headers.size();
mbfl_memory_device_strncat(&device, p, n);
if (n > 0 && p[n - 1] != '\n') {
mbfl_memory_device_strncat(&device, "\n", 1);
}
}
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER1,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER1) - 1);
mbfl_memory_device_strncat(&device, "\n", 1);
if (!suppressed_hdrs.cnt_type) {
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER2,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER2) - 1);
char *p = (char *)mbfl_no2preferred_mime_name(tran_cs);
if (p != nullptr) {
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER3,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER3) - 1);
mbfl_memory_device_strcat(&device, p);
}
mbfl_memory_device_strncat(&device, "\n", 1);
}
if (!suppressed_hdrs.cnt_trans_enc) {
mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER4,
sizeof(PHP_MBSTR_MAIL_MIME_HEADER4) - 1);
const char *p = (char *)mbfl_no2preferred_mime_name(body_enc);
if (p == nullptr) {
p = "7bit";
}
mbfl_memory_device_strcat(&device, p);
mbfl_memory_device_strncat(&device, "\n", 1);
}
mbfl_memory_device_unput(&device);
mbfl_memory_device_output('\0', &device);
char *all_headers = (char *)device.buffer;
String cmd = string_escape_shell_cmd(extra_cmd.c_str());
bool ret = (!err && php_mail(to_r, encoded_subject.data(),
encoded_message.data(),
all_headers, cmd.data()));
mbfl_memory_device_clear(&device);
req::free(to_r);
return ret;
}
static struct mbstringExtension final : Extension {
mbstringExtension() : Extension("mbstring", NO_EXTENSION_VERSION_YET) {}
void moduleInit() override {
// TODO make these PHP_INI_ALL and thread local once we use them
IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_input",
&http_input);
IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_output",
&http_output);
IniSetting::Bind(this, IniSetting::PHP_INI_ALL,
"mbstring.substitute_character",
&MBSTRG(current_filter_illegal_mode));
HHVM_RC_INT(MB_OVERLOAD_MAIL, 1);
HHVM_RC_INT(MB_OVERLOAD_STRING, 2);
HHVM_RC_INT(MB_OVERLOAD_REGEX, 4);
HHVM_RC_INT(MB_CASE_UPPER, PHP_UNICODE_CASE_UPPER);
HHVM_RC_INT(MB_CASE_LOWER, PHP_UNICODE_CASE_LOWER);
HHVM_RC_INT(MB_CASE_TITLE, PHP_UNICODE_CASE_TITLE);
HHVM_FE(mb_list_encodings);
HHVM_FE(mb_list_encodings_alias_names);
HHVM_FE(mb_list_mime_names);
HHVM_FE(mb_check_encoding);
HHVM_FE(mb_convert_case);
HHVM_FE(mb_convert_encoding);
HHVM_FE(mb_convert_kana);
HHVM_FE(mb_convert_variables);
HHVM_FE(mb_decode_mimeheader);
HHVM_FE(mb_decode_numericentity);
HHVM_FE(mb_detect_encoding);
HHVM_FE(mb_detect_order);
HHVM_FE(mb_encode_mimeheader);
HHVM_FE(mb_encode_numericentity);
HHVM_FE(mb_encoding_aliases);
HHVM_FE(mb_ereg_match);
HHVM_FE(mb_ereg_replace);
HHVM_FE(mb_ereg_search_getpos);
HHVM_FE(mb_ereg_search_getregs);
HHVM_FE(mb_ereg_search_init);
HHVM_FE(mb_ereg_search_pos);
HHVM_FE(mb_ereg_search_regs);
HHVM_FE(mb_ereg_search_setpos);
HHVM_FE(mb_ereg_search);
HHVM_FE(mb_ereg);
HHVM_FE(mb_eregi_replace);
HHVM_FE(mb_eregi);
HHVM_FE(mb_get_info);
HHVM_FE(mb_http_input);
HHVM_FE(mb_http_output);
HHVM_FE(mb_internal_encoding);
HHVM_FE(mb_language);
HHVM_FE(mb_output_handler);
HHVM_FE(mb_parse_str);
HHVM_FE(mb_preferred_mime_name);
HHVM_FE(mb_regex_encoding);
HHVM_FE(mb_regex_set_options);
HHVM_FE(mb_send_mail);
HHVM_FE(mb_split);
HHVM_FE(mb_strcut);
HHVM_FE(mb_strimwidth);
HHVM_FE(mb_stripos);
HHVM_FE(mb_stristr);
HHVM_FE(mb_strlen);
HHVM_FE(mb_strpos);
HHVM_FE(mb_strrchr);
HHVM_FE(mb_strrichr);
HHVM_FE(mb_strripos);
HHVM_FE(mb_strrpos);
HHVM_FE(mb_strstr);
HHVM_FE(mb_strtolower);
HHVM_FE(mb_strtoupper);
HHVM_FE(mb_strwidth);
HHVM_FE(mb_substitute_character);
HHVM_FE(mb_substr_count);
HHVM_FE(mb_substr);
loadSystemlib();
}
static std::string http_input;
static std::string http_output;
static std::string substitute_character;
} s_mbstring_extension;
std::string mbstringExtension::http_input = "pass";
std::string mbstringExtension::http_output = "pass";
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_847_0 |
crossvul-cpp_data_good_1442_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
* Copyright (C) 2008 by Stefan Rado
* based on admin.cpp by Sebastian Ramacher
* based on admin.cpp in crox branch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
using std::map;
using std::vector;
template <std::size_t N>
struct array_size_helper {
char __place_holder[N];
};
template <class T, std::size_t N>
static array_size_helper<N> array_size(T (&)[N]) {
return array_size_helper<N>();
}
#define ARRAY_SIZE(array) sizeof(array_size((array)))
class CAdminMod : public CModule {
using CModule::PutModule;
struct Setting {
const char* name;
CString type;
};
void PrintVarsHelp(const CString& sFilter, const Setting vars[],
unsigned int uSize, const CString& sDescription) {
CTable VarTable;
VarTable.AddColumn(t_s("Type", "helptable"));
VarTable.AddColumn(t_s("Variables", "helptable"));
std::map<CString, VCString> mvsTypedVariables;
for (unsigned int i = 0; i != uSize; ++i) {
CString sVar = CString(vars[i].name).AsLower();
if (sFilter.empty() || sVar.StartsWith(sFilter) ||
sVar.WildCmp(sFilter)) {
mvsTypedVariables[vars[i].type].emplace_back(vars[i].name);
}
}
for (const auto& i : mvsTypedVariables) {
VarTable.AddRow();
VarTable.SetCell(t_s("Type", "helptable"), i.first);
VarTable.SetCell(
t_s("Variables", "helptable"),
CString(", ").Join(i.second.cbegin(), i.second.cend()));
}
if (!VarTable.empty()) {
PutModule(sDescription);
PutModule(VarTable);
}
}
void PrintHelp(const CString& sLine) {
HandleHelpCommand(sLine);
const CString str = t_s("String");
const CString boolean = t_s("Boolean (true/false)");
const CString integer = t_s("Integer");
const CString number = t_s("Number");
const CString sCmdFilter = sLine.Token(1, false);
const CString sVarFilter = sLine.Token(2, true).AsLower();
if (sCmdFilter.empty() || sCmdFilter.StartsWith("Set") ||
sCmdFilter.StartsWith("Get")) {
Setting vars[] = {
{"Nick", str},
{"Altnick", str},
{"Ident", str},
{"RealName", str},
{"BindHost", str},
{"MultiClients", boolean},
{"DenyLoadMod", boolean},
{"DenySetBindHost", boolean},
{"DefaultChanModes", str},
{"QuitMsg", str},
{"ChanBufferSize", integer},
{"QueryBufferSize", integer},
{"AutoClearChanBuffer", boolean},
{"AutoClearQueryBuffer", boolean},
{"Password", str},
{"JoinTries", integer},
{"MaxJoins", integer},
{"MaxNetworks", integer},
{"MaxQueryBuffers", integer},
{"Timezone", str},
{"Admin", boolean},
{"AppendTimestamp", boolean},
{"PrependTimestamp", boolean},
{"AuthOnlyViaModule", boolean},
{"TimestampFormat", str},
{"DCCBindHost", str},
{"StatusPrefix", str},
#ifdef HAVE_I18N
{"Language", str},
#endif
#ifdef HAVE_ICU
{"ClientEncoding", str},
#endif
};
PrintVarsHelp(sVarFilter, vars, ARRAY_SIZE(vars),
t_s("The following variables are available when "
"using the Set/Get commands:"));
}
if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetNetwork") ||
sCmdFilter.StartsWith("GetNetwork")) {
Setting nvars[] = {
{"Nick", str},
{"Altnick", str},
{"Ident", str},
{"RealName", str},
{"BindHost", str},
{"FloodRate", number},
{"FloodBurst", integer},
{"JoinDelay", integer},
#ifdef HAVE_ICU
{"Encoding", str},
#endif
{"QuitMsg", str},
{"TrustAllCerts", boolean},
{"TrustPKI", boolean},
};
PrintVarsHelp(sVarFilter, nvars, ARRAY_SIZE(nvars),
t_s("The following variables are available when "
"using the SetNetwork/GetNetwork commands:"));
}
if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetChan") ||
sCmdFilter.StartsWith("GetChan")) {
Setting cvars[] = {{"DefModes", str},
{"Key", str},
{"BufferSize", integer},
{"InConfig", boolean},
{"AutoClearChanBuffer", boolean},
{"Detached", boolean}};
PrintVarsHelp(sVarFilter, cvars, ARRAY_SIZE(cvars),
t_s("The following variables are available when "
"using the SetChan/GetChan commands:"));
}
if (sCmdFilter.empty())
PutModule(
t_s("You can use $user as the user name and $network as the "
"network name for modifying your own user and network."));
}
CUser* FindUser(const CString& sUsername) {
if (sUsername.Equals("$me") || sUsername.Equals("$user"))
return GetUser();
CUser* pUser = CZNC::Get().FindUser(sUsername);
if (!pUser) {
PutModule(t_f("Error: User [{1}] does not exist!")(sUsername));
return nullptr;
}
if (pUser != GetUser() && !GetUser()->IsAdmin()) {
PutModule(t_s(
"Error: You need to have admin rights to modify other users!"));
return nullptr;
}
return pUser;
}
CIRCNetwork* FindNetwork(CUser* pUser, const CString& sNetwork) {
if (sNetwork.Equals("$net") || sNetwork.Equals("$network")) {
if (pUser != GetUser()) {
PutModule(t_s(
"Error: You cannot use $network to modify other users!"));
return nullptr;
}
return CModule::GetNetwork();
}
CIRCNetwork* pNetwork = pUser->FindNetwork(sNetwork);
if (!pNetwork) {
PutModule(
t_f("Error: User {1} does not have a network named [{2}].")(
pUser->GetUserName(), sNetwork));
}
return pNetwork;
}
void Get(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUsername = sLine.Token(2, true);
CUser* pUser;
if (sVar.empty()) {
PutModule(t_s("Usage: Get <variable> [username]"));
return;
}
if (sUsername.empty()) {
pUser = GetUser();
} else {
pUser = FindUser(sUsername);
}
if (!pUser) return;
if (sVar == "nick")
PutModule("Nick = " + pUser->GetNick());
else if (sVar == "altnick")
PutModule("AltNick = " + pUser->GetAltNick());
else if (sVar == "ident")
PutModule("Ident = " + pUser->GetIdent());
else if (sVar == "realname")
PutModule("RealName = " + pUser->GetRealName());
else if (sVar == "bindhost")
PutModule("BindHost = " + pUser->GetBindHost());
else if (sVar == "multiclients")
PutModule("MultiClients = " + CString(pUser->MultiClients()));
else if (sVar == "denyloadmod")
PutModule("DenyLoadMod = " + CString(pUser->DenyLoadMod()));
else if (sVar == "denysetbindhost")
PutModule("DenySetBindHost = " + CString(pUser->DenySetBindHost()));
else if (sVar == "defaultchanmodes")
PutModule("DefaultChanModes = " + pUser->GetDefaultChanModes());
else if (sVar == "quitmsg")
PutModule("QuitMsg = " + pUser->GetQuitMsg());
else if (sVar == "buffercount")
PutModule("BufferCount = " + CString(pUser->GetBufferCount()));
else if (sVar == "chanbuffersize")
PutModule("ChanBufferSize = " +
CString(pUser->GetChanBufferSize()));
else if (sVar == "querybuffersize")
PutModule("QueryBufferSize = " +
CString(pUser->GetQueryBufferSize()));
else if (sVar == "keepbuffer")
// XXX compatibility crap, added in 0.207
PutModule("KeepBuffer = " + CString(!pUser->AutoClearChanBuffer()));
else if (sVar == "autoclearchanbuffer")
PutModule("AutoClearChanBuffer = " +
CString(pUser->AutoClearChanBuffer()));
else if (sVar == "autoclearquerybuffer")
PutModule("AutoClearQueryBuffer = " +
CString(pUser->AutoClearQueryBuffer()));
else if (sVar == "maxjoins")
PutModule("MaxJoins = " + CString(pUser->MaxJoins()));
else if (sVar == "notraffictimeout")
PutModule("NoTrafficTimeout = " +
CString(pUser->GetNoTrafficTimeout()));
else if (sVar == "maxnetworks")
PutModule("MaxNetworks = " + CString(pUser->MaxNetworks()));
else if (sVar == "maxquerybuffers")
PutModule("MaxQueryBuffers = " + CString(pUser->MaxQueryBuffers()));
else if (sVar == "jointries")
PutModule("JoinTries = " + CString(pUser->JoinTries()));
else if (sVar == "timezone")
PutModule("Timezone = " + pUser->GetTimezone());
else if (sVar == "appendtimestamp")
PutModule("AppendTimestamp = " +
CString(pUser->GetTimestampAppend()));
else if (sVar == "prependtimestamp")
PutModule("PrependTimestamp = " +
CString(pUser->GetTimestampPrepend()));
else if (sVar == "authonlyviamodule")
PutModule("AuthOnlyViaModule = " +
CString(pUser->AuthOnlyViaModule()));
else if (sVar == "timestampformat")
PutModule("TimestampFormat = " + pUser->GetTimestampFormat());
else if (sVar == "dccbindhost")
PutModule("DCCBindHost = " + CString(pUser->GetDCCBindHost()));
else if (sVar == "admin")
PutModule("Admin = " + CString(pUser->IsAdmin()));
else if (sVar == "statusprefix")
PutModule("StatusPrefix = " + pUser->GetStatusPrefix());
#ifdef HAVE_I18N
else if (sVar == "language")
PutModule("Language = " + (pUser->GetLanguage().empty()
? "en"
: pUser->GetLanguage()));
#endif
#ifdef HAVE_ICU
else if (sVar == "clientencoding")
PutModule("ClientEncoding = " + pUser->GetClientEncoding());
#endif
else
PutModule(t_s("Error: Unknown variable"));
}
void Set(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUserName = sLine.Token(2);
CString sValue = sLine.Token(3, true);
if (sValue.empty()) {
PutModule(t_s("Usage: Set <variable> <username> <value>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
if (sVar == "nick") {
pUser->SetNick(sValue);
PutModule("Nick = " + sValue);
} else if (sVar == "altnick") {
pUser->SetAltNick(sValue);
PutModule("AltNick = " + sValue);
} else if (sVar == "ident") {
pUser->SetIdent(sValue);
PutModule("Ident = " + sValue);
} else if (sVar == "realname") {
pUser->SetRealName(sValue);
PutModule("RealName = " + sValue);
} else if (sVar == "bindhost") {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
if (sValue.Equals(pUser->GetBindHost())) {
PutModule(t_s("This bind host is already set!"));
return;
}
pUser->SetBindHost(sValue);
PutModule("BindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "multiclients") {
bool b = sValue.ToBool();
pUser->SetMultiClients(b);
PutModule("MultiClients = " + CString(b));
} else if (sVar == "denyloadmod") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetDenyLoadMod(b);
PutModule("DenyLoadMod = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "denysetbindhost") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetDenySetBindHost(b);
PutModule("DenySetBindHost = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "defaultchanmodes") {
pUser->SetDefaultChanModes(sValue);
PutModule("DefaultChanModes = " + sValue);
} else if (sVar == "quitmsg") {
pUser->SetQuitMsg(sValue);
PutModule("QuitMsg = " + sValue);
} else if (sVar == "chanbuffersize" || sVar == "buffercount") {
unsigned int i = sValue.ToUInt();
// Admins don't have to honour the buffer limit
if (pUser->SetChanBufferSize(i, GetUser()->IsAdmin())) {
PutModule("ChanBufferSize = " + sValue);
} else {
PutModule(t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
}
} else if (sVar == "querybuffersize") {
unsigned int i = sValue.ToUInt();
// Admins don't have to honour the buffer limit
if (pUser->SetQueryBufferSize(i, GetUser()->IsAdmin())) {
PutModule("QueryBufferSize = " + sValue);
} else {
PutModule(t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
}
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
bool b = !sValue.ToBool();
pUser->SetAutoClearChanBuffer(b);
PutModule("AutoClearChanBuffer = " + CString(b));
} else if (sVar == "autoclearchanbuffer") {
bool b = sValue.ToBool();
pUser->SetAutoClearChanBuffer(b);
PutModule("AutoClearChanBuffer = " + CString(b));
} else if (sVar == "autoclearquerybuffer") {
bool b = sValue.ToBool();
pUser->SetAutoClearQueryBuffer(b);
PutModule("AutoClearQueryBuffer = " + CString(b));
} else if (sVar == "password") {
const CString sSalt = CUtils::GetSalt();
const CString sHash = CUser::SaltedHash(sValue, sSalt);
pUser->SetPass(sHash, CUser::HASH_DEFAULT, sSalt);
PutModule(t_s("Password has been changed!"));
} else if (sVar == "maxjoins") {
unsigned int i = sValue.ToUInt();
pUser->SetMaxJoins(i);
PutModule("MaxJoins = " + CString(pUser->MaxJoins()));
} else if (sVar == "notraffictimeout") {
unsigned int i = sValue.ToUInt();
if (i < 30) {
PutModule(t_s("Timeout can't be less than 30 seconds!"));
} else {
pUser->SetNoTrafficTimeout(i);
PutModule("NoTrafficTimeout = " +
CString(pUser->GetNoTrafficTimeout()));
}
} else if (sVar == "maxnetworks") {
if (GetUser()->IsAdmin()) {
unsigned int i = sValue.ToUInt();
pUser->SetMaxNetworks(i);
PutModule("MaxNetworks = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "maxquerybuffers") {
unsigned int i = sValue.ToUInt();
pUser->SetMaxQueryBuffers(i);
PutModule("MaxQueryBuffers = " + sValue);
} else if (sVar == "jointries") {
unsigned int i = sValue.ToUInt();
pUser->SetJoinTries(i);
PutModule("JoinTries = " + CString(pUser->JoinTries()));
} else if (sVar == "timezone") {
pUser->SetTimezone(sValue);
PutModule("Timezone = " + pUser->GetTimezone());
} else if (sVar == "admin") {
if (GetUser()->IsAdmin() && pUser != GetUser()) {
bool b = sValue.ToBool();
pUser->SetAdmin(b);
PutModule("Admin = " + CString(pUser->IsAdmin()));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "prependtimestamp") {
bool b = sValue.ToBool();
pUser->SetTimestampPrepend(b);
PutModule("PrependTimestamp = " + CString(b));
} else if (sVar == "appendtimestamp") {
bool b = sValue.ToBool();
pUser->SetTimestampAppend(b);
PutModule("AppendTimestamp = " + CString(b));
} else if (sVar == "authonlyviamodule") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetAuthOnlyViaModule(b);
PutModule("AuthOnlyViaModule = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "timestampformat") {
pUser->SetTimestampFormat(sValue);
PutModule("TimestampFormat = " + sValue);
} else if (sVar == "dccbindhost") {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
pUser->SetDCCBindHost(sValue);
PutModule("DCCBindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "statusprefix") {
if (sVar.find_first_of(" \t\n") == CString::npos) {
pUser->SetStatusPrefix(sValue);
PutModule("StatusPrefix = " + sValue);
} else {
PutModule(t_s("That would be a bad idea!"));
}
}
#ifdef HAVE_I18N
else if (sVar == "language") {
auto mTranslations = CTranslationInfo::GetTranslations();
// TODO: maybe stop special-casing English
if (sValue == "en") {
pUser->SetLanguage("");
PutModule("Language is set to English");
} else if (mTranslations.count(sValue)) {
pUser->SetLanguage(sValue);
PutModule("Language = " + sValue);
} else {
VCString vsCodes = {"en"};
for (const auto it : mTranslations) {
vsCodes.push_back(it.first);
}
PutModule(t_f("Supported languages: {1}")(
CString(", ").Join(vsCodes.begin(), vsCodes.end())));
}
}
#endif
#ifdef HAVE_ICU
else if (sVar == "clientencoding") {
pUser->SetClientEncoding(sValue);
PutModule("ClientEncoding = " + pUser->GetClientEncoding());
}
#endif
else
PutModule(t_s("Error: Unknown variable"));
}
void GetNetwork(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
const CString sUsername = sLine.Token(2);
const CString sNetwork = sLine.Token(3);
CIRCNetwork* pNetwork = nullptr;
CUser* pUser;
if (sVar.empty()) {
PutModule(t_s("Usage: GetNetwork <variable> [username] [network]"));
return;
}
if (sUsername.empty()) {
pUser = GetUser();
} else {
pUser = FindUser(sUsername);
}
if (!pUser) {
return;
}
if (sNetwork.empty()) {
if (pUser == GetUser()) {
pNetwork = CModule::GetNetwork();
} else {
PutModule(
t_s("Error: A network must be specified to get another "
"users settings."));
return;
}
if (!pNetwork) {
PutModule(t_s("You are not currently attached to a network."));
return;
}
} else {
pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
PutModule(t_s("Error: Invalid network."));
return;
}
}
if (sVar.Equals("nick")) {
PutModule("Nick = " + pNetwork->GetNick());
} else if (sVar.Equals("altnick")) {
PutModule("AltNick = " + pNetwork->GetAltNick());
} else if (sVar.Equals("ident")) {
PutModule("Ident = " + pNetwork->GetIdent());
} else if (sVar.Equals("realname")) {
PutModule("RealName = " + pNetwork->GetRealName());
} else if (sVar.Equals("bindhost")) {
PutModule("BindHost = " + pNetwork->GetBindHost());
} else if (sVar.Equals("floodrate")) {
PutModule("FloodRate = " + CString(pNetwork->GetFloodRate()));
} else if (sVar.Equals("floodburst")) {
PutModule("FloodBurst = " + CString(pNetwork->GetFloodBurst()));
} else if (sVar.Equals("joindelay")) {
PutModule("JoinDelay = " + CString(pNetwork->GetJoinDelay()));
#ifdef HAVE_ICU
} else if (sVar.Equals("encoding")) {
PutModule("Encoding = " + pNetwork->GetEncoding());
#endif
} else if (sVar.Equals("quitmsg")) {
PutModule("QuitMsg = " + pNetwork->GetQuitMsg());
} else if (sVar.Equals("trustallcerts")) {
PutModule("TrustAllCerts = " + CString(pNetwork->GetTrustAllCerts()));
} else if (sVar.Equals("trustpki")) {
PutModule("TrustPKI = " + CString(pNetwork->GetTrustPKI()));
} else {
PutModule(t_s("Error: Unknown variable"));
}
}
void SetNetwork(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
const CString sUsername = sLine.Token(2);
const CString sNetwork = sLine.Token(3);
const CString sValue = sLine.Token(4, true);
if (sValue.empty()) {
PutModule(t_s(
"Usage: SetNetwork <variable> <username> <network> <value>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) {
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (sVar.Equals("nick")) {
pNetwork->SetNick(sValue);
PutModule("Nick = " + pNetwork->GetNick());
} else if (sVar.Equals("altnick")) {
pNetwork->SetAltNick(sValue);
PutModule("AltNick = " + pNetwork->GetAltNick());
} else if (sVar.Equals("ident")) {
pNetwork->SetIdent(sValue);
PutModule("Ident = " + pNetwork->GetIdent());
} else if (sVar.Equals("realname")) {
pNetwork->SetRealName(sValue);
PutModule("RealName = " + pNetwork->GetRealName());
} else if (sVar.Equals("bindhost")) {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
if (sValue.Equals(pNetwork->GetBindHost())) {
PutModule(t_s("This bind host is already set!"));
return;
}
pNetwork->SetBindHost(sValue);
PutModule("BindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar.Equals("floodrate")) {
pNetwork->SetFloodRate(sValue.ToDouble());
PutModule("FloodRate = " + CString(pNetwork->GetFloodRate()));
} else if (sVar.Equals("floodburst")) {
pNetwork->SetFloodBurst(sValue.ToUShort());
PutModule("FloodBurst = " + CString(pNetwork->GetFloodBurst()));
} else if (sVar.Equals("joindelay")) {
pNetwork->SetJoinDelay(sValue.ToUShort());
PutModule("JoinDelay = " + CString(pNetwork->GetJoinDelay()));
#ifdef HAVE_ICU
} else if (sVar.Equals("encoding")) {
pNetwork->SetEncoding(sValue);
PutModule("Encoding = " + pNetwork->GetEncoding());
#endif
} else if (sVar.Equals("quitmsg")) {
pNetwork->SetQuitMsg(sValue);
PutModule("QuitMsg = " + pNetwork->GetQuitMsg());
} else if (sVar.Equals("trustallcerts")) {
bool b = sValue.ToBool();
pNetwork->SetTrustAllCerts(b);
PutModule("TrustAllCerts = " + CString(b));
} else if (sVar.Equals("trustpki")) {
bool b = sValue.ToBool();
pNetwork->SetTrustPKI(b);
PutModule("TrustPKI = " + CString(b));
} else {
PutModule(t_s("Error: Unknown variable"));
}
}
void AddChan(const CString& sLine) {
const CString sUsername = sLine.Token(1);
const CString sNetwork = sLine.Token(2);
const CString sChan = sLine.Token(3);
if (sChan.empty()) {
PutModule(t_s("Usage: AddChan <username> <network> <channel>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork->FindChan(sChan)) {
PutModule(t_f("Error: User {1} already has a channel named {2}.")(
sUsername, sChan));
return;
}
CChan* pChan = new CChan(sChan, pNetwork, true);
if (pNetwork->AddChan(pChan))
PutModule(t_f("Channel {1} for user {2} added to network {3}.")(
pChan->GetName(), sUsername, pNetwork->GetName()));
else
PutModule(t_f(
"Could not add channel {1} for user {2} to network {3}, does "
"it already exist?")(sChan, sUsername, pNetwork->GetName()));
}
void DelChan(const CString& sLine) {
const CString sUsername = sLine.Token(1);
const CString sNetwork = sLine.Token(2);
const CString sChan = sLine.Token(3);
if (sChan.empty()) {
PutModule(t_s("Usage: DelChan <username> <network> <channel>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
std::vector<CChan*> vChans = pNetwork->FindChans(sChan);
if (vChans.empty()) {
PutModule(
t_f("Error: User {1} does not have any channel matching [{2}] "
"in network {3}")(sUsername, sChan, pNetwork->GetName()));
return;
}
VCString vsNames;
for (const CChan* pChan : vChans) {
const CString& sName = pChan->GetName();
vsNames.push_back(sName);
pNetwork->PutIRC("PART " + sName);
pNetwork->DelChan(sName);
}
PutModule(t_p("Channel {1} is deleted from network {2} of user {3}",
"Channels {1} are deleted from network {2} of user {3}",
vsNames.size())(
CString(", ").Join(vsNames.begin(), vsNames.end()),
pNetwork->GetName(), sUsername));
}
void GetChan(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUsername = sLine.Token(2);
CString sNetwork = sLine.Token(3);
CString sChan = sLine.Token(4, true);
if (sChan.empty()) {
PutModule(
t_s("Usage: GetChan <variable> <username> <network> <chan>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
std::vector<CChan*> vChans = pNetwork->FindChans(sChan);
if (vChans.empty()) {
PutModule(t_f("Error: No channels matching [{1}] found.")(sChan));
return;
}
for (CChan* pChan : vChans) {
if (sVar == "defmodes") {
PutModule(pChan->GetName() + ": DefModes = " +
pChan->GetDefaultModes());
} else if (sVar == "buffersize" || sVar == "buffer") {
CString sValue(pChan->GetBufferCount());
if (!pChan->HasBufferCountSet()) {
sValue += " (default)";
}
PutModule(pChan->GetName() + ": BufferSize = " + sValue);
} else if (sVar == "inconfig") {
PutModule(pChan->GetName() + ": InConfig = " +
CString(pChan->InConfig()));
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
PutModule(pChan->GetName() + ": KeepBuffer = " +
CString(!pChan->AutoClearChanBuffer()));
} else if (sVar == "autoclearchanbuffer") {
CString sValue(pChan->AutoClearChanBuffer());
if (!pChan->HasAutoClearChanBufferSet()) {
sValue += " (default)";
}
PutModule(pChan->GetName() + ": AutoClearChanBuffer = " +
sValue);
} else if (sVar == "detached") {
PutModule(pChan->GetName() + ": Detached = " +
CString(pChan->IsDetached()));
} else if (sVar == "key") {
PutModule(pChan->GetName() + ": Key = " + pChan->GetKey());
} else {
PutModule(t_s("Error: Unknown variable"));
return;
}
}
}
void SetChan(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUsername = sLine.Token(2);
CString sNetwork = sLine.Token(3);
CString sChan = sLine.Token(4);
CString sValue = sLine.Token(5, true);
if (sValue.empty()) {
PutModule(
t_s("Usage: SetChan <variable> <username> <network> <chan> "
"<value>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
std::vector<CChan*> vChans = pNetwork->FindChans(sChan);
if (vChans.empty()) {
PutModule(t_f("Error: No channels matching [{1}] found.")(sChan));
return;
}
for (CChan* pChan : vChans) {
if (sVar == "defmodes") {
pChan->SetDefaultModes(sValue);
PutModule(pChan->GetName() + ": DefModes = " + sValue);
} else if (sVar == "buffersize" || sVar == "buffer") {
unsigned int i = sValue.ToUInt();
if (sValue.Equals("-")) {
pChan->ResetBufferCount();
PutModule(pChan->GetName() + ": BufferSize = " +
CString(pChan->GetBufferCount()));
} else if (pChan->SetBufferCount(i, GetUser()->IsAdmin())) {
// Admins don't have to honour the buffer limit
PutModule(pChan->GetName() + ": BufferSize = " + sValue);
} else {
PutModule(
t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
return;
}
} else if (sVar == "inconfig") {
bool b = sValue.ToBool();
pChan->SetInConfig(b);
PutModule(pChan->GetName() + ": InConfig = " + CString(b));
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
bool b = !sValue.ToBool();
pChan->SetAutoClearChanBuffer(b);
PutModule(pChan->GetName() + ": AutoClearChanBuffer = " +
CString(b));
} else if (sVar == "autoclearchanbuffer") {
if (sValue.Equals("-")) {
pChan->ResetAutoClearChanBuffer();
} else {
bool b = sValue.ToBool();
pChan->SetAutoClearChanBuffer(b);
}
PutModule(pChan->GetName() + ": AutoClearChanBuffer = " +
CString(pChan->AutoClearChanBuffer()));
} else if (sVar == "detached") {
bool b = sValue.ToBool();
if (pChan->IsDetached() != b) {
if (b)
pChan->DetachUser();
else
pChan->AttachUser();
}
PutModule(pChan->GetName() + ": Detached = " + CString(b));
} else if (sVar == "key") {
pChan->SetKey(sValue);
PutModule(pChan->GetName() + ": Key = " + sValue);
} else {
PutModule(t_s("Error: Unknown variable"));
return;
}
}
}
void ListUsers(const CString&) {
if (!GetUser()->IsAdmin()) return;
const map<CString, CUser*>& msUsers = CZNC::Get().GetUserMap();
CTable Table;
Table.AddColumn(t_s("Username", "listusers"));
Table.AddColumn(t_s("Realname", "listusers"));
Table.AddColumn(t_s("IsAdmin", "listusers"));
Table.AddColumn(t_s("Nick", "listusers"));
Table.AddColumn(t_s("AltNick", "listusers"));
Table.AddColumn(t_s("Ident", "listusers"));
Table.AddColumn(t_s("BindHost", "listusers"));
for (const auto& it : msUsers) {
Table.AddRow();
Table.SetCell(t_s("Username", "listusers"), it.first);
Table.SetCell(t_s("Realname", "listusers"),
it.second->GetRealName());
if (!it.second->IsAdmin())
Table.SetCell(t_s("IsAdmin", "listusers"), t_s("No"));
else
Table.SetCell(t_s("IsAdmin", "listusers"), t_s("Yes"));
Table.SetCell(t_s("Nick", "listusers"), it.second->GetNick());
Table.SetCell(t_s("AltNick", "listusers"), it.second->GetAltNick());
Table.SetCell(t_s("Ident", "listusers"), it.second->GetIdent());
Table.SetCell(t_s("BindHost", "listusers"),
it.second->GetBindHost());
}
PutModule(Table);
}
void AddUser(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule(
t_s("Error: You need to have admin rights to add new users!"));
return;
}
const CString sUsername = sLine.Token(1), sPassword = sLine.Token(2);
if (sPassword.empty()) {
PutModule(t_s("Usage: AddUser <username> <password>"));
return;
}
if (CZNC::Get().FindUser(sUsername)) {
PutModule(t_f("Error: User {1} already exists!")(sUsername));
return;
}
CUser* pNewUser = new CUser(sUsername);
CString sSalt = CUtils::GetSalt();
pNewUser->SetPass(CUser::SaltedHash(sPassword, sSalt),
CUser::HASH_DEFAULT, sSalt);
CString sErr;
if (!CZNC::Get().AddUser(pNewUser, sErr)) {
delete pNewUser;
PutModule(t_f("Error: User not added: {1}")(sErr));
return;
}
PutModule(t_f("User {1} added!")(sUsername));
return;
}
void DelUser(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule(
t_s("Error: You need to have admin rights to delete users!"));
return;
}
const CString sUsername = sLine.Token(1, true);
if (sUsername.empty()) {
PutModule(t_s("Usage: DelUser <username>"));
return;
}
CUser* pUser = CZNC::Get().FindUser(sUsername);
if (!pUser) {
PutModule(t_f("Error: User [{1}] does not exist!")(sUsername));
return;
}
if (pUser == GetUser()) {
PutModule(t_s("Error: You can't delete yourself!"));
return;
}
if (!CZNC::Get().DeleteUser(pUser->GetUserName())) {
// This can't happen, because we got the user from FindUser()
PutModule(t_s("Error: Internal error!"));
return;
}
PutModule(t_f("User {1} deleted!")(sUsername));
return;
}
void CloneUser(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule(
t_s("Error: You need to have admin rights to add new users!"));
return;
}
const CString sOldUsername = sLine.Token(1),
sNewUsername = sLine.Token(2, true);
if (sOldUsername.empty() || sNewUsername.empty()) {
PutModule(t_s("Usage: CloneUser <old username> <new username>"));
return;
}
CUser* pOldUser = CZNC::Get().FindUser(sOldUsername);
if (!pOldUser) {
PutModule(t_f("Error: User [{1}] does not exist!")(sOldUsername));
return;
}
CUser* pNewUser = new CUser(sNewUsername);
CString sError;
if (!pNewUser->Clone(*pOldUser, sError)) {
delete pNewUser;
PutModule(t_f("Error: Cloning failed: {1}")(sError));
return;
}
if (!CZNC::Get().AddUser(pNewUser, sError)) {
delete pNewUser;
PutModule(t_f("Error: User not added: {1}")(sError));
return;
}
PutModule(t_f("User {1} added!")(sNewUsername));
return;
}
void AddNetwork(const CString& sLine) {
CString sUser = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CUser* pUser = GetUser();
if (sNetwork.empty()) {
sNetwork = sUser;
} else {
pUser = FindUser(sUser);
if (!pUser) {
return;
}
}
if (sNetwork.empty()) {
PutModule(t_s("Usage: AddNetwork [user] network"));
return;
}
if (!GetUser()->IsAdmin() && !pUser->HasSpaceForNewNetwork()) {
PutStatus(
t_s("Network number limit reached. Ask an admin to increase "
"the limit for you, or delete unneeded networks using /znc "
"DelNetwork <name>"));
return;
}
if (pUser->FindNetwork(sNetwork)) {
PutModule(
t_f("Error: User {1} already has a network with the name {2}")(
pUser->GetUserName(), sNetwork));
return;
}
CString sNetworkAddError;
if (pUser->AddNetwork(sNetwork, sNetworkAddError)) {
PutModule(t_f("Network {1} added to user {2}.")(
sNetwork, pUser->GetUserName()));
} else {
PutModule(t_f(
"Error: Network [{1}] could not be added for user {2}: {3}")(
sNetwork, pUser->GetUserName(), sNetworkAddError));
}
}
void DelNetwork(const CString& sLine) {
CString sUser = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CUser* pUser = GetUser();
if (sNetwork.empty()) {
sNetwork = sUser;
} else {
pUser = FindUser(sUser);
if (!pUser) {
return;
}
}
if (sNetwork.empty()) {
PutModule(t_s("Usage: DelNetwork [user] network"));
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork == CModule::GetNetwork()) {
PutModule(t_f(
"The currently active network can be deleted via {1}status")(
GetUser()->GetStatusPrefix()));
return;
}
if (pUser->DeleteNetwork(sNetwork)) {
PutModule(t_f("Network {1} deleted for user {2}.")(
sNetwork, pUser->GetUserName()));
} else {
PutModule(
t_f("Error: Network {1} could not be deleted for user {2}.")(
sNetwork, pUser->GetUserName()));
}
}
void ListNetworks(const CString& sLine) {
CString sUser = sLine.Token(1);
CUser* pUser = GetUser();
if (!sUser.empty()) {
pUser = FindUser(sUser);
if (!pUser) {
return;
}
}
const vector<CIRCNetwork*>& vNetworks = pUser->GetNetworks();
CTable Table;
Table.AddColumn(t_s("Network", "listnetworks"));
Table.AddColumn(t_s("OnIRC", "listnetworks"));
Table.AddColumn(t_s("IRC Server", "listnetworks"));
Table.AddColumn(t_s("IRC User", "listnetworks"));
Table.AddColumn(t_s("Channels", "listnetworks"));
for (const CIRCNetwork* pNetwork : vNetworks) {
Table.AddRow();
Table.SetCell(t_s("Network", "listnetworks"), pNetwork->GetName());
if (pNetwork->IsIRCConnected()) {
Table.SetCell(t_s("OnIRC", "listnetworks"), t_s("Yes"));
Table.SetCell(t_s("IRC Server", "listnetworks"),
pNetwork->GetIRCServer());
Table.SetCell(t_s("IRC User", "listnetworks"),
pNetwork->GetIRCNick().GetNickMask());
Table.SetCell(t_s("Channels", "listnetworks"),
CString(pNetwork->GetChans().size()));
} else {
Table.SetCell(t_s("OnIRC", "listnetworks"), t_s("No"));
}
}
if (PutModule(Table) == 0) {
PutModule(t_s("No networks"));
}
}
void AddServer(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sServer = sLine.Token(3, true);
if (sServer.empty()) {
PutModule(
t_s("Usage: AddServer <username> <network> <server> [[+]port] "
"[password]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork->AddServer(sServer))
PutModule(t_f("Added IRC Server {1} to network {2} for user {3}.")(
sServer, pNetwork->GetName(), pUser->GetUserName()));
else
PutModule(t_f(
"Error: Could not add IRC server {1} to network {2} for user "
"{3}.")(sServer, pNetwork->GetName(), pUser->GetUserName()));
}
void DelServer(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sServer = sLine.Token(3, true);
unsigned short uPort = sLine.Token(4).ToUShort();
CString sPass = sLine.Token(5);
if (sServer.empty()) {
PutModule(
t_s("Usage: DelServer <username> <network> <server> [[+]port] "
"[password]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
if (pNetwork->DelServer(sServer, uPort, sPass))
PutModule(
t_f("Deleted IRC Server {1} from network {2} for user {3}.")(
sServer, pNetwork->GetName(), pUser->GetUserName()));
else
PutModule(
t_f("Error: Could not delete IRC server {1} from network {2} "
"for user {3}.")(sServer, pNetwork->GetName(),
pUser->GetUserName()));
}
void ReconnectUser(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sNetwork = sLine.Token(2);
if (sNetwork.empty()) {
PutModule(t_s("Usage: Reconnect <username> <network>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) {
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
CIRCSock* pIRCSock = pNetwork->GetIRCSock();
// cancel connection attempt:
if (pIRCSock && !pIRCSock->IsConnected()) {
pIRCSock->Close();
}
// or close existing connection:
else if (pIRCSock) {
pIRCSock->Quit();
}
// then reconnect
pNetwork->SetIRCConnectEnabled(true);
PutModule(t_f("Queued network {1} of user {2} for a reconnect.")(
pNetwork->GetName(), pUser->GetUserName()));
}
void DisconnectUser(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sNetwork = sLine.Token(2);
if (sNetwork.empty()) {
PutModule(t_s("Usage: Disconnect <username> <network>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) {
return;
}
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
pNetwork->SetIRCConnectEnabled(false);
PutModule(t_f("Closed IRC connection for network {1} of user {2}.")(
pNetwork->GetName(), pUser->GetUserName()));
}
void ListCTCP(const CString& sLine) {
CString sUserName = sLine.Token(1, true);
if (sUserName.empty()) {
sUserName = GetUser()->GetUserName();
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
const MCString& msCTCPReplies = pUser->GetCTCPReplies();
CTable Table;
Table.AddColumn(t_s("Request", "listctcp"));
Table.AddColumn(t_s("Reply", "listctcp"));
for (const auto& it : msCTCPReplies) {
Table.AddRow();
Table.SetCell(t_s("Request", "listctcp"), it.first);
Table.SetCell(t_s("Reply", "listctcp"), it.second);
}
if (Table.empty()) {
PutModule(t_f("No CTCP replies for user {1} are configured")(
pUser->GetUserName()));
} else {
PutModule(t_f("CTCP replies for user {1}:")(pUser->GetUserName()));
PutModule(Table);
}
}
void AddCTCP(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sCTCPRequest = sLine.Token(2);
CString sCTCPReply = sLine.Token(3, true);
if (sCTCPRequest.empty()) {
sCTCPRequest = sUserName;
sCTCPReply = sLine.Token(2, true);
sUserName = GetUser()->GetUserName();
}
if (sCTCPRequest.empty()) {
PutModule(t_s("Usage: AddCTCP [user] [request] [reply]"));
PutModule(
t_s("This will cause ZNC to reply to the CTCP instead of "
"forwarding it to clients."));
PutModule(t_s(
"An empty reply will cause the CTCP request to be blocked."));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
pUser->AddCTCPReply(sCTCPRequest, sCTCPReply);
if (sCTCPReply.empty()) {
PutModule(t_f("CTCP requests {1} to user {2} will now be blocked.")(
sCTCPRequest.AsUpper(), pUser->GetUserName()));
} else {
PutModule(
t_f("CTCP requests {1} to user {2} will now get reply: {3}")(
sCTCPRequest.AsUpper(), pUser->GetUserName(), sCTCPReply));
}
}
void DelCTCP(const CString& sLine) {
CString sUserName = sLine.Token(1);
CString sCTCPRequest = sLine.Token(2, true);
if (sCTCPRequest.empty()) {
sCTCPRequest = sUserName;
sUserName = GetUser()->GetUserName();
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
if (sCTCPRequest.empty()) {
PutModule(t_s("Usage: DelCTCP [user] [request]"));
return;
}
if (pUser->DelCTCPReply(sCTCPRequest)) {
PutModule(t_f(
"CTCP requests {1} to user {2} will now be sent to IRC clients")(
sCTCPRequest.AsUpper(), pUser->GetUserName()));
} else {
PutModule(
t_f("CTCP requests {1} to user {2} will be sent to IRC clients "
"(nothing has changed)")(sCTCPRequest.AsUpper(),
pUser->GetUserName()));
}
}
void LoadModuleFor(CModules& Modules, const CString& sModName,
const CString& sArgs, CModInfo::EModuleType eType,
CUser* pUser, CIRCNetwork* pNetwork) {
if (pUser->DenyLoadMod() && !GetUser()->IsAdmin()) {
PutModule(t_s("Loading modules has been disabled."));
return;
}
CString sModRet;
CModule* pMod = Modules.FindModule(sModName);
if (!pMod) {
if (!Modules.LoadModule(sModName, sArgs, eType, pUser, pNetwork,
sModRet)) {
PutModule(t_f("Error: Unable to load module {1}: {2}")(
sModName, sModRet));
} else {
PutModule(t_f("Loaded module {1}")(sModName));
}
} else if (pMod->GetArgs() != sArgs) {
if (!Modules.ReloadModule(sModName, sArgs, pUser, pNetwork,
sModRet)) {
PutModule(t_f("Error: Unable to reload module {1}: {2}")(
sModName, sModRet));
} else {
PutModule(t_f("Reloaded module {1}")(sModName));
}
} else {
PutModule(
t_f("Error: Unable to load module {1} because it is already "
"loaded")(sModName));
}
}
void LoadModuleForUser(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sModName = sLine.Token(2);
CString sArgs = sLine.Token(3, true);
if (sModName.empty()) {
PutModule(t_s("Usage: LoadModule <username> <modulename> [args]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
LoadModuleFor(pUser->GetModules(), sModName, sArgs,
CModInfo::UserModule, pUser, nullptr);
}
void LoadModuleForNetwork(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sModName = sLine.Token(3);
CString sArgs = sLine.Token(4, true);
if (sModName.empty()) {
PutModule(
t_s("Usage: LoadNetModule <username> <network> <modulename> "
"[args]"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
LoadModuleFor(pNetwork->GetModules(), sModName, sArgs,
CModInfo::NetworkModule, pUser, pNetwork);
}
void UnLoadModuleFor(CModules& Modules, const CString& sModName,
CUser* pUser) {
if (pUser->DenyLoadMod() && !GetUser()->IsAdmin()) {
PutModule(t_s("Loading modules has been disabled."));
return;
}
if (Modules.FindModule(sModName) == this) {
PutModule(t_f("Please use /znc unloadmod {1}")(sModName));
return;
}
CString sModRet;
if (!Modules.UnloadModule(sModName, sModRet)) {
PutModule(t_f("Error: Unable to unload module {1}: {2}")(sModName,
sModRet));
} else {
PutModule(t_f("Unloaded module {1}")(sModName));
}
}
void UnLoadModuleForUser(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sModName = sLine.Token(2);
if (sModName.empty()) {
PutModule(t_s("Usage: UnloadModule <username> <modulename>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
UnLoadModuleFor(pUser->GetModules(), sModName, pUser);
}
void UnLoadModuleForNetwork(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
CString sModName = sLine.Token(3);
if (sModName.empty()) {
PutModule(t_s(
"Usage: UnloadNetModule <username> <network> <modulename>"));
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) {
return;
}
UnLoadModuleFor(pNetwork->GetModules(), sModName, pUser);
}
void ListModulesFor(CModules& Modules) {
CTable Table;
Table.AddColumn(t_s("Name", "listmodules"));
Table.AddColumn(t_s("Arguments", "listmodules"));
for (const CModule* pMod : Modules) {
Table.AddRow();
Table.SetCell(t_s("Name", "listmodules"), pMod->GetModName());
Table.SetCell(t_s("Arguments", "listmodules"), pMod->GetArgs());
}
PutModule(Table);
}
void ListModulesForUser(const CString& sLine) {
CString sUsername = sLine.Token(1);
if (sUsername.empty()) {
PutModule("Usage: ListMods <username>");
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
if (pUser->GetModules().empty()) {
PutModule(
t_f("User {1} has no modules loaded.")(pUser->GetUserName()));
return;
}
PutModule(t_f("Modules loaded for user {1}:")(pUser->GetUserName()));
ListModulesFor(pUser->GetModules());
}
void ListModulesForNetwork(const CString& sLine) {
CString sUsername = sLine.Token(1);
CString sNetwork = sLine.Token(2);
if (sNetwork.empty()) {
PutModule("Usage: ListNetMods <username> <network>");
return;
}
CUser* pUser = FindUser(sUsername);
if (!pUser) return;
CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork);
if (!pNetwork) return;
if (pNetwork->GetModules().empty()) {
PutModule(t_f("Network {1} of user {2} has no modules loaded.")(
pNetwork->GetName(), pUser->GetUserName()));
return;
}
PutModule(t_f("Modules loaded for network {1} of user {2}:")(
pNetwork->GetName(), pUser->GetUserName()));
ListModulesFor(pNetwork->GetModules());
}
public:
MODCONSTRUCTOR(CAdminMod) {
AddCommand("Help", t_d("[command] [variable]"),
t_d("Prints help for matching commands and variables"),
[=](const CString& sLine) { PrintHelp(sLine); });
AddCommand(
"Get", t_d("<variable> [username]"),
t_d("Prints the variable's value for the given or current user"),
[=](const CString& sLine) { Get(sLine); });
AddCommand("Set", t_d("<variable> <username> <value>"),
t_d("Sets the variable's value for the given user"),
[=](const CString& sLine) { Set(sLine); });
AddCommand("GetNetwork", t_d("<variable> [username] [network]"),
t_d("Prints the variable's value for the given network"),
[=](const CString& sLine) { GetNetwork(sLine); });
AddCommand("SetNetwork", t_d("<variable> <username> <network> <value>"),
t_d("Sets the variable's value for the given network"),
[=](const CString& sLine) { SetNetwork(sLine); });
AddCommand("GetChan", t_d("<variable> [username] <network> <chan>"),
t_d("Prints the variable's value for the given channel"),
[=](const CString& sLine) { GetChan(sLine); });
AddCommand("SetChan",
t_d("<variable> <username> <network> <chan> <value>"),
t_d("Sets the variable's value for the given channel"),
[=](const CString& sLine) { SetChan(sLine); });
AddCommand("AddChan", t_d("<username> <network> <chan>"),
t_d("Adds a new channel"),
[=](const CString& sLine) { AddChan(sLine); });
AddCommand("DelChan", t_d("<username> <network> <chan>"),
t_d("Deletes a channel"),
[=](const CString& sLine) { DelChan(sLine); });
AddCommand("ListUsers", "", t_d("Lists users"),
[=](const CString& sLine) { ListUsers(sLine); });
AddCommand("AddUser", t_d("<username> <password>"),
t_d("Adds a new user"),
[=](const CString& sLine) { AddUser(sLine); });
AddCommand("DelUser", t_d("<username>"), t_d("Deletes a user"),
[=](const CString& sLine) { DelUser(sLine); });
AddCommand("CloneUser", t_d("<old username> <new username>"),
t_d("Clones a user"),
[=](const CString& sLine) { CloneUser(sLine); });
AddCommand("AddServer", t_d("<username> <network> <server>"),
t_d("Adds a new IRC server for the given or current user"),
[=](const CString& sLine) { AddServer(sLine); });
AddCommand("DelServer", t_d("<username> <network> <server>"),
t_d("Deletes an IRC server from the given or current user"),
[=](const CString& sLine) { DelServer(sLine); });
AddCommand("Reconnect", t_d("<username> <network>"),
t_d("Cycles the user's IRC server connection"),
[=](const CString& sLine) { ReconnectUser(sLine); });
AddCommand("Disconnect", t_d("<username> <network>"),
t_d("Disconnects the user from their IRC server"),
[=](const CString& sLine) { DisconnectUser(sLine); });
AddCommand("LoadModule", t_d("<username> <modulename> [args]"),
t_d("Loads a Module for a user"),
[=](const CString& sLine) { LoadModuleForUser(sLine); });
AddCommand("UnLoadModule", t_d("<username> <modulename>"),
t_d("Removes a Module of a user"),
[=](const CString& sLine) { UnLoadModuleForUser(sLine); });
AddCommand("ListMods", t_d("<username>"),
t_d("Get the list of modules for a user"),
[=](const CString& sLine) { ListModulesForUser(sLine); });
AddCommand("LoadNetModule",
t_d("<username> <network> <modulename> [args]"),
t_d("Loads a Module for a network"),
[=](const CString& sLine) { LoadModuleForNetwork(sLine); });
AddCommand(
"UnLoadNetModule", t_d("<username> <network> <modulename>"),
t_d("Removes a Module of a network"),
[=](const CString& sLine) { UnLoadModuleForNetwork(sLine); });
AddCommand("ListNetMods", t_d("<username> <network>"),
t_d("Get the list of modules for a network"),
[=](const CString& sLine) { ListModulesForNetwork(sLine); });
AddCommand("ListCTCPs", t_d("<username>"),
t_d("List the configured CTCP replies"),
[=](const CString& sLine) { ListCTCP(sLine); });
AddCommand("AddCTCP", t_d("<username> <ctcp> [reply]"),
t_d("Configure a new CTCP reply"),
[=](const CString& sLine) { AddCTCP(sLine); });
AddCommand("DelCTCP", t_d("<username> <ctcp>"),
t_d("Remove a CTCP reply"),
[=](const CString& sLine) { DelCTCP(sLine); });
// Network commands
AddCommand("AddNetwork", t_d("[username] <network>"),
t_d("Add a network for a user"),
[=](const CString& sLine) { AddNetwork(sLine); });
AddCommand("DelNetwork", t_d("[username] <network>"),
t_d("Delete a network for a user"),
[=](const CString& sLine) { DelNetwork(sLine); });
AddCommand("ListNetworks", t_d("[username]"),
t_d("List all networks for a user"),
[=](const CString& sLine) { ListNetworks(sLine); });
}
~CAdminMod() override {}
};
template <>
void TModInfo<CAdminMod>(CModInfo& Info) {
Info.SetWikiPage("controlpanel");
}
USERMODULEDEFS(CAdminMod,
t_s("Dynamic configuration through IRC. Allows editing only "
"yourself if you're not ZNC admin."))
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1442_0 |
crossvul-cpp_data_good_1376_0 | /*
* Copyright 2004-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/protocol/TProtocolException.h>
#include <folly/Format.h>
namespace apache { namespace thrift { namespace protocol {
[[noreturn]] void TProtocolException::throwUnionMissingStop() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"missing stop marker to terminate a union");
}
[[noreturn]] void TProtocolException::throwReportedTypeMismatch() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"The reported type of thrift element does not match the serialized type");
}
[[noreturn]] void TProtocolException::throwNegativeSize() {
throw TProtocolException(TProtocolException::NEGATIVE_SIZE);
}
[[noreturn]] void TProtocolException::throwExceededSizeLimit() {
throw TProtocolException(TProtocolException::SIZE_LIMIT);
}
[[noreturn]] void TProtocolException::throwMissingRequiredField(
folly::StringPiece field,
folly::StringPiece type) {
constexpr auto fmt =
"Required field '{}' was not found in serialized data! Struct: {}";
throw TProtocolException(
TProtocolException::MISSING_REQUIRED_FIELD,
folly::sformat(fmt, field, type));
}
[[noreturn]] void TProtocolException::throwBoolValueOutOfRange(uint8_t value) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
folly::sformat(
"Attempt to interpret value {} as bool, probably the data is corrupted",
value));
}
[[noreturn]] void TProtocolException::throwInvalidSkipType(TType type) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
folly::sformat(
"Encountered invalid field/element type ({}) during skipping",
static_cast<uint8_t>(type)));
}
}}}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1376_0 |
crossvul-cpp_data_bad_239_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Query.h>
using std::set;
using std::map;
using std::vector;
#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \
{ \
CModule* pModule = nullptr; \
if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
pModule->SetClient(CLIENT); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(NETWORK)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
(USER)->GetModules().UnloadModule(MOD); \
} \
} \
} else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \
try { \
CClient* pOldClient = pModule->GetClient(); \
CIRCNetwork* pOldNetwork = pModule->GetNetwork(); \
CUser* pOldUser = pModule->GetUser(); \
pModule->SetClient(CLIENT); \
pModule->SetNetwork(NETWORK); \
pModule->SetUser(USER); \
pModule->FUNC; \
pModule->SetClient(pOldClient); \
pModule->SetNetwork(pOldNetwork); \
pModule->SetUser(pOldUser); \
} catch (const CModule::EModException& e) { \
if (e == CModule::UNLOAD) { \
CZNC::Get().GetModules().UnloadModule(MOD); \
} \
} \
} else { \
PutStatus(t_f("No such module {1}")(MOD)); \
} \
}
CClient::~CClient() {
if (m_spAuth) {
CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth);
pAuth->Invalidate();
}
if (m_pUser != nullptr) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CClient::SendRequiredPasswordNotice() {
PutClient(":irc.znc.in 464 " + GetNick() + " :Password required");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"You need to send your password. "
"Configure your client to send a server password.");
PutClient(
":irc.znc.in NOTICE " + GetNick() + " :*** "
"To connect now, you can use /quote PASS <username>:<password>, "
"or /quote PASS <username>/<network>:<password> to connect to a "
"specific network.");
}
void CClient::ReadLine(const CString& sData) {
CLanguageScope user_lang(GetUser() ? GetUser()->GetLanguage() : "");
CString sLine = sData;
sLine.TrimRight("\n\r");
DEBUG("(" << GetFullName() << ") CLI -> ZNC ["
<< CDebug::Filter(sLine) << "]");
bool bReturn = false;
if (IsAttached()) {
NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn);
}
if (bReturn) return;
CMessage Message(sLine);
Message.SetClient(this);
if (IsAttached()) {
NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
} else {
GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn);
}
if (bReturn) return;
CString sCommand = Message.GetCommand();
if (!IsAttached()) {
// The following commands happen before authentication with ZNC
if (sCommand.Equals("PASS")) {
m_bGotPass = true;
CString sAuthLine = Message.GetParam(0);
ParsePass(sAuthLine);
AuthUser();
// Don't forward this msg. ZNC has already registered us.
return;
} else if (sCommand.Equals("NICK")) {
CString sNick = Message.GetParam(0);
m_sNick = sNick;
m_bGotNick = true;
AuthUser();
// Don't forward this msg. ZNC will handle nick changes until auth
// is complete
return;
} else if (sCommand.Equals("USER")) {
CString sAuthLine = Message.GetParam(0);
if (m_sUser.empty() && !sAuthLine.empty()) {
ParseUser(sAuthLine);
}
m_bGotUser = true;
if (m_bGotPass) {
AuthUser();
} else if (!m_bInCap) {
SendRequiredPasswordNotice();
}
// Don't forward this msg. ZNC has already registered us.
return;
}
}
if (Message.GetType() == CMessage::Type::Capability) {
HandleCap(Message);
// Don't let the client talk to the server directly about CAP,
// we don't want anything enabled that ZNC does not support.
return;
}
if (!m_pUser) {
// Only CAP, NICK, USER and PASS are allowed before login
return;
}
switch (Message.GetType()) {
case CMessage::Type::Action:
bReturn = OnActionMessage(Message);
break;
case CMessage::Type::CTCP:
bReturn = OnCTCPMessage(Message);
break;
case CMessage::Type::Join:
bReturn = OnJoinMessage(Message);
break;
case CMessage::Type::Mode:
bReturn = OnModeMessage(Message);
break;
case CMessage::Type::Notice:
bReturn = OnNoticeMessage(Message);
break;
case CMessage::Type::Part:
bReturn = OnPartMessage(Message);
break;
case CMessage::Type::Ping:
bReturn = OnPingMessage(Message);
break;
case CMessage::Type::Pong:
bReturn = OnPongMessage(Message);
break;
case CMessage::Type::Quit:
bReturn = OnQuitMessage(Message);
break;
case CMessage::Type::Text:
bReturn = OnTextMessage(Message);
break;
case CMessage::Type::Topic:
bReturn = OnTopicMessage(Message);
break;
default:
bReturn = OnOtherMessage(Message);
break;
}
if (bReturn) return;
PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags));
}
void CClient::SetNick(const CString& s) { m_sNick = s; }
void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect,
bool bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientDisconnected(this);
if (bDisconnect) {
ClearServerDependentCaps();
// Tell the client they are no longer in these channels.
const vector<CChan*>& vChans = m_pNetwork->GetChans();
for (const CChan* pChan : vChans) {
if (!(pChan->IsDetached())) {
PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() +
" PART " + pChan->GetName());
}
}
}
} else if (m_pUser) {
m_pUser->UserDisconnected(this);
}
m_pNetwork = pNetwork;
if (bReconnect) {
if (m_pNetwork) {
m_pNetwork->ClientConnected(this);
} else if (m_pUser) {
m_pUser->UserConnected(this);
}
}
}
const vector<CClient*>& CClient::GetClients() const {
if (m_pNetwork) {
return m_pNetwork->GetClients();
}
return m_pUser->GetUserClients();
}
const CIRCSock* CClient::GetIRCSock() const {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
CIRCSock* CClient::GetIRCSock() {
if (m_pNetwork) {
return m_pNetwork->GetIRCSock();
}
return nullptr;
}
void CClient::StatusCTCP(const CString& sLine) {
CString sCommand = sLine.Token(0);
if (sCommand.Equals("PING")) {
PutStatusNotice("\001PING " + sLine.Token(1, true) + "\001");
} else if (sCommand.Equals("VERSION")) {
PutStatusNotice("\001VERSION " + CZNC::GetTag() + "\001");
}
}
bool CClient::SendMotd() {
const VCString& vsMotd = CZNC::Get().GetMotd();
if (!vsMotd.size()) {
return false;
}
for (const CString& sLine : vsMotd) {
if (m_pNetwork) {
PutStatusNotice(m_pNetwork->ExpandString(sLine));
} else {
PutStatusNotice(m_pUser->ExpandString(sLine));
}
}
return true;
}
void CClient::AuthUser() {
if (!m_bGotNick || !m_bGotUser || !m_bGotPass || m_bInCap || IsAttached())
return;
m_spAuth = std::make_shared<CClientAuth>(this, m_sUser, m_sPass);
CZNC::Get().AuthUser(m_spAuth);
}
CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername,
const CString& sPassword)
: CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {}
void CClientAuth::RefusedLogin(const CString& sReason) {
if (m_pClient) {
m_pClient->RefuseLogin(sReason);
}
}
CString CAuthBase::GetRemoteIP() const {
if (m_pSock) return m_pSock->GetRemoteIP();
return "";
}
void CAuthBase::Invalidate() { m_pSock = nullptr; }
void CAuthBase::AcceptLogin(CUser& User) {
if (m_pSock) {
AcceptedLogin(User);
Invalidate();
}
}
void CAuthBase::RefuseLogin(const CString& sReason) {
if (!m_pSock) return;
CUser* pUser = CZNC::Get().FindUser(GetUsername());
// If the username is valid, notify that user that someone tried to
// login. Use sReason because there are other reasons than "wrong
// password" for a login to be rejected (e.g. fail2ban).
if (pUser) {
pUser->PutStatusNotice(t_f(
"A client from {1} attempted to login as you, but was rejected: "
"{2}")(GetRemoteIP(), sReason));
}
GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING);
RefusedLogin(sReason);
Invalidate();
}
void CClient::RefuseLogin(const CString& sReason) {
PutStatus("Bad username and/or password.");
PutClient(":irc.znc.in 464 " + GetNick() + " :" + sReason);
Close(Csock::CLT_AFTERWRITE);
}
void CClientAuth::AcceptedLogin(CUser& User) {
if (m_pClient) {
m_pClient->AcceptLogin(User);
}
}
void CClient::AcceptLogin(CUser& User) {
m_sPass = "";
m_pUser = &User;
// Set our proper timeout and set back our proper timeout mode
// (constructor set a different timeout and mode)
SetTimeout(User.GetNoTrafficTimeout(), TMO_READ);
SetSockName("USR::" + m_pUser->GetUserName());
SetEncoding(m_pUser->GetClientEncoding());
if (!m_sNetwork.empty()) {
m_pNetwork = m_pUser->FindNetwork(m_sNetwork);
if (!m_pNetwork) {
PutStatus(t_f("Network {1} doesn't exist.")(m_sNetwork));
}
} else if (!m_pUser->GetNetworks().empty()) {
// If a user didn't supply a network, and they have a network called
// "default" then automatically use this network.
m_pNetwork = m_pUser->FindNetwork("default");
// If no "default" network, try "user" network. It's for compatibility
// with early network stuff in ZNC, which converted old configs to
// "user" network.
if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user");
// Otherwise, just try any network of the user.
if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin();
if (m_pNetwork && m_pUser->GetNetworks().size() > 1) {
PutStatusNotice(
t_s("You have several networks configured, but no network was "
"specified for the connection."));
PutStatusNotice(
t_f("Selecting network {1}. To see list of all configured "
"networks, use /znc ListNetworks")(m_pNetwork->GetName()));
PutStatusNotice(t_f(
"If you want to choose another network, use /znc JumpNetwork "
"<network>, or connect to ZNC with username {1}/<network> "
"(instead of just {1})")(m_pUser->GetUserName()));
}
} else {
PutStatusNotice(
t_s("You have no networks configured. Use /znc AddNetwork "
"<network> to add one."));
}
SetNetwork(m_pNetwork, false);
SendMotd();
NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING);
}
void CClient::Timeout() { PutClient("ERROR :" + t_s("Closing link: Timeout")); }
void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); }
void CClient::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
}
void CClient::Disconnected() {
DEBUG(GetSockName() << " == Disconnected()");
CIRCNetwork* pNetwork = m_pNetwork;
SetNetwork(nullptr, false, false);
if (m_pUser) {
NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this,
NOTHING);
}
}
void CClient::ReachedMaxBuffer() {
DEBUG(GetSockName() << " == ReachedMaxBuffer()");
if (IsAttached()) {
PutClient("ERROR :" + t_s("Closing link: Too long raw line"));
}
Close();
}
void CClient::BouncedOff() {
PutStatusNotice(
t_s("You are being disconnected because another user just "
"authenticated as you."));
Close(Csock::CLT_AFTERWRITE);
}
void CClient::PutIRC(const CString& sLine) {
if (m_pNetwork) {
m_pNetwork->PutIRC(sLine);
}
}
CString CClient::GetFullName() const {
if (!m_pUser) return GetRemoteIP();
CString sFullName = m_pUser->GetUserName();
if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier;
if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName();
return sFullName;
}
void CClient::PutClient(const CString& sLine) {
PutClient(CMessage(sLine));
}
bool CClient::PutClient(const CMessage& Message) {
if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
return false;
} else if (!m_bAccountNotify &&
Message.GetType() == CMessage::Type::Account) {
return false;
}
CMessage Msg(Message);
const CIRCSock* pIRCSock = GetIRCSock();
if (pIRCSock) {
if (Msg.GetType() == CMessage::Type::Numeric) {
unsigned int uCode = Msg.As<CNumericMessage>().GetCode();
if (uCode == 352) { // RPL_WHOREPLY
if (!m_bNamesx && pIRCSock->HasNamesx()) {
// The server has NAMESX, but the client doesn't, so we need
// to remove extra prefixes
CString sNick = Msg.GetParam(6);
if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
CString sNewNick = sNick;
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNewNick = sNick[0] + sNick.substr(pos);
}
Msg.SetParam(6, sNewNick);
}
}
} else if (uCode == 353) { // RPL_NAMES
if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
(!m_bUHNames && pIRCSock->HasUHNames())) {
// The server has either UHNAMES or NAMESX, but the client
// is missing either or both
CString sNicks = Msg.GetParam(3);
VCString vsNicks;
sNicks.Split(" ", vsNicks, false);
for (CString& sNick : vsNicks) {
if (sNick.empty()) break;
if (!m_bNamesx && pIRCSock->HasNamesx() &&
pIRCSock->IsPermChar(sNick[0])) {
// The server has NAMESX, but the client doesn't, so
// we just use the first perm char
size_t pos =
sNick.find_first_not_of(pIRCSock->GetPerms());
if (pos >= 2 && pos != CString::npos) {
sNick = sNick[0] + sNick.substr(pos);
}
}
if (!m_bUHNames && pIRCSock->HasUHNames()) {
// The server has UHNAMES, but the client doesn't,
// so we strip away ident and host
sNick = sNick.Token(0, false, "!");
}
}
Msg.SetParam(
3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
}
}
} else if (Msg.GetType() == CMessage::Type::Join) {
if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
}
}
}
MCString mssTags;
for (const auto& it : Msg.GetTags()) {
if (IsTagEnabled(it.first)) {
mssTags[it.first] = it.second;
}
}
if (HasServerTime()) {
// If the server didn't set the time tag, manually set it
mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
}
Msg.SetTags(mssTags);
Msg.SetClient(this);
Msg.SetNetwork(m_pNetwork);
bool bReturn = false;
NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
return PutClientRaw(Msg.ToString());
}
bool CClient::PutClientRaw(const CString& sLine) {
CString sCopy = sLine;
bool bReturn = false;
NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
&bReturn);
if (bReturn) return false;
DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
<< CDebug::Filter(sCopy) << "]");
Write(sCopy + "\r\n");
return true;
}
void CClient::PutStatusNotice(const CString& sLine) {
PutModNotice("status", sLine);
}
unsigned int CClient::PutStatus(const CTable& table) {
unsigned int idx = 0;
CString sLine;
while (table.GetLine(idx++, sLine)) PutStatus(sLine);
return idx - 1;
}
void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); }
void CClient::PutModNotice(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in NOTICE " << GetNick() << " :" << sLine
<< "]");
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " +
GetNick() + " :" + sLine + "\r\n");
}
void CClient::PutModule(const CString& sModule, const CString& sLine) {
if (!m_pUser) {
return;
}
DEBUG("(" << GetFullName()
<< ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine
<< "]");
VCString vsLines;
sLine.Split("\n", vsLines);
for (const CString& s : vsLines) {
Write(":" + m_pUser->GetStatusPrefix() +
((sModule.empty()) ? "status" : sModule) +
"!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n");
}
}
CString CClient::GetNick(bool bAllowIRCNick) const {
CString sRet;
const CIRCSock* pSock = GetIRCSock();
if (bAllowIRCNick && pSock && pSock->IsAuthed()) {
sRet = pSock->GetNick();
}
return (sRet.empty()) ? m_sNick : sRet;
}
CString CClient::GetNickMask() const {
if (GetIRCSock() && GetIRCSock()->IsAuthed()) {
return GetIRCSock()->GetNickMask();
}
CString sHost =
m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost();
if (sHost.empty()) {
sHost = "irc.znc.in";
}
return GetNick() + "!" +
(m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" +
sHost;
}
bool CClient::IsValidIdentifier(const CString& sIdentifier) {
// ^[-\w]+$
if (sIdentifier.empty()) {
return false;
}
const char* p = sIdentifier.c_str();
while (*p) {
if (*p != '_' && *p != '-' && !isalnum(*p)) {
return false;
}
p++;
}
return true;
}
void CClient::RespondCap(const CString& sResponse) {
PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse);
}
void CClient::HandleCap(const CMessage& Message) {
CString sSubCmd = Message.GetParam(0);
if (sSubCmd.Equals("LS")) {
SCString ssOfferCaps;
for (const auto& it : m_mCoreCaps) {
bool bServerDependent = std::get<0>(it.second);
if (!bServerDependent ||
m_ssServerDependentCaps.count(it.first) > 0)
ssOfferCaps.insert(it.first);
}
GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING);
CString sRes =
CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end());
RespondCap("LS :" + sRes);
m_bInCap = true;
if (Message.GetParam(1).ToInt() >= 302) {
m_bCapNotify = true;
}
} else if (sSubCmd.Equals("END")) {
m_bInCap = false;
if (!IsAttached()) {
if (!m_pUser && m_bGotUser && !m_bGotPass) {
SendRequiredPasswordNotice();
} else {
AuthUser();
}
}
} else if (sSubCmd.Equals("REQ")) {
VCString vsTokens;
Message.GetParam(1).Split(" ", vsTokens, false);
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
bool bAccepted = false;
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
bAccepted = !bServerDependent ||
m_ssServerDependentCaps.count(sCap) > 0;
}
GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal),
&bAccepted);
if (!bAccepted) {
// Some unsupported capability is requested
RespondCap("NAK :" + Message.GetParam(1));
return;
}
}
// All is fine, we support what was requested
for (const CString& sToken : vsTokens) {
bool bVal = true;
CString sCap = sToken;
if (sCap.TrimPrefix("-")) bVal = false;
auto handler_it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != handler_it) {
const auto& handler = std::get<1>(handler_it->second);
handler(bVal);
}
GLOBALMODULECALL(OnClientCapRequest(this, sCap, bVal), NOTHING);
if (bVal) {
m_ssAcceptedCaps.insert(sCap);
} else {
m_ssAcceptedCaps.erase(sCap);
}
}
RespondCap("ACK :" + Message.GetParam(1));
} else if (sSubCmd.Equals("LIST")) {
CString sList =
CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end());
RespondCap("LIST :" + sList);
} else {
PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd +
" :Invalid CAP subcommand");
}
}
void CClient::ParsePass(const CString& sAuthLine) {
// [user[@identifier][/network]:]password
const size_t uColon = sAuthLine.find(":");
if (uColon != CString::npos) {
m_sPass = sAuthLine.substr(uColon + 1);
ParseUser(sAuthLine.substr(0, uColon));
} else {
m_sPass = sAuthLine;
}
}
void CClient::ParseUser(const CString& sAuthLine) {
// user[@identifier][/network]
const size_t uSlash = sAuthLine.rfind("/");
if (uSlash != CString::npos) {
m_sNetwork = sAuthLine.substr(uSlash + 1);
ParseIdentifier(sAuthLine.substr(0, uSlash));
} else {
ParseIdentifier(sAuthLine);
}
}
void CClient::ParseIdentifier(const CString& sAuthLine) {
// user[@identifier]
const size_t uAt = sAuthLine.rfind("@");
if (uAt != CString::npos) {
const CString sId = sAuthLine.substr(uAt + 1);
if (IsValidIdentifier(sId)) {
m_sIdentifier = sId;
m_sUser = sAuthLine.substr(0, uAt);
} else {
m_sUser = sAuthLine;
}
} else {
m_sUser = sAuthLine;
}
}
void CClient::SetTagSupport(const CString& sTag, bool bState) {
if (bState) {
m_ssSupportedTags.insert(sTag);
} else {
m_ssSupportedTags.erase(sTag);
}
}
void CClient::NotifyServerDependentCaps(const SCString& ssCaps) {
for (const CString& sCap : ssCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
bool bServerDependent = std::get<0>(it->second);
if (bServerDependent) {
m_ssServerDependentCaps.insert(sCap);
}
}
}
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps);
}
}
void CClient::ClearServerDependentCaps() {
if (HasCapNotify() && !m_ssServerDependentCaps.empty()) {
CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(),
m_ssServerDependentCaps.end());
PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps);
for (const CString& sCap : m_ssServerDependentCaps) {
const auto& it = m_mCoreCaps.find(sCap);
if (m_mCoreCaps.end() != it) {
const auto& handler = std::get<1>(it->second);
handler(false);
}
}
}
m_ssServerDependentCaps.clear();
}
template <typename T>
void CClient::AddBuffer(const T& Message) {
const CString sTarget = Message.GetTarget();
T Format;
Format.Clone(Message);
Format.SetNick(CNick(_NAMEDFMT(GetNickMask())));
Format.SetTarget(_NAMEDFMT(sTarget));
Format.SetText("{text}");
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan) {
if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline()) {
pChan->AddBuffer(Format, Message.GetText());
}
} else if (Message.GetType() != CMessage::Type::Notice) {
if (!m_pUser->AutoClearQueryBuffer() || !m_pNetwork->IsUserOnline()) {
CQuery* pQuery = m_pNetwork->AddQuery(sTarget);
if (pQuery) {
pQuery->AddBuffer(Format, Message.GetText());
}
}
}
}
void CClient::EchoMessage(const CMessage& Message) {
CMessage EchoedMessage = Message;
for (CClient* pClient : GetClients()) {
if (pClient->HasEchoMessage() ||
(pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||
pClient->HasSelfMessage()))) {
EchoedMessage.SetNick(GetNickMask());
pClient->PutClient(EchoedMessage);
}
}
}
set<CChan*> CClient::MatchChans(const CString& sPatterns) const {
VCString vsPatterns;
sPatterns.Replace_n(",", " ")
.Split(" ", vsPatterns, false, "", "", true, true);
set<CChan*> sChans;
for (const CString& sPattern : vsPatterns) {
vector<CChan*> vChans = m_pNetwork->FindChans(sPattern);
sChans.insert(vChans.begin(), vChans.end());
}
return sChans;
}
unsigned int CClient::AttachChans(const std::set<CChan*>& sChans) {
unsigned int uAttached = 0;
for (CChan* pChan : sChans) {
if (!pChan->IsDetached()) continue;
uAttached++;
pChan->AttachUser();
}
return uAttached;
}
unsigned int CClient::DetachChans(const std::set<CChan*>& sChans) {
unsigned int uDetached = 0;
for (CChan* pChan : sChans) {
if (pChan->IsDetached()) continue;
uDetached++;
pChan->DetachUser();
}
return uDetached;
}
bool CClient::OnActionMessage(CActionMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnCTCPMessage(CCTCPMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
if (Message.IsReply()) {
CString sCTCP = Message.GetText();
if (sCTCP.Token(0) == "VERSION") {
// There are 2 different scenarios:
//
// a) CTCP reply for VERSION is not set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC forwards CTCP VERSION to client
// 3. Client replies with something
// 4. ZNC adds itself to the reply
// 5. ZNC sends the modified reply to whoever asked
//
// b) CTCP reply for VERSION is set.
// 1. ZNC receives CTCP VERSION from someone
// 2. ZNC replies with the configured reply (or just drops it if
// empty), without forwarding anything to client
// 3. Client does not see any CTCP request, and does not reply
//
// So, if user doesn't want "via ZNC" in CTCP VERSION reply, they
// can set custom reply.
//
// See more bikeshedding at github issues #820 and #1012
Message.SetText(sCTCP + " via " + CZNC::GetTag(false));
}
}
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
bool bContinue = false;
if (Message.IsReply()) {
NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser,
m_pNetwork, this, &bContinue);
} else {
NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
}
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(t_f(
"Your CTCP to {1} got lost, you are not connected to IRC!")(
Message.GetTarget()));
continue;
}
if (m_pNetwork) {
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnJoinMessage(CJoinMessage& Message) {
CString sChans = Message.GetTarget();
CString sKeys = Message.GetKey();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
VCString vsKeys;
sKeys.Split(",", vsKeys, true);
sKeys.clear();
for (unsigned int a = 0; a < vsChans.size(); a++) {
Message.SetTarget(vsChans[a]);
Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : "");
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(vsChans[a]));
}
bool bContinue = false;
NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
CString sChannel = Message.GetTarget();
CString sKey = Message.GetKey();
if (m_pNetwork) {
CChan* pChan = m_pNetwork->FindChan(sChannel);
if (pChan) {
if (pChan->IsDetached())
pChan->AttachUser(this);
else
pChan->JoinUser(sKey);
continue;
} else if (!sChannel.empty()) {
pChan = new CChan(sChannel, m_pNetwork, false);
if (m_pNetwork->AddChan(pChan)) {
pChan->SetKey(sKey);
}
}
}
if (!sChannel.empty()) {
sChans += (sChans.empty()) ? sChannel : CString("," + sChannel);
if (!vsKeys.empty()) {
sKeys += (sKeys.empty()) ? sKey : CString("," + sKey);
}
}
}
Message.SetTarget(sChans);
Message.SetKey(sKeys);
return sChans.empty();
}
bool CClient::OnModeMessage(CModeMessage& Message) {
CString sTarget = Message.GetTarget();
CString sModes = Message.GetModes();
if (m_pNetwork && m_pNetwork->IsChan(sTarget) && sModes.empty()) {
// If we are on that channel and already received a
// /mode reply from the server, we can answer this
// request ourself.
CChan* pChan = m_pNetwork->FindChan(sTarget);
if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
" " + sTarget + " " + pChan->GetModeString());
if (pChan->GetCreationDate() > 0) {
PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
GetNick() + " " + sTarget + " " +
CString(pChan->GetCreationDate()));
}
return true;
}
}
return false;
}
bool CClient::OnNoticeMessage(CNoticeMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (!sTarget.Equals("status")) {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModNotice(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork,
this, &bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a NOTICE to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your notice to {1} got lost, you are not connected to "
"IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnPartMessage(CPartMessage& Message) {
CString sChans = Message.GetTarget();
VCString vsChans;
sChans.Split(",", vsChans, false);
sChans.clear();
for (CString& sChan : vsChans) {
bool bContinue = false;
Message.SetTarget(sChan);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
sChan = Message.GetTarget();
CChan* pChan = m_pNetwork ? m_pNetwork->FindChan(sChan) : nullptr;
if (pChan && !pChan->IsOn()) {
PutStatusNotice(t_f("Removing channel {1}")(sChan));
m_pNetwork->DelChan(sChan);
} else {
sChans += (sChans.empty()) ? sChan : CString("," + sChan);
}
}
if (sChans.empty()) {
return true;
}
Message.SetTarget(sChans);
return false;
}
bool CClient::OnPingMessage(CMessage& Message) {
// All PONGs are generated by ZNC. We will still forward this to
// the ircd, but all PONGs from irc will be blocked.
if (!Message.GetParams().empty())
PutClient(":irc.znc.in PONG irc.znc.in " + Message.GetParamsColon(0));
else
PutClient(":irc.znc.in PONG irc.znc.in");
return false;
}
bool CClient::OnPongMessage(CMessage& Message) {
// Block PONGs, we already responded to the pings
return true;
}
bool CClient::OnQuitMessage(CQuitMessage& Message) {
bool bReturn = false;
NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this,
&bReturn);
if (!bReturn) {
Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach
}
// Don't forward this msg. We don't want the client getting us
// disconnected.
return true;
}
bool CClient::OnTextMessage(CTextMessage& Message) {
CString sTargets = Message.GetTarget();
VCString vTargets;
sTargets.Split(",", vTargets, false);
for (CString& sTarget : vTargets) {
Message.SetTarget(sTarget);
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sTarget));
}
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
if (sTarget.Equals("status")) {
CString sMsg = Message.GetText();
UserCommand(sMsg);
} else {
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(Message.GetText()));
}
continue;
}
bool bContinue = false;
NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,
&bContinue);
if (bContinue) continue;
if (!GetIRCSock()) {
// Some lagmeters do a PRIVMSG to their own nick, ignore those.
if (!sTarget.Equals(m_sNick))
PutStatus(
t_f("Your message to {1} got lost, you are not connected "
"to IRC!")(Message.GetTarget()));
continue;
}
if (m_pNetwork) {
AddBuffer(Message);
EchoMessage(Message);
PutIRC(Message.ToString(CMessage::ExcludePrefix |
CMessage::ExcludeTags));
}
}
return true;
}
bool CClient::OnTopicMessage(CTopicMessage& Message) {
bool bReturn = false;
CString sChan = Message.GetTarget();
CString sTopic = Message.GetTopic();
if (m_pNetwork) {
// May be nullptr.
Message.SetChan(m_pNetwork->FindChan(sChan));
}
if (!sTopic.empty()) {
NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork,
this, &bReturn);
} else {
NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this,
&bReturn);
Message.SetTarget(sChan);
}
return bReturn;
}
bool CClient::OnOtherMessage(CMessage& Message) {
const CString& sCommand = Message.GetCommand();
if (sCommand.Equals("ZNC")) {
CString sTarget = Message.GetParam(0);
CString sModCommand;
if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {
sModCommand = Message.GetParamsColon(1);
} else {
sTarget = "status";
sModCommand = Message.GetParamsColon(0);
}
if (sTarget.Equals("status")) {
if (sModCommand.empty())
PutStatus(t_s("Hello. How may I help you?"));
else
UserCommand(sModCommand);
} else {
if (sModCommand.empty())
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
PutModule(t_s("Hello. How may I help you?")))
else
CALLMOD(sTarget, this, m_pUser, m_pNetwork,
OnModCommand(sModCommand))
}
return true;
} else if (sCommand.Equals("ATTACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /attach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uAttachedChans = AttachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Attached {1} channel", "Attached {1} channels",
uAttachedChans)(uAttachedChans));
return true;
} else if (sCommand.Equals("DETACH")) {
if (!m_pNetwork) {
return true;
}
CString sPatterns = Message.GetParamsColon(0);
if (sPatterns.empty()) {
PutStatusNotice(t_s("Usage: /detach <#chans>"));
return true;
}
set<CChan*> sChans = MatchChans(sPatterns);
unsigned int uDetached = DetachChans(sChans);
PutStatusNotice(t_p("There was {1} channel matching [{2}]",
"There were {1} channels matching [{2}]",
sChans.size())(sChans.size(), sPatterns));
PutStatusNotice(t_p("Detached {1} channel", "Detached {1} channels",
uDetached)(uDetached));
return true;
} else if (sCommand.Equals("PROTOCTL")) {
for (const CString& sParam : Message.GetParams()) {
if (sParam == "NAMESX") {
m_bNamesx = true;
} else if (sParam == "UHNAMES") {
m_bUHNames = true;
}
}
return true; // If the server understands it, we already enabled namesx
// / uhnames
}
return false;
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_239_0 |
crossvul-cpp_data_bad_1580_4 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: ParaNdis6-Impl.c
*
* This file contains NDIS6-specific implementation of driver's procedures.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ParaNdis6.h"
static MINIPORT_DISABLE_INTERRUPT MiniportDisableInterruptEx;
static MINIPORT_ENABLE_INTERRUPT MiniportEnableInterruptEx;
static MINIPORT_INTERRUPT_DPC MiniportInterruptDPC;
static MINIPORT_ISR MiniportInterrupt;
static MINIPORT_ENABLE_MESSAGE_INTERRUPT MiniportEnableMSIInterrupt;
static MINIPORT_DISABLE_MESSAGE_INTERRUPT MiniportDisableMSIInterrupt;
static MINIPORT_MESSAGE_INTERRUPT MiniportMSIInterrupt;
static MINIPORT_MESSAGE_INTERRUPT_DPC MiniportMSIInterruptDpc;
static MINIPORT_PROCESS_SG_LIST ProcessSGListHandler;
static MINIPORT_ALLOCATE_SHARED_MEM_COMPLETE SharedMemAllocateCompleteHandler;
static MINIPORT_PROCESS_SG_LIST ProcessSGListHandler;
/**********************************************************
Implements general-purpose memory allocation routine
Parameters:
ULONG ulRequiredSize: block size
Return value:
PVOID allocated memory block
NULL on error
***********************************************************/
PVOID ParaNdis_AllocateMemoryRaw(NDIS_HANDLE MiniportHandle, ULONG ulRequiredSize)
{
return NdisAllocateMemoryWithTagPriority(
MiniportHandle,
ulRequiredSize,
PARANDIS_MEMORY_TAG,
NormalPoolPriority);
}
PVOID ParaNdis_AllocateMemory(PARANDIS_ADAPTER *pContext, ULONG ulRequiredSize)
{
return ParaNdis_AllocateMemoryRaw(pContext->MiniportHandle, ulRequiredSize);
}
/**********************************************************
Implements opening of adapter-specific configuration
Parameters:
Return value:
NDIS_HANDLE Handle of open configuration
NULL on error
***********************************************************/
NDIS_HANDLE ParaNdis_OpenNICConfiguration(PARANDIS_ADAPTER *pContext)
{
NDIS_CONFIGURATION_OBJECT co;
NDIS_HANDLE cfg;
NDIS_STATUS status;
DEBUG_ENTRY(2);
co.Header.Type = NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT;
co.Header.Revision = NDIS_CONFIGURATION_OBJECT_REVISION_1;
co.Header.Size = sizeof(co);
co.Flags = 0;
co.NdisHandle = pContext->MiniportHandle;
status = NdisOpenConfigurationEx(&co, &cfg);
if (status != NDIS_STATUS_SUCCESS)
cfg = NULL;
DEBUG_EXIT_STATUS(status == NDIS_STATUS_SUCCESS ? 2 : 0, status);
return cfg;
}
/**********************************************************
NDIS6 implementation of shared memory allocation
Parameters:
context
tCompletePhysicalAddress *pAddresses
the structure accumulates all our knowledge
about the allocation (size, addresses, cacheability etc)
Return value:
TRUE if the allocation was successful
***********************************************************/
BOOLEAN ParaNdis_InitialAllocatePhysicalMemory(
PARANDIS_ADAPTER *pContext,
tCompletePhysicalAddress *pAddresses)
{
NdisMAllocateSharedMemory(
pContext->MiniportHandle,
pAddresses->size,
TRUE,
&pAddresses->Virtual,
&pAddresses->Physical);
return pAddresses->Virtual != NULL;
}
/**********************************************************
NDIS6 implementation of shared memory freeing
Parameters:
context
tCompletePhysicalAddress *pAddresses
the structure accumulates all our knowledge
about the allocation (size, addresses, cacheability etc)
filled by ParaNdis_InitialAllocatePhysicalMemory or
by ParaNdis_RuntimeRequestToAllocatePhysicalMemory
***********************************************************/
VOID ParaNdis_FreePhysicalMemory(
PARANDIS_ADAPTER *pContext,
tCompletePhysicalAddress *pAddresses)
{
NdisMFreeSharedMemory(
pContext->MiniportHandle,
pAddresses->size,
TRUE,
pAddresses->Virtual,
pAddresses->Physical);
}
#if (NDIS_SUPPORT_NDIS620)
typedef MINIPORT_SYNCHRONIZE_INTERRUPT_HANDLER NDIS_SYNC_PROC_TYPE;
#else
typedef PVOID NDIS_SYNC_PROC_TYPE;
#endif
BOOLEAN ParaNdis_SynchronizeWithInterrupt(
PARANDIS_ADAPTER *pContext,
ULONG messageId,
tSynchronizedProcedure procedure,
PVOID parameter)
{
tSynchronizedContext SyncContext;
NDIS_SYNC_PROC_TYPE syncProc;
#pragma warning (push)
#pragma warning (disable:4152)
syncProc = (NDIS_SYNC_PROC_TYPE) procedure;
#pragma warning (pop)
SyncContext.pContext = pContext;
SyncContext.Parameter = parameter;
return NdisMSynchronizeWithInterruptEx(pContext->InterruptHandle, messageId, syncProc, &SyncContext);
}
/**********************************************************
NDIS-required procedure for hardware interrupt registration
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
***********************************************************/
static VOID MiniportDisableInterruptEx(IN PVOID MiniportInterruptContext)
{
DEBUG_ENTRY(0);
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
/* TODO - make sure that interrups are not reenabled by the DPC callback*/
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.DisableInterrupts();
pContext->pPathBundles[i].rxPath.DisableInterrupts();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.DisableInterrupts();
}
}
/**********************************************************
NDIS-required procedure for hardware interrupt registration
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
***********************************************************/
static VOID MiniportEnableInterruptEx(IN PVOID MiniportInterruptContext)
{
DEBUG_ENTRY(0);
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.EnableInterrupts();
pContext->pPathBundles[i].rxPath.EnableInterrupts();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.EnableInterrupts();
}
}
/**********************************************************
NDIS-required procedure for hardware interrupt handling
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
OUT PBOOLEAN QueueDefaultInterruptDpc - set to TRUE for default DPC spawning
OUT PULONG TargetProcessors
Return value:
TRUE if recognized
***********************************************************/
static BOOLEAN MiniportInterrupt(
IN PVOID MiniportInterruptContext,
OUT PBOOLEAN QueueDefaultInterruptDpc,
OUT PULONG TargetProcessors
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
ULONG status = VirtIODeviceISR(pContext->IODevice);
*TargetProcessors = 0;
if((status == 0) ||
(status == VIRTIO_NET_INVALID_INTERRUPT_STATUS))
{
*QueueDefaultInterruptDpc = FALSE;
return FALSE;
}
PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext);
if(!pContext->bDeviceInitialized) {
*QueueDefaultInterruptDpc = FALSE;
return TRUE;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.DisableInterrupts();
pContext->pPathBundles[i].rxPath.DisableInterrupts();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.DisableInterrupts();
}
*QueueDefaultInterruptDpc = TRUE;
pContext->ulIrqReceived += 1;
return true;
}
static CParaNdisAbstractPath *GetPathByMessageId(PARANDIS_ADAPTER *pContext, ULONG MessageId)
{
CParaNdisAbstractPath *path = NULL;
UINT bundleId = MessageId / 2;
if (bundleId >= pContext->nPathBundles)
{
path = &pContext->CXPath;
}
else if (MessageId % 2)
{
path = &(pContext->pPathBundles[bundleId].rxPath);
}
else
{
path = &(pContext->pPathBundles[bundleId].txPath);
}
return path;
}
/**********************************************************
NDIS-required procedure for MSI hardware interrupt handling
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
IN ULONG MessageId - specific interrupt index
OUT PBOOLEAN QueueDefaultInterruptDpc - - set to TRUE for default DPC spawning
OUT PULONG TargetProcessors
Return value:
TRUE if recognized
***********************************************************/
static BOOLEAN MiniportMSIInterrupt(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId,
OUT PBOOLEAN QueueDefaultInterruptDpc,
OUT PULONG TargetProcessors
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext);
*TargetProcessors = 0;
if (!pContext->bDeviceInitialized) {
*QueueDefaultInterruptDpc = FALSE;
return TRUE;
}
CParaNdisAbstractPath *path = GetPathByMessageId(pContext, MessageId);
path->DisableInterrupts();
path->ReportInterrupt();
#if NDIS_SUPPORT_NDIS620
if (path->DPCAffinity.Mask)
{
NdisMQueueDpcEx(pContext->InterruptHandle, MessageId, &path->DPCAffinity, NULL);
*QueueDefaultInterruptDpc = FALSE;
}
else
{
*QueueDefaultInterruptDpc = TRUE;
}
#else
*TargetProcessors = (ULONG)path->DPCTargetProcessor;
*QueueDefaultInterruptDpc = TRUE;
#endif
pContext->ulIrqReceived += 1;
return true;
}
#if NDIS_SUPPORT_NDIS620
static __inline
VOID GetAffinityForCurrentCpu(PGROUP_AFFINITY pAffinity)
{
PROCESSOR_NUMBER ProcNum;
KeGetCurrentProcessorNumberEx(&ProcNum);
pAffinity->Group = ProcNum.Group;
pAffinity->Mask = 1;
pAffinity->Mask <<= ProcNum.Number;
}
#endif
/**********************************************************
NDIS-required procedure for DPC handling
Parameters:
PVOID MiniportInterruptContext (Adapter context)
***********************************************************/
static VOID MiniportInterruptDPC(
IN NDIS_HANDLE MiniportInterruptContext,
IN PVOID MiniportDpcContext,
IN PVOID ReceiveThrottleParameters,
IN PVOID NdisReserved2
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
bool requiresDPCRescheduling;
#if NDIS_SUPPORT_NDIS620
PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters;
DEBUG_ENTRY(5);
RxThrottleParameters->MoreNblsPending = 0;
requiresDPCRescheduling = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate);
if (requiresDPCRescheduling)
{
GROUP_AFFINITY Affinity;
GetAffinityForCurrentCpu(&Affinity);
NdisMQueueDpcEx(pContext->InterruptHandle, 0, &Affinity, MiniportDpcContext);
}
#else /* NDIS 6.0*/
DEBUG_ENTRY(5);
UNREFERENCED_PARAMETER(ReceiveThrottleParameters);
requiresDPCRescheduling = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
if (requiresDPCRescheduling)
{
DPrintf(4, ("[%s] Queued additional DPC for %d\n", __FUNCTION__, requiresDPCRescheduling));
NdisMQueueDpc(pContext->InterruptHandle, 0, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext);
}
#endif /* NDIS_SUPPORT_NDIS620 */
UNREFERENCED_PARAMETER(NdisReserved2);
}
/**********************************************************
NDIS-required procedure for MSI DPC handling
Parameters:
PVOID MiniportInterruptContext (Adapter context)
IN ULONG MessageId - specific interrupt index
***********************************************************/
static VOID MiniportMSIInterruptDpc(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId,
IN PVOID MiniportDpcContext,
#if NDIS_SUPPORT_NDIS620
IN PVOID ReceiveThrottleParameters,
IN PVOID NdisReserved2
#else
IN PULONG NdisReserved1,
IN PULONG NdisReserved2
#endif
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
bool requireDPCRescheduling;
#if NDIS_SUPPORT_NDIS620
PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters;
RxThrottleParameters->MoreNblsPending = 0;
requireDPCRescheduling = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate);
if (requireDPCRescheduling)
{
GROUP_AFFINITY Affinity;
GetAffinityForCurrentCpu(&Affinity);
NdisMQueueDpcEx(pContext->InterruptHandle, MessageId, &Affinity, MiniportDpcContext);
}
#else
UNREFERENCED_PARAMETER(NdisReserved1);
requireDPCRescheduling = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
if (requireDPCRescheduling)
{
NdisMQueueDpc(pContext->InterruptHandle, MessageId, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext);
}
#endif
UNREFERENCED_PARAMETER(NdisReserved2);
}
static VOID MiniportDisableMSIInterrupt(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
/* TODO - How we prevent DPC procedure from re-enabling interrupt? */
CParaNdisAbstractPath *path = GetPathByMessageId(pContext, MessageId);
path->DisableInterrupts();
}
static VOID MiniportEnableMSIInterrupt(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
CParaNdisAbstractPath *path = GetPathByMessageId(pContext, MessageId);
path->EnableInterrupts();
}
/**********************************************************
NDIS required handler for run-time allocation of physical memory
Parameters:
Return value:
***********************************************************/
static VOID SharedMemAllocateCompleteHandler(
IN NDIS_HANDLE MiniportAdapterContext,
IN PVOID VirtualAddress,
IN PNDIS_PHYSICAL_ADDRESS PhysicalAddress,
IN ULONG Length,
IN PVOID Context
)
{
UNREFERENCED_PARAMETER(MiniportAdapterContext);
UNREFERENCED_PARAMETER(VirtualAddress);
UNREFERENCED_PARAMETER(PhysicalAddress);
UNREFERENCED_PARAMETER(Length);
UNREFERENCED_PARAMETER(Context);
}
NDIS_STATUS ParaNdis_ConfigureMSIXVectors(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_RESOURCES;
UINT i;
PIO_INTERRUPT_MESSAGE_INFO pTable = pContext->pMSIXInfoTable;
if (pTable && pTable->MessageCount)
{
status = NDIS_STATUS_SUCCESS;
DPrintf(0, ("[%s] Using MSIX interrupts (%d messages, irql %d)\n",
__FUNCTION__, pTable->MessageCount, pTable->UnifiedIrql));
for (i = 0; i < pContext->pMSIXInfoTable->MessageCount; ++i)
{
DPrintf(0, ("[%s] MSIX message%d=%08X=>%I64X\n",
__FUNCTION__, i,
pTable->MessageInfo[i].MessageData,
pTable->MessageInfo[i].MessageAddress));
}
for (UINT j = 0; j < pContext->nPathBundles && status == NDIS_STATUS_SUCCESS; ++j)
{
status = pContext->pPathBundles[j].rxPath.SetupMessageIndex(2 * u16(j) + 1);
status = pContext->pPathBundles[j].txPath.SetupMessageIndex(2 * u16(j));
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.SetupMessageIndex(2 * u16(pContext->nPathBundles));
}
}
if (status == NDIS_STATUS_SUCCESS)
{
for (UINT j = 0; j < pContext->nPathBundles && status == NDIS_STATUS_SUCCESS; ++j)
{
DPrintf(0, ("[%s] Using messages %u/%u for RX/TX queue %u\n", __FUNCTION__, pContext->pPathBundles[j].rxPath.getMessageIndex(),
pContext->pPathBundles[j].txPath.getMessageIndex(), j));
}
if (pContext->bCXPathCreated)
{
DPrintf(0, ("[%s] Using message %u for controls\n", __FUNCTION__, pContext->CXPath.getMessageIndex()));
}
else
{
DPrintf(0, ("[%s] - No control path\n", __FUNCTION__));
}
}
DEBUG_EXIT_STATUS(2, status);
return status;
}
void ParaNdis_RestoreDeviceConfigurationAfterReset(
PARANDIS_ADAPTER *pContext)
{
ParaNdis_ConfigureMSIXVectors(pContext);
}
static void DebugParseOffloadBits()
{
NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO info;
tChecksumCheckResult res;
ULONG val = 1;
int level = 1;
while (val)
{
info.Value = (PVOID)(ULONG_PTR)val;
if (info.Receive.IpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed\n", val));
if (info.Receive.IpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK\n", val));
if (info.Receive.TcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed\n", val));
if (info.Receive.TcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK\n", val));
if (info.Receive.UdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed\n", val));
if (info.Receive.UdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK\n", val));
val = val << 1;
}
val = 1;
while (val)
{
res.value = val;
if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed\n", val));
if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK\n", val));
if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed\n", val));
if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK\n", val));
if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed\n", val));
if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK\n", val));
val = val << 1;
}
}
/**********************************************************
NDIS6-related final initialization:
Installing interrupt handler
Allocate buffer list pool
Parameters:
Return value:
***********************************************************/
NDIS_STATUS ParaNdis_FinishSpecificInitialization(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
NET_BUFFER_LIST_POOL_PARAMETERS PoolParams;
NDIS_MINIPORT_INTERRUPT_CHARACTERISTICS mic;
DEBUG_ENTRY(0);
NdisZeroMemory(&mic, sizeof(mic));
mic.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT;
mic.Header.Revision = NDIS_MINIPORT_INTERRUPT_REVISION_1;
mic.Header.Size = NDIS_SIZEOF_MINIPORT_INTERRUPT_CHARACTERISTICS_REVISION_1;
mic.DisableInterruptHandler = MiniportDisableInterruptEx;
mic.EnableInterruptHandler = MiniportEnableInterruptEx;
mic.InterruptDpcHandler = MiniportInterruptDPC;
mic.InterruptHandler = MiniportInterrupt;
if (pContext->bUsingMSIX)
{
mic.MsiSupported = TRUE;
mic.MsiSyncWithAllMessages = TRUE;
mic.EnableMessageInterruptHandler = MiniportEnableMSIInterrupt;
mic.DisableMessageInterruptHandler = MiniportDisableMSIInterrupt;
mic.MessageInterruptHandler = MiniportMSIInterrupt;
mic.MessageInterruptDpcHandler = MiniportMSIInterruptDpc;
}
PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
PoolParams.Header.Size = sizeof(PoolParams);
PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT;
PoolParams.fAllocateNetBuffer = TRUE;
PoolParams.ContextSize = 0;
PoolParams.PoolTag = PARANDIS_MEMORY_TAG;
PoolParams.DataSize = 0;
pContext->BufferListsPool = NdisAllocateNetBufferListPool(pContext->MiniportHandle, &PoolParams);
if (!pContext->BufferListsPool)
{
status = NDIS_STATUS_RESOURCES;
}
if (status == NDIS_STATUS_SUCCESS)
{
status = NdisMRegisterInterruptEx(pContext->MiniportHandle, pContext, &mic, &pContext->InterruptHandle);
}
#ifdef DBG
if (pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] MSIX message table %savailable, count = %u\n", __FUNCTION__, (mic.MessageInfoTable == nullptr ? "not " : ""),
(mic.MessageInfoTable == nullptr ? 0 : mic.MessageInfoTable->MessageCount)));
}
else
{
DPrintf(0, ("[%s] Not using MSIX\n", __FUNCTION__));
}
#endif
if (status == NDIS_STATUS_SUCCESS)
{
NDIS_SG_DMA_DESCRIPTION sgDesc;
sgDesc.Header.Type = NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION;
sgDesc.Header.Revision = NDIS_SG_DMA_DESCRIPTION_REVISION_1;
sgDesc.Header.Size = sizeof(sgDesc);
sgDesc.Flags = NDIS_SG_DMA_64_BIT_ADDRESS;
sgDesc.MaximumPhysicalMapping = 0x10000; // 64K
sgDesc.ProcessSGListHandler = ProcessSGListHandler;
sgDesc.SharedMemAllocateCompleteHandler = SharedMemAllocateCompleteHandler;
sgDesc.ScatterGatherListSize = 0; // OUT value
status = NdisMRegisterScatterGatherDma(pContext->MiniportHandle, &sgDesc, &pContext->DmaHandle);
if (status != NDIS_STATUS_SUCCESS)
{
DPrintf(0, ("[%s] ERROR: NdisMRegisterScatterGatherDma failed (%X)!\n", __FUNCTION__, status));
}
else
{
DPrintf(0, ("[%s] SG recommended size %d\n", __FUNCTION__, sgDesc.ScatterGatherListSize));
}
}
if (status == NDIS_STATUS_SUCCESS)
{
if (NDIS_CONNECT_MESSAGE_BASED == mic.InterruptType)
{
pContext->pMSIXInfoTable = mic.MessageInfoTable;
}
else if (pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] ERROR: Interrupt type %d, message table %p\n",
__FUNCTION__, mic.InterruptType, mic.MessageInfoTable));
status = NDIS_STATUS_RESOURCE_CONFLICT;
}
ParaNdis6_ApplyOffloadPersistentConfiguration(pContext);
DebugParseOffloadBits();
}
DEBUG_EXIT_STATUS(0, status);
return status;
}
/**********************************************************
NDIS6-related final initialization:
Uninstalling interrupt handler
Dellocate buffer list pool
Parameters:
context
***********************************************************/
VOID ParaNdis_FinalizeCleanup(PARANDIS_ADAPTER *pContext)
{
// we zero context members to be able examine them in the debugger/dump
if (pContext->InterruptHandle)
{
NdisMDeregisterInterruptEx(pContext->InterruptHandle);
pContext->InterruptHandle = NULL;
}
if (pContext->BufferListsPool)
{
NdisFreeNetBufferListPool(pContext->BufferListsPool);
pContext->BufferListsPool = NULL;
}
if (pContext->DmaHandle)
{
NdisMDeregisterScatterGatherDma(pContext->DmaHandle);
pContext->DmaHandle = NULL;
}
}
BOOLEAN ParaNdis_BindRxBufferToPacket(
PARANDIS_ADAPTER *pContext,
pRxNetDescriptor p)
{
ULONG i;
PMDL *NextMdlLinkage = &p->Holder;
for(i = PARANDIS_FIRST_RX_DATA_PAGE; i < p->PagesAllocated; i++)
{
*NextMdlLinkage = NdisAllocateMdl(pContext->MiniportHandle, p->PhysicalPages[i].Virtual, PAGE_SIZE);
if(*NextMdlLinkage == NULL) goto error_exit;
NextMdlLinkage = &(NDIS_MDL_LINKAGE(*NextMdlLinkage));
}
*NextMdlLinkage = NULL;
return TRUE;
error_exit:
ParaNdis_UnbindRxBufferFromPacket(p);
return FALSE;
}
void ParaNdis_UnbindRxBufferFromPacket(
pRxNetDescriptor p)
{
PMDL NextMdlLinkage = p->Holder;
while(NextMdlLinkage != NULL)
{
PMDL pThisMDL = NextMdlLinkage;
NextMdlLinkage = NDIS_MDL_LINKAGE(pThisMDL);
NdisAdjustMdlLength(pThisMDL, PAGE_SIZE);
NdisFreeMdl(pThisMDL);
}
}
static
void ParaNdis_AdjustRxBufferHolderLength(
pRxNetDescriptor p,
ULONG ulDataOffset)
{
PMDL NextMdlLinkage = p->Holder;
ULONG ulBytesLeft = p->PacketInfo.dataLength + ulDataOffset;
while(NextMdlLinkage != NULL)
{
ULONG ulThisMdlBytes = min(PAGE_SIZE, ulBytesLeft);
NdisAdjustMdlLength(NextMdlLinkage, ulThisMdlBytes);
ulBytesLeft -= ulThisMdlBytes;
NextMdlLinkage = NDIS_MDL_LINKAGE(NextMdlLinkage);
}
ASSERT(ulBytesLeft == 0);
}
static __inline
VOID NBLSetRSSInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO PacketInfo)
{
#if PARANDIS_SUPPORT_RSS
CNdisRWLockState lockState;
pContext->RSSParameters.rwLock.acquireReadDpr(lockState);
if(pContext->RSSParameters.RSSMode != PARANDIS_RSS_DISABLED)
{
NET_BUFFER_LIST_SET_HASH_TYPE (pNBL, PacketInfo->RSSHash.Type);
NET_BUFFER_LIST_SET_HASH_FUNCTION(pNBL, PacketInfo->RSSHash.Function);
NET_BUFFER_LIST_SET_HASH_VALUE (pNBL, PacketInfo->RSSHash.Value);
}
pContext->RSSParameters.rwLock.releaseDpr(lockState);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(pNBL);
UNREFERENCED_PARAMETER(PacketInfo);
#endif
}
static __inline
VOID NBLSet8021QInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO pPacketInfo)
{
NDIS_NET_BUFFER_LIST_8021Q_INFO qInfo;
qInfo.Value = NULL;
if (IsPrioritySupported(pContext))
qInfo.TagHeader.UserPriority = pPacketInfo->Vlan.UserPriority;
if (IsVlanSupported(pContext))
qInfo.TagHeader.VlanId = pPacketInfo->Vlan.VlanId;
if(qInfo.Value != NULL)
pContext->extraStatistics.framesRxPriority++;
NET_BUFFER_LIST_INFO(pNBL, Ieee8021QNetBufferListInfo) = qInfo.Value;
}
#if PARANDIS_SUPPORT_RSC
static __inline
UINT PktGetTCPCoalescedSegmentsCount(PNET_PACKET_INFO PacketInfo, UINT nMaxTCPPayloadSize)
{
// We have no corresponding data, following is a simulation
return PacketInfo->L2PayloadLen / nMaxTCPPayloadSize +
!!(PacketInfo->L2PayloadLen % nMaxTCPPayloadSize);
}
static __inline
VOID NBLSetRSCInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL,
PNET_PACKET_INFO PacketInfo, UINT nCoalescedSegments)
{
NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;
qCSInfo.Value = NULL;
qCSInfo.Receive.IpChecksumSucceeded = TRUE;
qCSInfo.Receive.IpChecksumValueInvalid = TRUE;
qCSInfo.Receive.TcpChecksumSucceeded = TRUE;
qCSInfo.Receive.TcpChecksumValueInvalid = TRUE;
NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value;
NET_BUFFER_LIST_COALESCED_SEG_COUNT(pNBL) = (USHORT) nCoalescedSegments;
NET_BUFFER_LIST_DUP_ACK_COUNT(pNBL) = 0;
NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedOctets, PacketInfo->L2PayloadLen);
NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalesceEvents, 1);
NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedPkts, nCoalescedSegments);
}
#endif
/**********************************************************
NDIS6 implementation of packet indication
Parameters:
context
PVOID pBuffersDescriptor - VirtIO buffer descriptor of data buffer
BOOLEAN bPrepareOnly - only return NBL for further indication in batch
Return value:
TRUE is packet indicated
FALSE if not (in this case, the descriptor should be freed now)
If priority header is in the packet. it will be removed and *pLength decreased
***********************************************************/
tPacketIndicationType ParaNdis_PrepareReceivedPacket(
PARANDIS_ADAPTER *pContext,
pRxNetDescriptor pBuffersDesc,
PUINT pnCoalescedSegmentsCount)
{
PMDL pMDL = pBuffersDesc->Holder;
PNET_BUFFER_LIST pNBL = NULL;
*pnCoalescedSegmentsCount = 1;
if (pMDL)
{
ULONG nBytesStripped = 0;
PNET_PACKET_INFO pPacketInfo = &pBuffersDesc->PacketInfo;
if (pContext->ulPriorityVlanSetting && pPacketInfo->hasVlanHeader)
{
nBytesStripped = ParaNdis_StripVlanHeaderMoveHead(pPacketInfo);
}
ParaNdis_PadPacketToMinimalLength(pPacketInfo);
ParaNdis_AdjustRxBufferHolderLength(pBuffersDesc, nBytesStripped);
pNBL = NdisAllocateNetBufferAndNetBufferList(pContext->BufferListsPool, 0, 0, pMDL, nBytesStripped, pPacketInfo->dataLength);
if (pNBL)
{
virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *) pBuffersDesc->PhysicalPages[0].Virtual;
tChecksumCheckResult csRes;
pNBL->SourceHandle = pContext->MiniportHandle;
NBLSetRSSInfo(pContext, pNBL, pPacketInfo);
NBLSet8021QInfo(pContext, pNBL, pPacketInfo);
pNBL->MiniportReserved[0] = pBuffersDesc;
#if PARANDIS_SUPPORT_RSC
if(pHeader->gso_type != VIRTIO_NET_HDR_GSO_NONE)
{
*pnCoalescedSegmentsCount = PktGetTCPCoalescedSegmentsCount(pPacketInfo, pContext->MaxPacketSize.nMaxDataSize);
NBLSetRSCInfo(pContext, pNBL, pPacketInfo, *pnCoalescedSegmentsCount);
}
else
#endif
{
csRes = ParaNdis_CheckRxChecksum(
pContext,
pHeader->flags,
&pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE],
pPacketInfo->dataLength,
nBytesStripped);
if (csRes.value)
{
NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;
qCSInfo.Value = NULL;
qCSInfo.Receive.IpChecksumFailed = csRes.flags.IpFailed;
qCSInfo.Receive.IpChecksumSucceeded = csRes.flags.IpOK;
qCSInfo.Receive.TcpChecksumFailed = csRes.flags.TcpFailed;
qCSInfo.Receive.TcpChecksumSucceeded = csRes.flags.TcpOK;
qCSInfo.Receive.UdpChecksumFailed = csRes.flags.UdpFailed;
qCSInfo.Receive.UdpChecksumSucceeded = csRes.flags.UdpOK;
NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value;
DPrintf(1, ("Reporting CS %X->%X\n", csRes.value, (ULONG)(ULONG_PTR)qCSInfo.Value));
}
}
pNBL->Status = NDIS_STATUS_SUCCESS;
#if defined(ENABLE_HISTORY_LOG)
{
tTcpIpPacketParsingResult packetReview = ParaNdis_CheckSumVerify(
RtlOffsetToPointer(pPacketInfo->headersBuffer, ETH_HEADER_SIZE),
pPacketInfo->dataLength,
pcrIpChecksum | pcrTcpChecksum | pcrUdpChecksum,
__FUNCTION__
);
ParaNdis_DebugHistory(pContext, hopPacketReceived, pNBL, pPacketInfo->dataLength, (ULONG)(ULONG_PTR)qInfo.Value, packetReview.value);
}
#endif
}
}
return pNBL;
}
/**********************************************************
NDIS procedure of returning us buffer of previously indicated packets
Parameters:
context
PNET_BUFFER_LIST pNBL - list of buffers to free
returnFlags - is dpc
The procedure frees:
received buffer descriptors back to list of RX buffers
all the allocated MDL structures
all the received NBLs back to our pool
***********************************************************/
VOID ParaNdis6_ReturnNetBufferLists(
NDIS_HANDLE miniportAdapterContext,
PNET_BUFFER_LIST pNBL,
ULONG returnFlags)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext;
UNREFERENCED_PARAMETER(returnFlags);
DEBUG_ENTRY(5);
while (pNBL)
{
PNET_BUFFER_LIST pTemp = pNBL;
pRxNetDescriptor pBuffersDescriptor = (pRxNetDescriptor)pNBL->MiniportReserved[0];
DPrintf(3, (" Returned NBL of pBuffersDescriptor %p!\n", pBuffersDescriptor));
pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL);
NET_BUFFER_LIST_NEXT_NBL(pTemp) = NULL;
NdisFreeNetBufferList(pTemp);
pBuffersDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBuffersDescriptor);
}
ParaMdis_TestPausing(pContext);
}
/**********************************************************
Pauses of restarts RX activity.
Restart is immediate, pause may be delayed until
NDIS returns all the indicated NBL
Parameters:
context
bPause 1/0 - pause or restart
ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished
Return value:
SUCCESS if finished synchronously
PENDING if not, then callback will be called
***********************************************************/
NDIS_STATUS ParaNdis6_ReceivePauseRestart(
PARANDIS_ADAPTER *pContext,
BOOLEAN bPause,
ONPAUSECOMPLETEPROC Callback
)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
if (bPause)
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0);
if (pContext->m_upstreamPacketPending != 0)
{
pContext->ReceiveState = srsPausing;
pContext->ReceivePauseCompletionProc = Callback;
status = NDIS_STATUS_PENDING;
}
else
{
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
pContext->ReceiveState = srsDisabled;
}
}
else
{
ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0);
pContext->ReceiveState = srsEnabled;
}
return status;
}
NDIS_STATUS ParaNdis_ExactSendFailureStatus(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_FAILURE;
if (pContext->SendState != srsEnabled ) status = NDIS_STATUS_PAUSED;
if (!pContext->bConnected) status = NDIS_STATUS_MEDIA_DISCONNECTED;
if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED;
// override NDIS_STATUS_PAUSED is there is a specific reason of implicit paused state
if (pContext->powerState != NdisDeviceStateD0) status = NDIS_STATUS_LOW_POWER_STATE;
if (pContext->bResetInProgress) status = NDIS_STATUS_RESET_IN_PROGRESS;
return status;
}
BOOLEAN ParaNdis_IsSendPossible(PARANDIS_ADAPTER *pContext)
{
BOOLEAN b;
b = !pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled;
return b;
}
/**********************************************************
NDIS required handler for run-time allocation of scatter-gather list
Parameters:
pSGL - scatter-hather list of elements (possible NULL when called directly)
Context - (tNetBufferEntry *) for specific NET_BUFFER in NBL
Called on DPC (DDK claims it)
***********************************************************/
VOID ProcessSGListHandler(
IN PDEVICE_OBJECT pDO,
IN PVOID Reserved,
IN PSCATTER_GATHER_LIST pSGL,
IN PVOID Context
)
{
UNREFERENCED_PARAMETER(Reserved);
UNREFERENCED_PARAMETER(pDO);
auto NBHolder = static_cast<CNB*>(Context);
NBHolder->MappingDone(pSGL);
}
/**********************************************************
Pauses of restarts TX activity.
Restart is immediate, pause may be delayed until
we return all the NBLs to NDIS
Parameters:
context
bPause 1/0 - pause or restart
ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished
Return value:
SUCCESS if finished synchronously
PENDING if not, then callback will be called later
***********************************************************/
NDIS_STATUS ParaNdis6_SendPauseRestart(
PARANDIS_ADAPTER *pContext,
BOOLEAN bPause,
ONPAUSECOMPLETEPROC Callback
)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
DEBUG_ENTRY(4);
if (bPause)
{
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0);
if (pContext->SendState == srsEnabled)
{
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
pContext->SendState = srsPausing;
pContext->SendPauseCompletionProc = Callback;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
if (!pContext->pPathBundles[i].txPath.Pause())
{
status = NDIS_STATUS_PENDING;
}
}
if (status == NDIS_STATUS_SUCCESS)
{
pContext->SendState = srsDisabled;
}
}
if (status == NDIS_STATUS_SUCCESS)
{
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0);
}
}
else
{
pContext->SendState = srsEnabled;
ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0);
}
return status;
}
/**********************************************************
Required procedure of NDIS
NDIS wants to cancel sending of each list which has specified CancelID
Can be tested only under NDIS Test
***********************************************************/
VOID ParaNdis6_CancelSendNetBufferLists(
NDIS_HANDLE miniportAdapterContext,
PVOID pCancelId)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext;
DEBUG_ENTRY(0);
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.CancelNBLs(pCancelId);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1580_4 |
crossvul-cpp_data_bad_4877_0 | #include "Hub.h"
#include "HTTPSocket.h"
#include <openssl/sha.h>
namespace uWS {
char *Hub::inflate(char *data, size_t &length) {
dynamicInflationBuffer.clear();
inflationStream.next_in = (Bytef *) data;
inflationStream.avail_in = length;
int err;
do {
inflationStream.next_out = (Bytef *) inflationBuffer;
inflationStream.avail_out = LARGE_BUFFER_SIZE;
err = ::inflate(&inflationStream, Z_FINISH);
if (!inflationStream.avail_in) {
break;
}
dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
} while (err == Z_BUF_ERROR);
inflateReset(&inflationStream);
if (err != Z_BUF_ERROR && err != Z_OK) {
length = 0;
return nullptr;
}
if (dynamicInflationBuffer.length()) {
dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
length = dynamicInflationBuffer.length();
return (char *) dynamicInflationBuffer.data();
}
length = LARGE_BUFFER_SIZE - inflationStream.avail_out;
return inflationBuffer;
}
void Hub::onServerAccept(uS::Socket s) {
uS::SocketData *socketData = s.getSocketData();
s.startTimeout<HTTPSocket<SERVER>::onEnd>();
s.enterState<HTTPSocket<SERVER>>(new HTTPSocket<SERVER>::Data(socketData));
delete socketData;
}
void Hub::onClientConnection(uS::Socket s, bool error) {
HTTPSocket<CLIENT>::Data *httpSocketData = (HTTPSocket<CLIENT>::Data *) s.getSocketData();
if (error) {
((Group<CLIENT> *) httpSocketData->nodeData)->errorHandler(httpSocketData->httpUser);
delete httpSocketData;
} else {
s.enterState<HTTPSocket<CLIENT>>(s.getSocketData());
HTTPSocket<CLIENT>(s).upgrade();
}
}
bool Hub::listen(int port, uS::TLS::Context sslContext, int options, Group<SERVER> *eh) {
if (!eh) {
eh = (Group<SERVER> *) this;
}
if (uS::Node::listen<onServerAccept>(port, sslContext, options, (uS::NodeData *) eh, nullptr)) {
eh->errorHandler(port);
return false;
}
return true;
}
void Hub::connect(std::string uri, void *user, int timeoutMs, Group<CLIENT> *eh) {
if (!eh) {
eh = (Group<CLIENT> *) this;
}
int offset = 0;
std::string protocol = uri.substr(offset, uri.find("://")), hostname, portStr, path;
if ((offset += protocol.length() + 3) < uri.length()) {
hostname = uri.substr(offset, uri.find_first_of(":/", offset) - offset);
offset += hostname.length();
if (uri[offset] == ':') {
offset++;
portStr = uri.substr(offset, uri.find("/", offset) - offset);
}
offset += portStr.length();
if (uri[offset] == '/') {
path = uri.substr(++offset);
}
}
if (hostname.length()) {
int port = 80;
bool secure = false;
if (protocol == "wss") {
port = 443;
secure = true;
} else if (protocol != "ws") {
eh->errorHandler(user);
}
if (portStr.length()) {
port = stoi(portStr);
}
uS::SocketData socketData((uS::NodeData *) eh);
HTTPSocket<CLIENT>::Data *httpSocketData = new HTTPSocket<CLIENT>::Data(&socketData);
httpSocketData->host = hostname;
httpSocketData->path = path;
httpSocketData->httpUser = user;
uS::Socket s = uS::Node::connect<onClientConnection>(hostname.c_str(), port, secure, httpSocketData);
if (s) {
s.startTimeout<HTTPSocket<CLIENT>::onEnd>(timeoutMs);
}
} else {
eh->errorHandler(user);
}
}
bool Hub::upgrade(uv_os_sock_t fd, const char *secKey, SSL *ssl, const char *extensions, size_t extensionsLength, Group<SERVER> *serverGroup) {
if (!serverGroup) {
serverGroup = &getDefaultGroup<SERVER>();
}
uS::Socket s = uS::Socket::init((uS::NodeData *) serverGroup, fd, ssl);
uS::SocketData *socketData = s.getSocketData();
HTTPSocket<SERVER>::Data *temporaryHttpData = new HTTPSocket<SERVER>::Data(socketData);
delete socketData;
s.enterState<HTTPSocket<SERVER>>(temporaryHttpData);
// todo: move this into upgrade call
bool perMessageDeflate = false;
std::string extensionsResponse;
if (extensionsLength) {
ExtensionsNegotiator<uWS::SERVER> extensionsNegotiator(serverGroup->extensionOptions);
extensionsNegotiator.readOffer(std::string(extensions, extensionsLength));
extensionsResponse = extensionsNegotiator.generateOffer();
if (extensionsNegotiator.getNegotiatedOptions() & PERMESSAGE_DEFLATE) {
perMessageDeflate = true;
}
}
if (HTTPSocket<SERVER>(s).upgrade(secKey, extensionsResponse.data(), extensionsResponse.length())) {
s.enterState<WebSocket<SERVER>>(new WebSocket<SERVER>::Data(perMessageDeflate, s.getSocketData()));
serverGroup->addWebSocket(s);
serverGroup->connectionHandler(WebSocket<SERVER>(s), {nullptr, nullptr, 0, 0});
delete temporaryHttpData;
return true;
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_4877_0 |
crossvul-cpp_data_bad_3594_0 | /***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevector.h>
#include <tdebug.h>
#include <xiphcomment.h>
using namespace TagLib;
class Ogg::XiphComment::XiphCommentPrivate
{
public:
FieldListMap fieldListMap;
String vendorID;
String commentField;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
Ogg::XiphComment::XiphComment() : TagLib::Tag()
{
d = new XiphCommentPrivate;
}
Ogg::XiphComment::XiphComment(const ByteVector &data) : TagLib::Tag()
{
d = new XiphCommentPrivate;
parse(data);
}
Ogg::XiphComment::~XiphComment()
{
delete d;
}
String Ogg::XiphComment::title() const
{
if(d->fieldListMap["TITLE"].isEmpty())
return String::null;
return d->fieldListMap["TITLE"].front();
}
String Ogg::XiphComment::artist() const
{
if(d->fieldListMap["ARTIST"].isEmpty())
return String::null;
return d->fieldListMap["ARTIST"].front();
}
String Ogg::XiphComment::album() const
{
if(d->fieldListMap["ALBUM"].isEmpty())
return String::null;
return d->fieldListMap["ALBUM"].front();
}
String Ogg::XiphComment::comment() const
{
if(!d->fieldListMap["DESCRIPTION"].isEmpty()) {
d->commentField = "DESCRIPTION";
return d->fieldListMap["DESCRIPTION"].front();
}
if(!d->fieldListMap["COMMENT"].isEmpty()) {
d->commentField = "COMMENT";
return d->fieldListMap["COMMENT"].front();
}
return String::null;
}
String Ogg::XiphComment::genre() const
{
if(d->fieldListMap["GENRE"].isEmpty())
return String::null;
return d->fieldListMap["GENRE"].front();
}
TagLib::uint Ogg::XiphComment::year() const
{
if(!d->fieldListMap["DATE"].isEmpty())
return d->fieldListMap["DATE"].front().toInt();
if(!d->fieldListMap["YEAR"].isEmpty())
return d->fieldListMap["YEAR"].front().toInt();
return 0;
}
TagLib::uint Ogg::XiphComment::track() const
{
if(!d->fieldListMap["TRACKNUMBER"].isEmpty())
return d->fieldListMap["TRACKNUMBER"].front().toInt();
if(!d->fieldListMap["TRACKNUM"].isEmpty())
return d->fieldListMap["TRACKNUM"].front().toInt();
return 0;
}
void Ogg::XiphComment::setTitle(const String &s)
{
addField("TITLE", s);
}
void Ogg::XiphComment::setArtist(const String &s)
{
addField("ARTIST", s);
}
void Ogg::XiphComment::setAlbum(const String &s)
{
addField("ALBUM", s);
}
void Ogg::XiphComment::setComment(const String &s)
{
addField(d->commentField.isEmpty() ? "DESCRIPTION" : d->commentField, s);
}
void Ogg::XiphComment::setGenre(const String &s)
{
addField("GENRE", s);
}
void Ogg::XiphComment::setYear(uint i)
{
removeField("YEAR");
if(i == 0)
removeField("DATE");
else
addField("DATE", String::number(i));
}
void Ogg::XiphComment::setTrack(uint i)
{
removeField("TRACKNUM");
if(i == 0)
removeField("TRACKNUMBER");
else
addField("TRACKNUMBER", String::number(i));
}
bool Ogg::XiphComment::isEmpty() const
{
FieldListMap::ConstIterator it = d->fieldListMap.begin();
for(; it != d->fieldListMap.end(); ++it)
if(!(*it).second.isEmpty())
return false;
return true;
}
TagLib::uint Ogg::XiphComment::fieldCount() const
{
uint count = 0;
FieldListMap::ConstIterator it = d->fieldListMap.begin();
for(; it != d->fieldListMap.end(); ++it)
count += (*it).second.size();
return count;
}
const Ogg::FieldListMap &Ogg::XiphComment::fieldListMap() const
{
return d->fieldListMap;
}
String Ogg::XiphComment::vendorID() const
{
return d->vendorID;
}
void Ogg::XiphComment::addField(const String &key, const String &value, bool replace)
{
if(replace)
removeField(key.upper());
if(!key.isEmpty() && !value.isEmpty())
d->fieldListMap[key.upper()].append(value);
}
void Ogg::XiphComment::removeField(const String &key, const String &value)
{
if(!value.isNull()) {
StringList::Iterator it = d->fieldListMap[key].begin();
while(it != d->fieldListMap[key].end()) {
if(value == *it)
it = d->fieldListMap[key].erase(it);
else
it++;
}
}
else
d->fieldListMap.erase(key);
}
bool Ogg::XiphComment::contains(const String &key) const
{
return d->fieldListMap.contains(key) && !d->fieldListMap[key].isEmpty();
}
ByteVector Ogg::XiphComment::render() const
{
return render(true);
}
ByteVector Ogg::XiphComment::render(bool addFramingBit) const
{
ByteVector data;
// Add the vendor ID length and the vendor ID. It's important to use the
// length of the data(String::UTF8) rather than the length of the the string
// since this is UTF8 text and there may be more characters in the data than
// in the UTF16 string.
ByteVector vendorData = d->vendorID.data(String::UTF8);
data.append(ByteVector::fromUInt(vendorData.size(), false));
data.append(vendorData);
// Add the number of fields.
data.append(ByteVector::fromUInt(fieldCount(), false));
// Iterate over the the field lists. Our iterator returns a
// std::pair<String, StringList> where the first String is the field name and
// the StringList is the values associated with that field.
FieldListMap::ConstIterator it = d->fieldListMap.begin();
for(; it != d->fieldListMap.end(); ++it) {
// And now iterate over the values of the current list.
String fieldName = (*it).first;
StringList values = (*it).second;
StringList::ConstIterator valuesIt = values.begin();
for(; valuesIt != values.end(); ++valuesIt) {
ByteVector fieldData = fieldName.data(String::UTF8);
fieldData.append('=');
fieldData.append((*valuesIt).data(String::UTF8));
data.append(ByteVector::fromUInt(fieldData.size(), false));
data.append(fieldData);
}
}
// Append the "framing bit".
if(addFramingBit)
data.append(char(1));
return data;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void Ogg::XiphComment::parse(const ByteVector &data)
{
// The first thing in the comment data is the vendor ID length, followed by a
// UTF8 string with the vendor ID.
int pos = 0;
int vendorLength = data.mid(0, 4).toUInt(false);
pos += 4;
d->vendorID = String(data.mid(pos, vendorLength), String::UTF8);
pos += vendorLength;
// Next the number of fields in the comment vector.
int commentFields = data.mid(pos, 4).toUInt(false);
pos += 4;
for(int i = 0; i < commentFields; i++) {
// Each comment field is in the format "KEY=value" in a UTF8 string and has
// 4 bytes before the text starts that gives the length.
int commentLength = data.mid(pos, 4).toUInt(false);
pos += 4;
String comment = String(data.mid(pos, commentLength), String::UTF8);
pos += commentLength;
int commentSeparatorPosition = comment.find("=");
String key = comment.substr(0, commentSeparatorPosition);
String value = comment.substr(commentSeparatorPosition + 1);
addField(key, value, false);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_3594_0 |
crossvul-cpp_data_bad_600_1 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/test/HTTPParallelCodecTest.h>
#include <proxygen/lib/http/codec/test/MockHTTPCodec.h>
#include <folly/io/Cursor.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/test/HTTP2FramerTest.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <folly/portability/GTest.h>
#include <folly/portability/GMock.h>
#include <random>
using namespace proxygen;
using namespace proxygen::compress;
using namespace folly;
using namespace folly::io;
using namespace std;
using namespace testing;
TEST(HTTP2CodecConstantsTest, HTTPContantsAreCommonHeaders) {
// The purpose of this test is to verify some basic assumptions that should
// never change but to make clear that the following http2 header constants
// map to the respective common headers. Should this test ever fail, the
// H2Codec would need to be updated in the corresponding places when creating
// compress/Header objects.
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kMethod),
HTTP_HEADER_COLON_METHOD);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kScheme),
HTTP_HEADER_COLON_SCHEME);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kPath),
HTTP_HEADER_COLON_PATH);
EXPECT_EQ(
HTTPCommonHeaders::hash(headers::kAuthority),
HTTP_HEADER_COLON_AUTHORITY);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kStatus),
HTTP_HEADER_COLON_STATUS);
}
class HTTP2CodecTest : public HTTPParallelCodecTest {
public:
HTTP2CodecTest()
:HTTPParallelCodecTest(upstreamCodec_, downstreamCodec_) {}
void SetUp() override {
HTTPParallelCodecTest::SetUp();
}
void testHeaderListSize(bool oversized);
void testFrameSizeLimit(bool oversized);
protected:
HTTP2Codec upstreamCodec_{TransportDirection::UPSTREAM};
HTTP2Codec downstreamCodec_{TransportDirection::DOWNSTREAM};
};
TEST_F(HTTP2CodecTest, IgnoreUnknownSettings) {
auto numSettings = downstreamCodec_.getIngressSettings()->getNumSettings();
std::deque<SettingPair> settings;
for (uint32_t i = 200; i < (200 + 1024); i++) {
settings.push_back(SettingPair(SettingsId(i), i));
}
http2::writeSettings(output_, settings);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(numSettings,
downstreamCodec_.getIngressSettings()->getNumSettings());
}
TEST_F(HTTP2CodecTest, NoExHeaders) {
// do not emit ENABLE_EX_HEADERS setting, if disabled
SetUpUpstreamTest();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.numSettings, 0);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
parseUpstream();
EXPECT_EQ(callbacks_.settings, 1);
// only 3 standard settings: HEADER_TABLE_SIZE, ENABLE_PUSH, MAX_FRAME_SIZE.
EXPECT_EQ(callbacks_.numSettings, 3);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersSetting) {
// disable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, EnableExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
EXPECT_EQ(true, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, InvalidExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
// attempt to set a invalid ENABLE_EX_HEADERS value
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 110)});
parse();
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeader) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, RequestFromServer) {
// this is to test EX_HEADERS frame, which carrys the HTTP request initiated
// by server side
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
SetUpUpstreamTest();
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
upstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true),
true);
parseUpstream();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, ResponseFromClient) {
// this is to test EX_HEADERS frame, which carrys the HTTP response replied by
// client side
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, resp,
HTTPCodec::ExAttributes(controlStream, true), true);
parse();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, ExHeadersWithPriority) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
auto req = getGetRequest();
auto pri = HTTPMessage::HTTPPriority(0, false, 7);
req.setHTTP2Priority(pri);
upstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.msg->getHTTP2Priority(), pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersIfNotEnabled) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
HTTPMessage req = getGetRequest("/guacamole");
downstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaders) {
static const std::string v1("GET");
static const std::string v2("/");
static const std::string v3("http");
static const std::string v4("foo.com");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 7);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPseudoHeaders) {
static const std::string v1("POST");
static const std::string v2("http");
static const std::string n3("foo");
static const std::string v3("bar");
static const std::string v4("/");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kScheme, v2),
Header::makeHeaderForTest(n3, v3),
Header::makeHeaderForTest(headers::kPath, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderValues) {
static const std::string v1("--1");
static const std::string v2("\13\10protocol-attack");
static const std::string v3("\13");
static const std::string v4("abc.com\\13\\10");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders;
allHeaders.push_back(reqHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 4);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
/**
* Ingress bytes with an empty header name
*/
const uint8_t kBufEmptyHeader[] = {
0x00, 0x00, 0x1d, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x82,
0x87, 0x44, 0x87, 0x62, 0x6b, 0x46, 0x41, 0xd2, 0x7a, 0x0b,
0x41, 0x89, 0xf1, 0xe3, 0xc2, 0xf2, 0x9c, 0xeb, 0x90, 0xf4,
0xff, 0x40, 0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7
};
TEST_F(HTTP2CodecTest, EmptyHeaderName) {
output_.append(IOBuf::copyBuffer(kBufEmptyHeader, sizeof(kBufEmptyHeader)));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicConnect) {
std::string authority = "myhost:1234";
HTTPMessage request;
request.setMethod(HTTPMethod::CONNECT);
request.getHeaders().add(proxygen::HTTP_HEADER_HOST, authority);
upstreamCodec_.generateHeader(output_, 1, request, false /* eom */);
parse();
callbacks_.expectMessage(false, 1, "");
EXPECT_EQ(HTTPMethod::CONNECT, callbacks_.msg->getMethod());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(authority, headers.getSingleOrEmpty(proxygen::HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, BadConnect) {
std::string v1 = "CONNECT";
std::string v2 = "somehost:576";
std::vector<proxygen::compress::Header> goodHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kAuthority, v2),
};
// See https://tools.ietf.org/html/rfc7540#section-8.3
std::string v3 = "/foobar";
std::vector<proxygen::compress::Header> badHeaders = {
Header::makeHeaderForTest(headers::kScheme, headers::kHttp),
Header::makeHeaderForTest(headers::kPath, v3),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < badHeaders.size(); i++, stream += 2) {
auto allHeaders = goodHeaders;
allHeaders.push_back(badHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, badHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
void HTTP2CodecTest::testHeaderListSize(bool oversized) {
if (oversized) {
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
}
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("x-long-long-header",
"supercalafragalisticexpialadoshus");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
void HTTP2CodecTest::testFrameSizeLimit(bool oversized) {
HTTPMessage req = getBigGetRequest("/guacamole");
auto settings = downstreamCodec_.getEgressSettings();
parse(); // consume preface
if (oversized) {
// trick upstream for sending a 2x bigger HEADERS frame
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin * 2);
downstreamCodec_.generateSettings(output_);
parseUpstream();
}
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
TEST_F(HTTP2CodecTest, NormalSizeHeader) {
testHeaderListSize(false);
}
TEST_F(HTTP2CodecTest, OversizedHeader) {
testHeaderListSize(true);
}
TEST_F(HTTP2CodecTest, NormalSizeFrame) {
testFrameSizeLimit(false);
}
TEST_F(HTTP2CodecTest, OversizedFrame) {
testFrameSizeLimit(true);
}
TEST_F(HTTP2CodecTest, BigHeaderCompressed) {
SetUpUpstreamTest();
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
downstreamCodec_.generateSettings(output_);
parseUpstream();
SetUp();
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeaderReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
// HTTP/2 doesnt support serialization - instead you get the default
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadHeadersReply) {
static const std::string v1("200");
static const vector<proxygen::compress::Header> respHeaders = {
Header::makeHeaderForTest(headers::kStatus, v1),
};
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, Cookies) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add("Cookie", "chocolate-chip=1");
req.getHeaders().add("Cookie", "rainbow-chip=2");
req.getHeaders().add("Cookie", "butterscotch=3");
req.getHeaders().add("Cookie", "oatmeal-raisin=4");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, "/guacamole");
EXPECT_EQ(callbacks_.msg->getCookie("chocolate-chip"), "1");
EXPECT_EQ(callbacks_.msg->getCookie("rainbow-chip"), "2");
EXPECT_EQ(callbacks_.msg->getCookie("butterscotch"), "3");
EXPECT_EQ(callbacks_.msg->getCookie("oatmeal-raisin"), "4");
}
TEST_F(HTTP2CodecTest, BasicContinuation) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicContinuationEndStream) {
// CONTINUATION with END_STREAM flag set on the preceding HEADERS frame
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadContinuation) {
// CONTINUATION with no preceding HEADERS
auto fakeHeaders = makeBuf(5);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, MissingContinuation) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, MissingContinuationBadFrame) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert an invalid frame
auto frame = makeBuf(http2::kFrameHeaderSize + 4134);
*((uint32_t *)frame->writableData()) = 0xfa000000;
output_.append(std::move(frame));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, BadContinuationStream) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
auto fakeHeaders = makeBuf(4134);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, FrameTooLarge) {
writeFrameHeaderManual(output_, 1 << 15, 0, 0, 1);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_TRUE(callbacks_.lastParseError->hasCodecStatusCode());
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::FRAME_SIZE_ERROR);
}
TEST_F(HTTP2CodecTest, UnknownFrameType) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// unknown frame type 17
writeFrameHeaderManual(output_, 17, 37, 0, 1);
output_.append("wicked awesome!!!");
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, ""); // + host
}
TEST_F(HTTP2CodecTest, JunkAfterConnError) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// write headers frame for stream 0
writeFrameHeaderManual(output_, 0, (uint8_t)http2::FrameType::HEADERS, 0, 0);
// now write a valid headers frame, should never be parsed
upstreamCodec_.generateHeader(output_, 1, req);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicData) {
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), data);
}
TEST_F(HTTP2CodecTest, LongData) {
// Hack the max frame size artificially low
HTTPSettings* settings = (HTTPSettings*)upstreamCodec_.getIngressSettings();
settings->setSetting(SettingsId::MAX_FRAME_SIZE, 16);
auto buf = makeBuf(100);
upstreamCodec_.generateBody(output_, 1, buf->clone(), HTTPCodec::NoPadding,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 7);
EXPECT_EQ(callbacks_.bodyLength, 100);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, MalformedPaddingLength) {
const uint8_t badInput[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x7e, 0x00, 0x6f, 0x6f, 0x6f, 0x6f,
// The padding length byte below is 0x82 (130
// in decimal) which is greater than the length
// specified by the header's length field, 126
0x01, 0x82, 0x87, 0x44, 0x87, 0x92, 0x97, 0x92,
0x92, 0x92, 0x7a, 0x0b, 0x41, 0x89, 0xf1, 0xe3,
0xc0, 0xf2, 0x9c, 0xdd, 0x90, 0xf4, 0xff, 0x40,
0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7};
output_.clear();
output_.append(badInput, sizeof(badInput));
EXPECT_EQ(output_.chainLength(), sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, MalformedPadding) {
const uint8_t badInput[] = {
0x00, 0x00, 0x0d, 0x01, 0xbe, 0x63, 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x73,
0x00, 0x00, 0x06, 0x08, 0x72, 0x00, 0x24, 0x00, 0xfa, 0x4d, 0x0d
};
output_.append(badInput, sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, NoAppByte) {
const uint8_t noAppByte[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x56, 0x00, 0x5d, 0x00, 0x00, 0x00,
0x01, 0x55, 0x00};
output_.clear();
output_.append(noAppByte, sizeof(noAppByte));
EXPECT_EQ(output_.chainLength(), sizeof(noAppByte));
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataOnFrameHeaderCall) {
using namespace testing;
NiceMock<MockHTTPCodecCallback> mockCallback;
EXPECT_CALL(mockCallback, onFrameHeader(_, _, _, _, _));
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
downstreamCodec_.setCallback(&mockCallback);
auto ingress = output_.move();
ingress->coalesce();
// Copy partial byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
downstreamCodec_.onIngress(*ingress1);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataWithNoAppByte) {
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
auto ingress = output_.move();
ingress->coalesce();
// Copy up to the padding length byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
size_t parsed = downstreamCodec_.onIngress(*ingress1);
// The 34th byte is the padding length byte which should not be parsed
EXPECT_EQ(parsed, 33);
// Copy from the padding length byte to the end
auto ingress2 = IOBuf::copyBuffer(ingress->data() + 33, 21);
parsed = downstreamCodec_.onIngress(*ingress2);
// The padding length byte should be parsed this time along with 10 bytes of
// application data and 10 bytes of padding
EXPECT_EQ(parsed, 21);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, bufSize);
// Total padding is the padding length byte and the padding bytes
EXPECT_EQ(callbacks_.paddingBytes, padding + 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, BasicRst) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicRstInvalidCode) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::_SPDY_INVALID_STREAM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicPing) {
upstreamCodec_.generatePingRequest(output_);
upstreamCodec_.generatePingReply(output_, 17);
uint64_t pingReq;
parse([&] (IOBuf* ingress) {
folly::io::Cursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
pingReq = c.read<uint64_t>();
});
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.recvPingRequest, pingReq);
EXPECT_EQ(callbacks_.recvPingReply, 17);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicWindow) {
// This test would fail if the codec had window state
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
upstreamCodec_.generateWindowUpdate(output_, 0, http2::kMaxWindowUpdateSize);
upstreamCodec_.generateWindowUpdate(output_, 1, 12);
upstreamCodec_.generateWindowUpdate(output_, 1, http2::kMaxWindowUpdateSize);
parse();
EXPECT_EQ(callbacks_.windowUpdateCalls, 4);
EXPECT_EQ(callbacks_.windowUpdates[0],
std::vector<uint32_t>({10, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.windowUpdates[1],
std::vector<uint32_t>({12, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, ZeroWindow) {
auto streamID = HTTPCodec::StreamID(1);
// First generate a frame with delta=1 so as to pass the checks, and then
// hack the frame so that delta=0 without modifying other checks
upstreamCodec_.generateWindowUpdate(output_, streamID, 1);
output_.trimEnd(http2::kFrameWindowUpdateSize);
QueueAppender appender(&output_, http2::kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(0);
parse();
// This test doesn't ensure that RST_STREAM is generated
EXPECT_EQ(callbacks_.windowUpdateCalls, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::PROTOCOL_ERROR);
}
TEST_F(HTTP2CodecTest, BasicGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_DEATH_NO_CORE(upstreamCodec_.generateGoaway(
output_, 27, ErrorCode::ENHANCE_YOUR_CALM), ".*");
}
TEST_F(HTTP2CodecTest, DoubleGoaway) {
parse();
SetUpUpstreamTest();
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::NO_ERROR);
EXPECT_TRUE(downstreamCodec_.isWaitingToDrain());
EXPECT_TRUE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
downstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parseUpstream();
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_EQ(callbacks_.goaways, 2);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parse();
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(2));
}
TEST_F(HTTP2CodecTest, DoubleGoawayWithError) {
SetUpUpstreamTest();
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
auto ret = downstreamCodec_.generateGoaway(output_, 0,
ErrorCode::NO_ERROR);
EXPECT_EQ(ret, 0);
parseUpstream();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, GoawayHandling) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
// send request
HTTPMessage req = getGetRequest();
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
EXPECT_GT(size.uncompressed, 0);
parse();
callbacks_.expectMessage(true, 1, "/");
callbacks_.reset();
SetUpUpstreamTest();
// drain after this message
downstreamCodec_.generateGoaway(output_, 1, ErrorCode::NO_ERROR);
parseUpstream();
// upstream cannot generate id > 1
upstreamCodec_.generateHeader(output_, 3, req, false, &size);
EXPECT_EQ(size.uncompressed, 0);
upstreamCodec_.generateWindowUpdate(output_, 3, 100);
upstreamCodec_.generateBody(output_, 3, makeBuf(10), HTTPCodec::NoPadding,
false);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateEOM(output_, 3);
upstreamCodec_.generateRstStream(output_, 3, ErrorCode::CANCEL);
EXPECT_EQ(output_.chainLength(), 0);
// send a push promise that will be rejected by downstream
req.getHeaders().add("foomonkey", "george");
downstreamCodec_.generatePushPromise(output_, 2, req, 1, false, &size);
EXPECT_GT(size.uncompressed, 0);
HTTPMessage resp;
resp.setStatusCode(200);
// send a push response that will be ignored
downstreamCodec_.generateHeader(output_, 2, resp, false, &size);
// window update for push doesn't make any sense, but whatever
downstreamCodec_.generateWindowUpdate(output_, 2, 100);
downstreamCodec_.generateBody(output_, 2, makeBuf(10), HTTPCodec::NoPadding,
false);
writeFrameHeaderManual(output_, 20, (uint8_t)http2::FrameType::DATA, 0, 2);
output_.append(makeBuf(10));
// tell the upstream no pushing, and parse the first batch
IOBufQueue dummy;
upstreamCodec_.generateGoaway(dummy, 0, ErrorCode::NO_ERROR);
parseUpstream();
output_.append(makeBuf(10));
downstreamCodec_.generatePriority(output_, 2,
HTTPMessage::HTTPPriority(0, true, 1));
downstreamCodec_.generateEOM(output_, 2);
downstreamCodec_.generateRstStream(output_, 2, ErrorCode::CANCEL);
// send a response that will be accepted, headers should be ok
downstreamCodec_.generateHeader(output_, 1, resp, true, &size);
EXPECT_GT(size.uncompressed, 0);
// parse the remainder
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
}
TEST_F(HTTP2CodecTest, GoawayReply) {
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
}
TEST_F(HTTP2CodecTest, BasicSetting) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS, 37);
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 12345);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.maxStreams, 37);
EXPECT_EQ(callbacks_.windowSize, 12345);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsAck) {
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.settingsAcks, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadSettings) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 0xffffffff);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BadPushSettings) {
auto settings = downstreamCodec_.getEgressSettings();
settings->clearSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 0);
SetUpUpstreamTest();
parseUpstream([&] (IOBuf* ingress) {
EXPECT_EQ(ingress->computeChainDataLength(), http2::kFrameHeaderSize);
});
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
// Only way to disable push for downstreamCodec_ is to read
// ENABLE_PUSH:0 from client
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadSettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
// This sets the max decoder table size to 8k
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
callbacks_.reset();
// Attempt to set a new max table size. This is a no-op because the first,
// setting is unacknowledged. The upstream encoder will up the table size to
// 8k per the first settings frame and the HPACK codec will send a code to
// update the decoder.
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 4096);
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSizeEarlyShrink) {
// Lower size to 2k
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 2048);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
// Parsing SETTINGS ack updates upstream decoder to 2k
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
// downstream encoder will send TSU/2k
downstreamCodec_.generateHeader(output_, 1, resp);
// sets pending table size to 512, but doesn't update it yet
settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 512);
IOBufQueue tmp{IOBufQueue::cacheChainLength()};
upstreamCodec_.generateSettings(tmp);
// Previous code would barf here, since TSU/2k is a violation of the current
// max=512
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BasicPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.priority, pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderPriority) {
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DuplicateBadHeaderPriority) {
// Sent an initial header with a circular dependency
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// Hack ingress with circular dependency.
EXPECT_TRUE(parse([&](IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
// On the same stream, send another request.
HTTPMessage nextRequest = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, nextRequest, true /* eom */);
parse();
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
class DummyQueue: public HTTPCodec::PriorityQueue {
public:
DummyQueue() {}
~DummyQueue() override {}
void addPriorityNode(HTTPCodec::StreamID id, HTTPCodec::StreamID) override {
nodes_.push_back(id);
}
std::vector<HTTPCodec::StreamID> nodes_;
};
TEST_F(HTTP2CodecTest, VirtualNodes) {
DummyQueue queue;
uint8_t level = 30;
upstreamCodec_.addPriorityNodes(queue, output_, level);
EXPECT_TRUE(parse());
for (int i = 0; i < level; i++) {
EXPECT_EQ(queue.nodes_[i], upstreamCodec_.mapPriorityToDependency(i));
}
// Out-of-range priorites are mapped to the lowest level of virtual nodes.
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level));
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level + 1));
}
TEST_F(HTTP2CodecTest, BasicPushPromise) {
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
EXPECT_FALSE(downstreamCodec_.supportsPushTransactions());
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_TRUE(upstreamCodec_.supportsPushTransactions());
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
SetUpUpstreamTest();
HTTPCodec::StreamID assocStream = 7;
for (auto i = 0; i < 2; i++) {
// Push promise
HTTPCodec::StreamID pushStream = downstreamCodec_.createStream();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, pushStream, req, assocStream);
parseUpstream();
callbacks_.expectMessage(false, 2, "/"); // + host
EXPECT_EQ(callbacks_.assocStreamId, assocStream);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
callbacks_.reset();
// Actual reply headers
HTTPMessage resp;
resp.setStatusCode(200);
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "text/plain");
downstreamCodec_.generateHeader(output_, pushStream, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("text/plain", callbacks_.msg->getHeaders().getSingleOrEmpty(
HTTP_HEADER_CONTENT_TYPE));
callbacks_.reset();
}
}
TEST_F(HTTP2CodecTest, BadPushPromise) {
// ENABLE_PUSH is now 0 by default
SetUpUpstreamTest();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicCertificateRequest) {
uint16_t requestId = 17;
std::unique_ptr<folly::IOBuf> authRequest =
folly::IOBuf::copyBuffer("authRequestData");
upstreamCodec_.generateCertificateRequest(
output_, requestId, std::move(authRequest));
parse();
EXPECT_EQ(callbacks_.certificateRequests, 1);
EXPECT_EQ(callbacks_.lastCertRequestId, requestId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authRequestData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicCertificate) {
uint16_t certId = 17;
std::unique_ptr<folly::IOBuf> authenticator =
folly::IOBuf::copyBuffer("authenticatorData");
upstreamCodec_.generateCertificate(output_, certId, std::move(authenticator));
parse();
EXPECT_EQ(callbacks_.certificates, 1);
EXPECT_EQ(callbacks_.lastCertId, certId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authenticatorData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadServerPreface) {
output_.move();
downstreamCodec_.generateWindowUpdate(output_, 0, 10);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, Normal1024Continuation) {
HTTPMessage req = getGetRequest();
string bigval(8691, '!');
bigval.append(8691, ' ');
req.getHeaders().add("x-headr", bigval);
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(bigval, headers.getSingleOrEmpty("x-headr"));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settingsAcks, 1);
}
TEST_F(HTTP2CodecTest, StreamIdOverflow) {
HTTP2Codec codec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID streamId;
codec.setNextEgressStreamId(std::numeric_limits<int32_t>::max() - 10);
while (codec.isReusable()) {
streamId = codec.createStream();
}
EXPECT_EQ(streamId, std::numeric_limits<int32_t>::max() - 2);
}
TEST_F(HTTP2CodecTest, TestMultipleDifferentContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add(HTTP_HEADER_CONTENT_LENGTH, "300");
EXPECT_EQ(req.getHeaders().getNumberOfValues(HTTP_HEADER_CONTENT_LENGTH), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the request fails before the codec finishes parsing the headers
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.lastParseError->getHttpStatusCode(), 400);
}
TEST_F(HTTP2CodecTest, TestMultipleIdenticalContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add("content-length", "200");
EXPECT_EQ(req.getHeaders().getNumberOfValues("content-length"), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the headers parsing completes correctly
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.headersComplete, 1);
}
TEST_F(HTTP2CodecTest, CleartextUpgrade) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
HTTP2Codec::requestUpgrade(req);
EXPECT_EQ(req.getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE), "h2c");
EXPECT_TRUE(req.checkForHeaderToken(HTTP_HEADER_CONNECTION,
"Upgrade", false));
EXPECT_TRUE(req.checkForHeaderToken(
HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(), false));
EXPECT_GT(
req.getHeaders().getSingleOrEmpty(http2::kProtocolSettingsHeader).length(),
0);
}
TEST_F(HTTP2CodecTest, HTTP2SettingsSuccess) {
HTTPMessage req = getGetRequest("/guacamole");
// empty settings
req.getHeaders().add(http2::kProtocolSettingsHeader, "");
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
// real settings (overwrites empty)
HTTP2Codec::requestUpgrade(req);
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2SettingsFailure) {
HTTPMessage req = getGetRequest("/guacamole");
// no settings
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
HTTPHeaders& headers = req.getHeaders();
// Not base64_url settings
headers.set(http2::kProtocolSettingsHeader, "????");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
headers.set(http2::kProtocolSettingsHeader, "AAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Too big
string bigSettings((http2::kMaxFramePayloadLength + 1) * 4 / 3, 'A');
headers.set(http2::kProtocolSettingsHeader, bigSettings);
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Malformed (not a multiple of 6)
headers.set(http2::kProtocolSettingsHeader, "AAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Two headers
headers.set(http2::kProtocolSettingsHeader, "AAAAAAAA");
headers.add(http2::kProtocolSettingsHeader, "AAAAAAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2EnableConnect) {
SetUpUpstreamTest();
// egress settings have no connect settings.
auto ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
// enable connect settings, and check.
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL, 1);
ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
EXPECT_EQ(ws_enable->value, 1);
// generateSettings.
// pass the buffer to be parsed by the codec and check for ingress settings.
upstreamCodec_.generateSettings(output_);
parseUpstream();
EXPECT_EQ(1, upstreamCodec_.peerHasWebsockets());
}
TEST_F(HTTP2CodecTest, WebsocketUpgrade) {
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
EXPECT_TRUE(callbacks_.msg->isIngressWebsocketUpgrade());
EXPECT_NE(nullptr, callbacks_.msg->getUpgradeProtocol());
EXPECT_EQ(headers::kWebsocketString, *callbacks_.msg->getUpgradeProtocol());
}
TEST_F(HTTP2CodecTest, WebsocketBadHeader) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
};
vector<proxygen::compress::Header> optionalHeaders = {
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
int stream = 1;
for (size_t i = 0; i < optionalHeaders.size(); ++i, stream += 2) {
auto headers = reqHeaders;
headers.push_back(optionalHeaders[i]);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
false,
true);
parse();
}
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, optionalHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketDupProtocol) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> headers = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
1,
folly::none,
http2::kNoPadding,
false,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketIncorrectResponse) {
parse();
SetUpUpstreamTest();
parseUpstream();
output_.clear();
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
output_.clear();
HTTPMessage resp;
resp.setStatusCode(201);
resp.setStatusMessage("OK");
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TestAllEgressFrameTypeCallbacks) {
class CallbackTypeTracker {
std::set<uint8_t> types;
public:
void add(uint8_t, uint8_t type, uint64_t, uint16_t) {
types.insert(type);
}
bool isAllFrameTypesReceived() {
http2::FrameType expectedTypes[] = {
http2::FrameType::DATA,
http2::FrameType::HEADERS,
http2::FrameType::PRIORITY,
http2::FrameType::RST_STREAM,
http2::FrameType::SETTINGS,
http2::FrameType::PUSH_PROMISE,
http2::FrameType::PING,
http2::FrameType::GOAWAY,
http2::FrameType::WINDOW_UPDATE,
http2::FrameType::CONTINUATION,
http2::FrameType::EX_HEADERS,
};
for(http2::FrameType type: expectedTypes) {
EXPECT_TRUE(types.find(static_cast<uint8_t>(type)) != types.end())
<< "callback missing for type " << static_cast<uint8_t>(type);
}
return types.size() == (sizeof(expectedTypes)/sizeof(http2::FrameType));
}
};
CallbackTypeTracker callbackTypeTracker;
NiceMock<MockHTTPCodecCallback> mockCallback;
upstreamCodec_.setCallback(&mockCallback);
downstreamCodec_.setCallback(&mockCallback);
EXPECT_CALL(mockCallback, onGenerateFrameHeader(_, _, _, _)).
WillRepeatedly(Invoke(&callbackTypeTracker, &CallbackTypeTracker::add));
// DATA frame
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
HTTPMessage req = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
upstreamCodec_.generateSettings(output_);
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
upstreamCodec_.generatePingRequest(output_);
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true));
// Tests the continuation frame
req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
EXPECT_TRUE(callbackTypeTracker.isAllFrameTypesReceived());
}
TEST_F(HTTP2CodecTest, Trailers) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersWithPseudoHeaders) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TrailersNoBody) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, TrailersContinuation) {
HTTPMessage req = getGetRequest("/guacamole");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(callbacks_.msg->getTrailers(), nullptr);
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-trailer-2", "chicken-kyiv");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ("chicken-kyiv",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-2"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithNoData) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithPseudoHeaders) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, TrailersReplyContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.msg->getStatusCode(), 200);
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyMissingContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4132);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_600_1 |
crossvul-cpp_data_bad_238_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Config.h>
#include <znc/FileUtils.h>
#include <stack>
#include <sstream>
struct ConfigStackEntry {
CString sTag;
CString sName;
CConfig Config;
ConfigStackEntry(const CString& Tag, const CString Name)
: sTag(Tag), sName(Name), Config() {}
};
CConfigEntry::CConfigEntry() : m_pSubConfig(nullptr) {}
CConfigEntry::CConfigEntry(const CConfig& Config)
: m_pSubConfig(new CConfig(Config)) {}
CConfigEntry::CConfigEntry(const CConfigEntry& other) : m_pSubConfig(nullptr) {
if (other.m_pSubConfig) m_pSubConfig = new CConfig(*other.m_pSubConfig);
}
CConfigEntry::~CConfigEntry() { delete m_pSubConfig; }
CConfigEntry& CConfigEntry::operator=(const CConfigEntry& other) {
delete m_pSubConfig;
if (other.m_pSubConfig)
m_pSubConfig = new CConfig(*other.m_pSubConfig);
else
m_pSubConfig = nullptr;
return *this;
}
bool CConfig::Parse(CFile& file, CString& sErrorMsg) {
CString sLine;
unsigned int uLineNum = 0;
CConfig* pActiveConfig = this;
std::stack<ConfigStackEntry> ConfigStack;
bool bCommented = false; // support for /**/ style comments
if (!file.Seek(0)) {
sErrorMsg = "Could not seek to the beginning of the config.";
return false;
}
while (file.ReadLine(sLine)) {
uLineNum++;
#define ERROR(arg) \
do { \
std::stringstream stream; \
stream << "Error on line " << uLineNum << ": " << arg; \
sErrorMsg = stream.str(); \
m_SubConfigs.clear(); \
m_ConfigEntries.clear(); \
return false; \
} while (0)
// Remove all leading spaces and trailing line endings
sLine.TrimLeft();
sLine.TrimRight("\r\n");
if (bCommented || sLine.StartsWith("/*")) {
/* Does this comment end on the same line again? */
bCommented = (!sLine.EndsWith("*/"));
continue;
}
if ((sLine.empty()) || (sLine.StartsWith("#")) ||
(sLine.StartsWith("//"))) {
continue;
}
if ((sLine.StartsWith("<")) && (sLine.EndsWith(">"))) {
sLine.LeftChomp();
sLine.RightChomp();
sLine.Trim();
CString sTag = sLine.Token(0);
CString sValue = sLine.Token(1, true);
sTag.Trim();
sValue.Trim();
if (sTag.TrimPrefix("/")) {
if (!sValue.empty())
ERROR("Malformated closing tag. Expected \"</" << sTag
<< ">\".");
if (ConfigStack.empty())
ERROR("Closing tag \"" << sTag << "\" which is not open.");
const struct ConfigStackEntry& entry = ConfigStack.top();
CConfig myConfig(entry.Config);
CString sName(entry.sName);
if (!sTag.Equals(entry.sTag))
ERROR("Closing tag \"" << sTag << "\" which is not open.");
// This breaks entry
ConfigStack.pop();
if (ConfigStack.empty())
pActiveConfig = this;
else
pActiveConfig = &ConfigStack.top().Config;
SubConfig& conf = pActiveConfig->m_SubConfigs[sTag.AsLower()];
SubConfig::const_iterator it = conf.find(sName);
if (it != conf.end())
ERROR("Duplicate entry for tag \"" << sTag << "\" name \""
<< sName << "\".");
conf[sName] = CConfigEntry(myConfig);
} else {
if (sValue.empty())
ERROR("Empty block name at begin of block.");
ConfigStack.push(ConfigStackEntry(sTag.AsLower(), sValue));
pActiveConfig = &ConfigStack.top().Config;
}
continue;
}
// If we have a regular line, figure out where it goes
CString sName = sLine.Token(0, false, "=");
CString sValue = sLine.Token(1, true, "=");
// Only remove the first space, people might want
// leading spaces (e.g. in the MOTD).
sValue.TrimPrefix(" ");
// We don't have any names with spaces, trim all
// leading/trailing spaces.
sName.Trim();
if (sName.empty() || sValue.empty()) ERROR("Malformed line");
CString sNameLower = sName.AsLower();
pActiveConfig->m_ConfigEntries[sNameLower].push_back(sValue);
}
if (bCommented) ERROR("Comment not closed at end of file.");
if (!ConfigStack.empty()) {
const CString& sTag = ConfigStack.top().sTag;
ERROR(
"Not all tags are closed at the end of the file. Inner-most open "
"tag is \""
<< sTag << "\".");
}
return true;
}
void CConfig::Write(CFile& File, unsigned int iIndentation) {
CString sIndentation = CString(iIndentation, '\t');
for (const auto& it : m_ConfigEntries) {
for (const CString& sValue : it.second) {
File.Write(sIndentation + it.first + " = " + sValue + "\n");
}
}
for (const auto& it : m_SubConfigs) {
for (const auto& it2 : it.second) {
File.Write("\n");
File.Write(sIndentation + "<" + it.first + " " + it2.first + ">\n");
it2.second.m_pSubConfig->Write(File, iIndentation + 1);
File.Write(sIndentation + "</" + it.first + ">\n");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_238_0 |
crossvul-cpp_data_good_512_0 | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "ScpFileSystem.h"
#include "Terminal.h"
#include "Common.h"
#include "Exceptions.h"
#include "Interface.h"
#include "TextsCore.h"
#include "HelpCore.h"
#include "SecureShell.h"
#include <StrUtils.hpp>
#include <stdio.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
#define FILE_OPERATION_LOOP_TERMINAL FTerminal
//---------------------------------------------------------------------------
const int coRaiseExcept = 1;
const int coExpectNoOutput = 2;
const int coWaitForLastLine = 4;
const int coOnlyReturnCode = 8;
const int coIgnoreWarnings = 16;
const int coReadProgress = 32;
const int ecRaiseExcept = 1;
const int ecIgnoreWarnings = 2;
const int ecReadProgress = 4;
const int ecDefault = ecRaiseExcept;
//---------------------------------------------------------------------------
DERIVE_EXT_EXCEPTION(EScpFileSkipped, ESkipFile);
//===========================================================================
#define MaxShellCommand fsLang
#define ShellCommandCount MaxShellCommand + 1
#define MaxCommandLen 40
struct TCommandType
{
int MinLines;
int MaxLines;
bool ModifiesFiles;
bool ChangesDirectory;
bool InteractiveCommand;
wchar_t Command[MaxCommandLen];
};
// Only one character! See TSCPFileSystem::ReadCommandOutput()
#define LastLineSeparator L":"
#define LAST_LINE L"WinSCP: this is end-of-file"
#define FIRST_LINE L"WinSCP: this is begin-of-file"
extern const TCommandType DefaultCommandSet[];
#define NationalVarCount 10
extern const wchar_t NationalVars[NationalVarCount][15];
#define CHECK_CMD DebugAssert((Cmd >=0) && (Cmd <= MaxShellCommand))
class TSessionData;
//---------------------------------------------------------------------------
class TCommandSet
{
private:
TCommandType CommandSet[ShellCommandCount];
TSessionData * FSessionData;
UnicodeString FReturnVar;
int __fastcall GetMaxLines(TFSCommand Cmd);
int __fastcall GetMinLines(TFSCommand Cmd);
bool __fastcall GetModifiesFiles(TFSCommand Cmd);
bool __fastcall GetChangesDirectory(TFSCommand Cmd);
bool __fastcall GetOneLineCommand(TFSCommand Cmd);
void __fastcall SetCommands(TFSCommand Cmd, UnicodeString value);
UnicodeString __fastcall GetCommands(TFSCommand Cmd);
UnicodeString __fastcall GetFirstLine();
bool __fastcall GetInteractiveCommand(TFSCommand Cmd);
UnicodeString __fastcall GetLastLine();
UnicodeString __fastcall GetReturnVar();
public:
__fastcall TCommandSet(TSessionData *aSessionData);
void __fastcall Default();
void __fastcall CopyFrom(TCommandSet * Source);
UnicodeString __fastcall Command(TFSCommand Cmd, const TVarRec * args, int size);
TStrings * __fastcall CreateCommandList();
UnicodeString __fastcall FullCommand(TFSCommand Cmd, const TVarRec * args, int size);
static UnicodeString __fastcall ExtractCommand(UnicodeString Command);
__property int MaxLines[TFSCommand Cmd] = { read=GetMaxLines};
__property int MinLines[TFSCommand Cmd] = { read=GetMinLines };
__property bool ModifiesFiles[TFSCommand Cmd] = { read=GetModifiesFiles };
__property bool ChangesDirectory[TFSCommand Cmd] = { read=GetChangesDirectory };
__property bool OneLineCommand[TFSCommand Cmd] = { read=GetOneLineCommand };
__property UnicodeString Commands[TFSCommand Cmd] = { read=GetCommands, write=SetCommands };
__property UnicodeString FirstLine = { read = GetFirstLine };
__property bool InteractiveCommand[TFSCommand Cmd] = { read = GetInteractiveCommand };
__property UnicodeString LastLine = { read=GetLastLine };
__property TSessionData * SessionData = { read=FSessionData, write=FSessionData };
__property UnicodeString ReturnVar = { read=GetReturnVar, write=FReturnVar };
};
//===========================================================================
const wchar_t NationalVars[NationalVarCount][15] =
{L"LANG", L"LANGUAGE", L"LC_CTYPE", L"LC_COLLATE", L"LC_MONETARY", L"LC_NUMERIC",
L"LC_TIME", L"LC_MESSAGES", L"LC_ALL", L"HUMAN_BLOCKS" };
const wchar_t FullTimeOption[] = L"--full-time";
//---------------------------------------------------------------------------
#define F false
#define T true
// TODO: remove "mf" and "cd", it is implemented in TTerminal already
const TCommandType DefaultCommandSet[ShellCommandCount] = {
// min max mf cd ia command
/*Null*/ { -1, -1, F, F, F, L"" },
/*VarValue*/ { -1, -1, F, F, F, L"echo \"$%s\"" /* variable */ },
/*LastLine*/ { -1, -1, F, F, F, L"echo \"%s" LastLineSeparator "%s\"" /* last line, return var */ },
/*FirstLine*/ { -1, -1, F, F, F, L"echo \"%s\"" /* first line */ },
/*CurrentDirectory*/ { 1, 1, F, F, F, L"pwd" },
/*ChangeDirectory*/ { 0, 0, F, T, F, L"cd %s" /* directory */ },
// list directory can be empty on permission denied, this is handled in ReadDirectory
/*ListDirectory*/ { -1, -1, F, F, F, L"%s %s \"%s\"" /* listing command, options, directory */ },
/*ListCurrentDirectory*/{ -1, -1, F, F, F, L"%s %s" /* listing command, options */ },
/*ListFile*/ { 1, 1, F, F, F, L"%s -d %s \"%s\"" /* listing command, options, file/directory */ },
/*LookupUserGroups*/ { 0, 1, F, F, F, L"groups" },
/*CopyToRemote*/ { -1, -1, T, F, T, L"scp -r %s -d -t \"%s\"" /* options, directory */ },
/*CopyToLocal*/ { -1, -1, F, F, T, L"scp -r %s -d -f \"%s\"" /* options, file */ },
/*DeleteFile*/ { 0, 0, T, F, F, L"rm -f -r \"%s\"" /* file/directory */},
/*RenameFile*/ { 0, 0, T, F, F, L"mv -f \"%s\" \"%s\"" /* file/directory, new name*/},
/*CreateDirectory*/ { 0, 0, T, F, F, L"mkdir \"%s\"" /* new directory */},
/*ChangeMode*/ { 0, 0, T, F, F, L"chmod %s %s \"%s\"" /* options, mode, filename */},
/*ChangeGroup*/ { 0, 0, T, F, F, L"chgrp %s \"%s\" \"%s\"" /* options, group, filename */},
/*ChangeOwner*/ { 0, 0, T, F, F, L"chown %s \"%s\" \"%s\"" /* options, owner, filename */},
/*HomeDirectory*/ { 0, 0, F, T, F, L"cd" },
/*Unset*/ { 0, 0, F, F, F, L"unset \"%s\"" /* variable */ },
/*Unalias*/ { 0, 0, F, F, F, L"unalias \"%s\"" /* alias */ },
/*CreateLink*/ { 0, 0, T, F, F, L"ln %s \"%s\" \"%s\"" /*symbolic (-s), filename, point to*/},
/*CopyFile*/ { 0, 0, T, F, F, L"cp -p -r -f %s \"%s\" \"%s\"" /* file/directory, target name*/},
/*AnyCommand*/ { 0, -1, T, T, F, L"%s" },
/*Lang*/ { 0, 1, F, F, F, L"printenv LANG"}
};
#undef F
#undef T
//---------------------------------------------------------------------------
__fastcall TCommandSet::TCommandSet(TSessionData *aSessionData):
FSessionData(aSessionData), FReturnVar(L"")
{
DebugAssert(FSessionData);
Default();
}
//---------------------------------------------------------------------------
void __fastcall TCommandSet::CopyFrom(TCommandSet * Source)
{
memmove(&CommandSet, Source->CommandSet, sizeof(CommandSet));
}
//---------------------------------------------------------------------------
void __fastcall TCommandSet::Default()
{
DebugAssert(sizeof(CommandSet) == sizeof(DefaultCommandSet));
memmove(&CommandSet, &DefaultCommandSet, sizeof(CommandSet));
}
//---------------------------------------------------------------------------
int __fastcall TCommandSet::GetMaxLines(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].MaxLines;
}
//---------------------------------------------------------------------------
int __fastcall TCommandSet::GetMinLines(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].MinLines;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetModifiesFiles(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].ModifiesFiles;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetChangesDirectory(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].ChangesDirectory;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetInteractiveCommand(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].InteractiveCommand;
}
//---------------------------------------------------------------------------
bool __fastcall TCommandSet::GetOneLineCommand(TFSCommand /*Cmd*/)
{
//CHECK_CMD;
// #56: we send "echo last line" from all commands on same line
// just as it was in 1.0
return True; //CommandSet[Cmd].OneLineCommand;
}
//---------------------------------------------------------------------------
void __fastcall TCommandSet::SetCommands(TFSCommand Cmd, UnicodeString value)
{
CHECK_CMD;
wcscpy(CommandSet[Cmd].Command, value.SubString(1, MaxCommandLen - 1).c_str());
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetCommands(TFSCommand Cmd)
{
CHECK_CMD;
return CommandSet[Cmd].Command;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::Command(TFSCommand Cmd, const TVarRec * args, int size)
{
if (args) return Format(Commands[Cmd], args, size);
else return Commands[Cmd];
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::FullCommand(TFSCommand Cmd, const TVarRec * args, int size)
{
UnicodeString Separator;
if (OneLineCommand[Cmd]) Separator = L" ; ";
else Separator = L"\n";
UnicodeString Line = Command(Cmd, args, size);
UnicodeString LastLineCmd =
Command(fsLastLine, ARRAYOFCONST((LastLine, ReturnVar)));
UnicodeString FirstLineCmd;
if (InteractiveCommand[Cmd])
FirstLineCmd = Command(fsFirstLine, ARRAYOFCONST((FirstLine))) + Separator;
UnicodeString Result;
if (!Line.IsEmpty())
Result = FORMAT(L"%s%s%s%s", (FirstLineCmd, Line, Separator, LastLineCmd));
else
Result = FORMAT(L"%s%s", (FirstLineCmd, LastLineCmd));
return Result;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetFirstLine()
{
return FIRST_LINE;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetLastLine()
{
return LAST_LINE;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::GetReturnVar()
{
DebugAssert(SessionData);
if (!FReturnVar.IsEmpty())
{
return UnicodeString(L'$') + FReturnVar;
}
else if (SessionData->DetectReturnVar)
{
return L'0';
}
else
{
return UnicodeString(L'$') + SessionData->ReturnVar;
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TCommandSet::ExtractCommand(UnicodeString Command)
{
int P = Command.Pos(L" ");
if (P > 0)
{
Command.SetLength(P-1);
}
return Command;
}
//---------------------------------------------------------------------------
TStrings * __fastcall TCommandSet::CreateCommandList()
{
TStrings * CommandList = new TStringList();
for (Integer Index = 0; Index < ShellCommandCount; Index++)
{
UnicodeString Cmd = Commands[(TFSCommand)Index];
if (!Cmd.IsEmpty())
{
Cmd = ExtractCommand(Cmd);
if ((Cmd != L"%s") && (CommandList->IndexOf(Cmd) < 0))
CommandList->Add(Cmd);
}
}
return CommandList;
}
//===========================================================================
__fastcall TSCPFileSystem::TSCPFileSystem(TTerminal * ATerminal, TSecureShell * SecureShell):
TCustomFileSystem(ATerminal)
{
FSecureShell = SecureShell;
FCommandSet = new TCommandSet(FTerminal->SessionData);
FLsFullTime = FTerminal->SessionData->SCPLsFullTime;
FOutput = new TStringList();
FProcessingCommand = false;
FOnCaptureOutput = NULL;
FFileSystemInfo.ProtocolBaseName = L"SCP";
FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
}
//---------------------------------------------------------------------------
__fastcall TSCPFileSystem::~TSCPFileSystem()
{
delete FCommandSet;
delete FOutput;
delete FSecureShell;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Open()
{
// this is used for reconnects only
FSecureShell->Open();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Close()
{
FSecureShell->Close();
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::GetActive()
{
return FSecureShell->Active;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CollectUsage()
{
FSecureShell->CollectUsage();
}
//---------------------------------------------------------------------------
const TSessionInfo & __fastcall TSCPFileSystem::GetSessionInfo()
{
return FSecureShell->GetSessionInfo();
}
//---------------------------------------------------------------------------
const TFileSystemInfo & __fastcall TSCPFileSystem::GetFileSystemInfo(bool Retrieve)
{
if (FFileSystemInfo.AdditionalInfo.IsEmpty() && Retrieve)
{
UnicodeString UName;
FTerminal->ExceptionOnFail = true;
try
{
try
{
AnyCommand(L"uname -a", NULL);
for (int Index = 0; Index < Output->Count; Index++)
{
if (Index > 0)
{
UName += L"; ";
}
UName += Output->Strings[Index];
}
}
catch(...)
{
if (!FTerminal->Active)
{
throw;
}
}
}
__finally
{
FTerminal->ExceptionOnFail = false;
}
FFileSystemInfo.RemoteSystem = UName;
}
return FFileSystemInfo;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
{
return false;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::GetStoredCredentialsTried()
{
return FSecureShell->GetStoredCredentialsTried();
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::GetUserName()
{
return FSecureShell->UserName;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Idle()
{
// Keep session alive
if ((FTerminal->SessionData->PingType != ptOff) &&
(Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
{
if ((FTerminal->SessionData->PingType == ptDummyCommand) &&
FSecureShell->Ready)
{
if (!FProcessingCommand)
{
ExecCommand(fsNull, NULL, 0, 0);
}
else
{
FTerminal->LogEvent(L"Cannot send keepalive, command is being executed");
// send at least SSH-level keepalive, if nothing else, it at least updates
// LastDataSent, no the next keepalive attempt is postponed
FSecureShell->KeepAlive();
}
}
else
{
FSecureShell->KeepAlive();
}
}
FSecureShell->Idle();
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::AbsolutePath(UnicodeString Path, bool /*Local*/)
{
return ::AbsolutePath(CurrentDirectory, Path);
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::IsCapable(int Capability) const
{
DebugAssert(FTerminal);
switch (Capability) {
case fcUserGroupListing:
case fcModeChanging:
case fcModeChangingUpload:
case fcPreservingTimestampUpload:
case fcGroupChanging:
case fcOwnerChanging:
case fcAnyCommand:
case fcShellAnyCommand:
case fcHardLink:
case fcSymbolicLink:
case fcResolveSymlink:
case fcRename:
case fcRemoteMove:
case fcRemoteCopy:
case fcRemoveCtrlZUpload:
case fcRemoveBOMUpload:
return true;
case fcTextMode:
return FTerminal->SessionData->EOLType != FTerminal->Configuration->LocalEOLType;
case fcNativeTextMode:
case fcNewerOnlyUpload:
case fcTimestampChanging:
case fcLoadingAdditionalProperties:
case fcCheckingSpaceAvailable:
case fcIgnorePermErrors:
case fcCalculatingChecksum:
case fcSecondaryShell: // has fcShellAnyCommand
case fcGroupOwnerChangingByID: // by name
case fcMoveToQueue:
case fcLocking:
case fcPreservingTimestampDirs:
case fcResumeSupport:
case fsSkipTransfer:
case fsParallelTransfers: // does not implement cpNoRecurse
return false;
case fcChangePassword:
return FSecureShell->CanChangePassword();
default:
DebugFail();
return false;
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::DelimitStr(UnicodeString Str)
{
if (!Str.IsEmpty())
{
Str = ::DelimitStr(Str, L"\\`$\"");
if (Str[1] == L'-') Str = L"./"+Str;
}
return Str;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::EnsureLocation()
{
if (!FCachedDirectoryChange.IsEmpty())
{
FTerminal->LogEvent(FORMAT(L"Locating to cached directory \"%s\".",
(FCachedDirectoryChange)));
UnicodeString Directory = FCachedDirectoryChange;
FCachedDirectoryChange = L"";
try
{
ChangeDirectory(Directory);
}
catch(...)
{
// when location to cached directory fails, pretend again
// location in cached directory
// here used to be check (CurrentDirectory != Directory), but it is
// false always (current directory is already set to cached directory),
// making the condition below useless. check removed.
if (FTerminal->Active)
{
FCachedDirectoryChange = Directory;
}
throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SendCommand(const UnicodeString Cmd)
{
EnsureLocation();
UnicodeString Line;
FSecureShell->ClearStdError();
FReturnCode = 0;
FOutput->Clear();
// We suppose, that 'Cmd' already contains command that ensures,
// that 'LastLine' will be printed
FSecureShell->SendLine(Cmd);
FProcessingCommand = true;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::IsTotalListingLine(const UnicodeString Line)
{
// On some hosts there is not "total" but "totalt". What's the reason??
// see mail from "Jan Wiklund (SysOp)" <jan@park.se>
return !Line.SubString(1, 5).CompareIC(L"total");
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::RemoveLastLine(UnicodeString & Line,
int & ReturnCode, UnicodeString LastLine)
{
bool IsLastLine = false;
if (LastLine.IsEmpty()) LastLine = LAST_LINE;
// #55: fixed so, even when last line of command output does not
// contain CR/LF, we can recognize last line
int Pos = Line.Pos(LastLine);
if (Pos)
{
// 2003-07-14: There must be nothing after return code number to
// consider string as last line. This fixes bug with 'set' command
// in console window
UnicodeString ReturnCodeStr = Line.SubString(Pos + LastLine.Length() + 1,
Line.Length() - Pos + LastLine.Length());
if (TryStrToInt(ReturnCodeStr, ReturnCode))
{
IsLastLine = true;
Line.SetLength(Pos - 1);
}
}
return IsLastLine;
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::IsLastLine(UnicodeString & Line)
{
bool Result = false;
try
{
Result = RemoveLastLine(Line, FReturnCode, FCommandSet->LastLine);
}
catch (Exception &E)
{
FTerminal->TerminalError(&E, LoadStr(CANT_DETECT_RETURN_CODE));
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SkipFirstLine()
{
UnicodeString Line = FSecureShell->ReceiveLine();
if (Line != FCommandSet->FirstLine)
{
FTerminal->TerminalError(NULL, FMTLOAD(FIRST_LINE_EXPECTED, (Line)));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadCommandOutput(int Params, const UnicodeString * Cmd)
{
try
{
if (Params & coWaitForLastLine)
{
UnicodeString Line;
bool IsLast;
unsigned int Total = 0;
// #55: fixed so, even when last line of command output does not
// contain CR/LF, we can recognize last line
do
{
Line = FSecureShell->ReceiveLine();
IsLast = IsLastLine(Line);
if (!IsLast || !Line.IsEmpty())
{
FOutput->Add(Line);
if (FLAGSET(Params, coReadProgress))
{
Total++;
if (Total % 10 == 0)
{
bool Cancel; //dummy
FTerminal->DoReadDirectoryProgress(Total, 0, Cancel);
}
}
}
}
while (!IsLast);
}
if (Params & coRaiseExcept)
{
UnicodeString Message = FSecureShell->GetStdError();
if ((Params & coExpectNoOutput) && FOutput->Count)
{
if (!Message.IsEmpty()) Message += L"\n";
Message += FOutput->Text;
}
while (!Message.IsEmpty() && (Message.LastDelimiter(L"\n\r") == Message.Length()))
{
Message.SetLength(Message.Length() - 1);
}
bool WrongReturnCode =
(ReturnCode > 1) || (ReturnCode == 1 && !(Params & coIgnoreWarnings));
if (FOnCaptureOutput != NULL)
{
FOnCaptureOutput(IntToStr(ReturnCode), cotExitCode);
}
if (Params & coOnlyReturnCode && WrongReturnCode)
{
FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
}
else if (!(Params & coOnlyReturnCode) &&
((!Message.IsEmpty() && ((FOutput->Count == 0) || !(Params & coIgnoreWarnings))) ||
WrongReturnCode))
{
DebugAssert(Cmd != NULL);
FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED, (*Cmd, ReturnCode, Message)));
}
}
}
__finally
{
FProcessingCommand = false;
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ExecCommand(const UnicodeString & Cmd, int Params,
const UnicodeString & CmdString)
{
if (Params < 0)
{
Params = ecDefault;
}
TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
SendCommand(Cmd);
int COParams = coWaitForLastLine;
if (Params & ecRaiseExcept) COParams |= coRaiseExcept;
if (Params & ecIgnoreWarnings) COParams |= coIgnoreWarnings;
if (Params & ecReadProgress) COParams |= coReadProgress;
ReadCommandOutput(COParams, &CmdString);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
int size, int Params)
{
if (Params < 0) Params = ecDefault;
UnicodeString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
UnicodeString Command = FCommandSet->Command(Cmd, args, size);
ExecCommand(FullCommand, Params, Command);
if (Params & ecRaiseExcept)
{
Integer MinL = FCommandSet->MinLines[Cmd];
Integer MaxL = FCommandSet->MaxLines[Cmd];
if (((MinL >= 0) && (MinL > FOutput->Count)) ||
((MaxL >= 0) && (MaxL > FOutput->Count)))
{
FTerminal->TerminalError(FmtLoadStr(INVALID_OUTPUT_ERROR,
ARRAYOFCONST((FullCommand, Output->Text))));
}
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TSCPFileSystem::GetCurrentDirectory()
{
return FCurrentDirectory;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DoStartup()
{
// Capabilities of SCP protocol are fixed
FTerminal->SaveCapabilities(FFileSystemInfo);
// SkipStartupMessage and DetectReturnVar must succeed,
// otherwise session is to be closed.
try
{
FTerminal->ExceptionOnFail = true;
SkipStartupMessage();
if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
FTerminal->ExceptionOnFail = false;
}
catch (Exception & E)
{
FTerminal->FatalError(&E, L"");
}
// Needs to be done before UnsetNationalVars()
DetectUtf();
#define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
COND_OPER(ClearAliases);
COND_OPER(UnsetNationalVars);
#undef COND_OPER
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DetectUtf()
{
switch (FTerminal->SessionData->NotUtf)
{
case asOn:
FSecureShell->UtfStrings = false; // noop
break;
case asOff:
FSecureShell->UtfStrings = true;
break;
default:
DebugFail();
case asAuto:
FSecureShell->UtfStrings = false; // noop
try
{
ExecCommand(fsLang, NULL, 0, false);
if ((FOutput->Count >= 1) &&
ContainsText(FOutput->Strings[0], L"UTF-8"))
{
FSecureShell->UtfStrings = true;
}
}
catch (Exception & E)
{
// ignore non-fatal errors
if (!FTerminal->Active)
{
throw;
}
}
break;
}
if (FSecureShell->UtfStrings)
{
FTerminal->LogEvent(L"We will use UTF-8");
}
else
{
FTerminal->LogEvent(L"We will not use UTF-8");
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SkipStartupMessage()
{
try
{
FTerminal->LogEvent(L"Skipping host startup message (if any).");
ExecCommand(fsNull, NULL, 0, 0);
}
catch (Exception & E)
{
FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR), 0, HELP_SKIP_STARTUP_MESSAGE_ERROR);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::LookupUsersGroups()
{
ExecCommand(fsLookupUsersGroups);
FTerminal->FUsers.Clear();
FTerminal->FGroups.Clear();
if (FOutput->Count > 0)
{
UnicodeString Groups = FOutput->Strings[0];
while (!Groups.IsEmpty())
{
UnicodeString NewGroup = CutToChar(Groups, L' ', false);
FTerminal->FGroups.Add(TRemoteToken(NewGroup));
FTerminal->FMembership.Add(TRemoteToken(NewGroup));
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DetectReturnVar()
{
// This suppose that something was already executed (probably SkipStartupMessage())
// or return code variable is already set on start up.
try
{
// #60 17.10.01: "status" and "?" switched
UnicodeString ReturnVars[2] = { L"status", L"?" };
UnicodeString NewReturnVar = L"";
FTerminal->LogEvent(L"Detecting variable containing return code of last command.");
for (int Index = 0; Index < 2; Index++)
{
bool Success = true;
try
{
FTerminal->LogEvent(FORMAT(L"Trying \"$%s\".", (ReturnVars[Index])));
ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255))
{
FTerminal->LogEvent(L"The response is not numerical exit code");
Abort();
}
}
catch (EFatal &E)
{
// if fatal error occurs, we need to exit ...
throw;
}
catch (Exception &E)
{
// ...otherwise, we will try next variable (if any)
Success = false;
}
if (Success)
{
NewReturnVar = ReturnVars[Index];
break;
}
}
if (NewReturnVar.IsEmpty())
{
EXCEPTION;
}
else
{
FCommandSet->ReturnVar = NewReturnVar;
FTerminal->LogEvent(FORMAT(L"Return code variable \"%s\" selected.",
(FCommandSet->ReturnVar)));
}
}
catch (Exception &E)
{
FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ClearAlias(UnicodeString Alias)
{
if (!Alias.IsEmpty())
{
// this command usually fails, because there will never be
// aliases on all commands -> see last False parameter
ExecCommand(fsUnalias, ARRAYOFCONST((Alias)), false);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ClearAliases()
{
try
{
FTerminal->LogEvent(L"Clearing all aliases.");
ClearAlias(TCommandSet::ExtractCommand(FTerminal->SessionData->ListingCommand));
TStrings * CommandList = FCommandSet->CreateCommandList();
try
{
for (int Index = 0; Index < CommandList->Count; Index++)
{
ClearAlias(CommandList->Strings[Index]);
}
}
__finally
{
delete CommandList;
}
}
catch (Exception &E)
{
FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::UnsetNationalVars()
{
try
{
FTerminal->LogEvent(L"Clearing national user variables.");
for (int Index = 0; Index < NationalVarCount; Index++)
{
ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
}
}
catch (Exception &E)
{
FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadCurrentDirectory()
{
if (FCachedDirectoryChange.IsEmpty())
{
ExecCommand(fsCurrentDirectory);
FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
}
else
{
FCurrentDirectory = FCachedDirectoryChange;
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::HomeDirectory()
{
ExecCommand(fsHomeDirectory);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::AnnounceFileListOperation()
{
// noop
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ChangeDirectory(const UnicodeString Directory)
{
UnicodeString ToDir;
if (!Directory.IsEmpty() &&
((Directory[1] != L'~') || (Directory.SubString(1, 2) == L"~ ")))
{
ToDir = L"\"" + DelimitStr(Directory) + L"\"";
}
else
{
ToDir = DelimitStr(Directory);
}
ExecCommand(fsChangeDirectory, ARRAYOFCONST((ToDir)));
FCachedDirectoryChange = L"";
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
{
FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
{
DebugAssert(FileList);
// emptying file list moved before command execution
FileList->Reset();
bool Again;
do
{
Again = false;
try
{
int Params = ecDefault | ecReadProgress |
FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
const wchar_t * Options =
((FLsFullTime == asAuto) || (FLsFullTime == asOn)) ? FullTimeOption : L"";
bool ListCurrentDirectory = (FileList->Directory == FTerminal->CurrentDirectory);
if (ListCurrentDirectory)
{
FTerminal->LogEvent(L"Listing current directory.");
ExecCommand(fsListCurrentDirectory,
ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options)), Params);
}
else
{
FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".",
(FileList->Directory)));
ExecCommand(fsListDirectory,
ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options,
DelimitStr(FileList->Directory))),
Params);
}
TRemoteFile * File;
// If output is not empty, we have successfully got file listing,
// otherwise there was an error, in case it was "permission denied"
// we try to get at least parent directory (see "else" statement below)
if (FOutput->Count > 0)
{
// Copy LS command output, because eventual symlink analysis would
// modify FTerminal->Output
TStringList * OutputCopy = new TStringList();
try
{
OutputCopy->Assign(FOutput);
// delete leading "total xxx" line
// On some hosts there is not "total" but "totalt". What's the reason??
// see mail from "Jan Wiklund (SysOp)" <jan@park.se>
if (IsTotalListingLine(OutputCopy->Strings[0]))
{
OutputCopy->Delete(0);
}
for (int Index = 0; Index < OutputCopy->Count; Index++)
{
UnicodeString OutputLine = OutputCopy->Strings[Index];
if (!OutputLine.IsEmpty())
{
File = CreateRemoteFile(OutputCopy->Strings[Index]);
FileList->AddFile(File);
}
}
}
__finally
{
delete OutputCopy;
}
}
else
{
bool Empty;
if (ListCurrentDirectory)
{
// Empty file list -> probably "permission denied", we
// at least get link to parent directory ("..")
FTerminal->ReadFile(
UnixIncludeTrailingBackslash(FTerminal->FFiles->Directory) +
PARENTDIRECTORY, File);
Empty = (File == NULL);
if (!Empty)
{
DebugAssert(File->IsParentDirectory);
FileList->AddFile(File);
}
}
else
{
Empty = true;
}
if (Empty)
{
throw ExtException(
NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
HELP_EMPTY_DIRECTORY);
}
}
if (FLsFullTime == asAuto)
{
FTerminal->LogEvent(
FORMAT(L"Directory listing with %s succeed, next time all errors during "
"directory listing will be displayed immediately.",
(FullTimeOption)));
FLsFullTime = asOn;
}
}
catch(Exception & E)
{
if (FTerminal->Active)
{
if (FLsFullTime == asAuto)
{
FTerminal->Log->AddException(&E);
FLsFullTime = asOff;
Again = true;
FTerminal->LogEvent(
FORMAT(L"Directory listing with %s failed, try again regular listing.",
(FullTimeOption)));
}
else
{
throw;
}
}
else
{
throw;
}
}
}
while (Again);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
TRemoteFile *& File)
{
CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ReadFile(const UnicodeString FileName,
TRemoteFile *& File)
{
CustomReadFile(FileName, File, NULL);
}
//---------------------------------------------------------------------------
TRemoteFile * __fastcall TSCPFileSystem::CreateRemoteFile(
const UnicodeString & ListingStr, TRemoteFile * LinkedByFile)
{
TRemoteFile * File = new TRemoteFile(LinkedByFile);
try
{
File->Terminal = FTerminal;
File->ListingStr = ListingStr;
File->ShiftTimeInSeconds(TimeToSeconds(FTerminal->SessionData->TimeDifference));
File->Complete();
}
catch(...)
{
delete File;
throw;
}
return File;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CustomReadFile(const UnicodeString FileName,
TRemoteFile *& File, TRemoteFile * ALinkedByFile)
{
File = NULL;
int Params = ecDefault |
FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
// the auto-detection of --full-time support is not implemented for fsListFile,
// so we use it only if we already know that it is supported (asOn).
const wchar_t * Options = (FLsFullTime == asOn) ? FullTimeOption : L"";
ExecCommand(fsListFile,
ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options, DelimitStr(FileName))),
Params);
if (FOutput->Count)
{
int LineIndex = 0;
if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
{
LineIndex++;
}
File = CreateRemoteFile(FOutput->Strings[LineIndex], ALinkedByFile);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::DeleteFile(const UnicodeString FileName,
const TRemoteFile * File, int Params, TRmSessionAction & Action)
{
DebugUsedParam(File);
DebugUsedParam(Params);
Action.Recursive();
DebugAssert(FLAGCLEAR(Params, dfNoRecursive) || (File && File->IsSymLink));
ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
const UnicodeString NewName)
{
ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
const UnicodeString NewName)
{
UnicodeString DelimitedFileName = DelimitStr(FileName);
UnicodeString DelimitedNewName = DelimitStr(NewName);
const UnicodeString AdditionalSwitches = L"-T";
try
{
ExecCommand(fsCopyFile, ARRAYOFCONST((AdditionalSwitches, DelimitedFileName, DelimitedNewName)));
}
catch (Exception & E)
{
if (FTerminal->Active)
{
// The -T is GNU switch and may not be available on all platforms.
// https://lists.gnu.org/archive/html/bug-coreutils/2004-07/msg00000.html
FTerminal->LogEvent(FORMAT(L"Attempt with %s failed, trying without", (AdditionalSwitches)));
ExecCommand(fsCopyFile, ARRAYOFCONST((L"", DelimitedFileName, DelimitedNewName)));
}
else
{
throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
{
ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CreateLink(const UnicodeString FileName,
const UnicodeString PointTo, bool Symbolic)
{
ExecCommand(fsCreateLink,
ARRAYOFCONST((Symbolic ? L"-s" : L"", DelimitStr(PointTo), DelimitStr(FileName))));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ChangeFileToken(const UnicodeString & DelimitedName,
const TRemoteToken & Token, TFSCommand Cmd, const UnicodeString & RecursiveStr)
{
UnicodeString Str;
if (Token.IDValid)
{
Str = IntToStr(int(Token.ID));
}
else if (Token.NameValid)
{
Str = Token.Name;
}
if (!Str.IsEmpty())
{
ExecCommand(Cmd, ARRAYOFCONST((RecursiveStr, Str, DelimitedName)));
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ChangeFileProperties(const UnicodeString FileName,
const TRemoteFile * File, const TRemoteProperties * Properties,
TChmodSessionAction & Action)
{
DebugAssert(Properties);
bool IsDirectory = File && File->IsDirectory;
bool Recursive = Properties->Recursive && IsDirectory;
UnicodeString RecursiveStr = Recursive ? L"-R" : L"";
UnicodeString DelimitedName = DelimitStr(FileName);
// change group before permissions as chgrp change permissions
if (Properties->Valid.Contains(vpGroup))
{
ChangeFileToken(DelimitedName, Properties->Group, fsChangeGroup, RecursiveStr);
}
if (Properties->Valid.Contains(vpOwner))
{
ChangeFileToken(DelimitedName, Properties->Owner, fsChangeOwner, RecursiveStr);
}
if (Properties->Valid.Contains(vpRights))
{
TRights Rights = Properties->Rights;
// if we don't set modes recursively, we may add X at once with other
// options. Otherwise we have to add X after recursive command
if (!Recursive && IsDirectory && Properties->AddXToDirectories)
Rights.AddExecute();
Action.Rights(Rights);
if (Recursive)
{
Action.Recursive();
}
if ((Rights.NumberSet | Rights.NumberUnset) != TRights::rfNo)
{
ExecCommand(fsChangeMode,
ARRAYOFCONST((RecursiveStr, Rights.SimplestStr, DelimitedName)));
}
// if file is directory and we do recursive mode settings with
// add-x-to-directories option on, add those X
if (Recursive && IsDirectory && Properties->AddXToDirectories)
{
Rights.AddExecute();
ExecCommand(fsChangeMode,
ARRAYOFCONST((L"", Rights.SimplestStr, DelimitedName)));
}
}
else
{
Action.Cancel();
}
DebugAssert(!Properties->Valid.Contains(vpLastAccess));
DebugAssert(!Properties->Valid.Contains(vpModification));
}
//---------------------------------------------------------------------------
bool __fastcall TSCPFileSystem::LoadFilesProperties(TStrings * /*FileList*/ )
{
DebugFail();
return false;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
TStrings * /*FileList*/, TStrings * /*Checksums*/,
TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CustomCommandOnFile(const UnicodeString FileName,
const TRemoteFile * File, UnicodeString Command, int Params,
TCaptureOutputEvent OutputEvent)
{
DebugAssert(File);
bool Dir = File->IsDirectory && FTerminal->CanRecurseToDirectory(File);
if (Dir && (Params & ccRecursive))
{
TCustomCommandParams AParams;
AParams.Command = Command;
AParams.Params = Params;
AParams.OutputEvent = OutputEvent;
FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
&AParams);
}
if (!Dir || (Params & ccApplyToDirectories))
{
TCustomCommandData Data(FTerminal);
UnicodeString Cmd = TRemoteCustomCommand(
Data, FTerminal->CurrentDirectory, FileName, L"").
Complete(Command, true);
if (!FTerminal->DoOnCustomCommand(Cmd))
{
AnyCommand(Cmd, OutputEvent);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CaptureOutput(const UnicodeString & AddedLine, TCaptureOutputType OutputType)
{
int ReturnCode;
UnicodeString Line = AddedLine;
// TSecureShell never uses cotExitCode
DebugAssert((OutputType == cotOutput) || (OutputType == cotError));
if ((OutputType == cotError) || DebugAlwaysFalse(OutputType == cotExitCode) ||
!RemoveLastLine(Line, ReturnCode) ||
!Line.IsEmpty())
{
DebugAssert(FOnCaptureOutput != NULL);
FOnCaptureOutput(Line, OutputType);
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::AnyCommand(const UnicodeString Command,
TCaptureOutputEvent OutputEvent)
{
DebugAssert(FSecureShell->OnCaptureOutput == NULL);
if (OutputEvent != NULL)
{
FSecureShell->OnCaptureOutput = CaptureOutput;
FOnCaptureOutput = OutputEvent;
}
try
{
ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)),
ecDefault | ecIgnoreWarnings);
}
__finally
{
FOnCaptureOutput = NULL;
FSecureShell->OnCaptureOutput = NULL;
}
}
//---------------------------------------------------------------------------
TStrings * __fastcall TSCPFileSystem::GetFixedPaths()
{
return NULL;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SpaceAvailable(const UnicodeString Path,
TSpaceAvailable & /*ASpaceAvailable*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
// transfer protocol
//---------------------------------------------------------------------------
unsigned int __fastcall TSCPFileSystem::ConfirmOverwrite(
const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName, TOperationSide Side,
const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
int Params, TFileOperationProgressType * OperationProgress)
{
TSuspendFileOperationProgress Suspend(OperationProgress);
TQueryButtonAlias Aliases[3];
Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
TQueryParams QueryParams(qpNeverAskAgainCheck);
QueryParams.Aliases = Aliases;
QueryParams.AliasesCount = LENOF(Aliases);
unsigned int Answer =
FTerminal->ConfirmFileOverwrite(
SourceFullFileName, TargetFileName, FileParams,
qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll,
&QueryParams, Side, CopyParam, Params, OperationProgress);
return Answer;
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
{
// Taken from scp.c response() and modified
unsigned char Resp;
FSecureShell->Receive(&Resp, 1);
switch (Resp)
{
case 0: /* ok */
FTerminal->LogEvent(L"SCP remote side confirmation (0)");
return;
default:
case 1: /* error */
case 2: /* fatal error */
// pscp adds 'Resp' to 'Msg', why?
UnicodeString Msg = FSecureShell->ReceiveLine();
UnicodeString Line = UnicodeString(static_cast<char>(Resp)) + Msg;
if (IsLastLine(Line))
{
if (GotLastLine != NULL)
{
*GotLastLine = true;
}
/* TODO 1 : Show stderror to user? */
FSecureShell->ClearStdError();
try
{
ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
}
catch(...)
{
// when ReadCommandOutput() fails than remote SCP is terminated already
if (GotLastLine != NULL)
{
*GotLastLine = true;
}
throw;
}
}
else if (Resp == 1)
{
// While the OpenSSH scp client distinguishes the 1 for error and 2 for fatal errors,
// the OpenSSH scp server always sends 1 even for fatal errors. Using the error message to tell
// which errors are fatal and which are not.
// This error list is valid for OpenSSH 5.3p1 and 7.2p2
if (SameText(Msg, L"scp: ambiguous target") ||
StartsText(L"scp: error: unexpected filename: ", Msg) ||
StartsText(L"scp: protocol error: ", Msg))
{
FTerminal->LogEvent(L"SCP remote side error (1), fatal error detected from error message");
Resp = 2;
FScpFatalError = true;
}
else
{
FTerminal->LogEvent(L"SCP remote side error (1)");
}
}
else
{
FTerminal->LogEvent(L"SCP remote side fatal error (2)");
FScpFatalError = true;
}
if (Resp == 1)
{
throw EScpFileSkipped(NULL, Msg);
}
else
{
throw EScp(NULL, Msg);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
const UnicodeString TargetDir, const TCopyParamType * CopyParam,
int Params, TFileOperationProgressType * OperationProgress,
TOnceDoneOperation & OnceDoneOperation)
{
// scp.c: source(), toremote()
DebugAssert(FilesToCopy && OperationProgress);
Params &= ~(cpAppend | cpResume);
UnicodeString Options = L"";
bool CheckExistence = UnixSamePath(TargetDir, FTerminal->CurrentDirectory) &&
(FTerminal->FFiles != NULL) && FTerminal->FFiles->Loaded;
bool CopyBatchStarted = false;
bool Failed = true;
bool GotLastLine = false;
UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir);
if (CopyParam->PreserveRights) Options = L"-p";
if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
FScpFatalError = false;
SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
SkipFirstLine();
try
{
try
{
SCPResponse(&GotLastLine);
// This can happen only if SCP command is not executed and return code is 0
// It has never happened to me (return code is usually 127)
if (GotLastLine)
{
throw Exception(L"");
}
}
catch(Exception & E)
{
if (GotLastLine && FTerminal->Active)
{
FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
}
else
{
throw;
}
}
CopyBatchStarted = true;
for (int IFile = 0; (IFile < FilesToCopy->Count) &&
!OperationProgress->Cancel; IFile++)
{
UnicodeString FileName = FilesToCopy->Strings[IFile];
bool CanProceed;
UnicodeString FileNameOnly =
FTerminal->ChangeFileName(
CopyParam, ExtractFileName(FileName), osLocal, true);
if (CheckExistence)
{
// previously there was assertion on FTerminal->FFiles->Loaded, but it
// fails for scripting, if 'ls' is not issued before.
// formally we should call CheckRemoteFile here but as checking is for
// free here (almost) ...
TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
if (File != NULL)
{
unsigned int Answer;
if (File->IsDirectory)
{
UnicodeString Message = FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly));
TQueryParams QueryParams(qpNeverAskAgainCheck);
TSuspendFileOperationProgress Suspend(OperationProgress);
Answer = FTerminal->ConfirmFileOverwrite(
FileName, FileNameOnly, NULL,
qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll,
&QueryParams, osRemote, CopyParam, Params, OperationProgress, Message);
}
else
{
__int64 MTime;
TOverwriteFileParams FileParams;
FTerminal->OpenLocalFile(FileName, GENERIC_READ,
NULL, NULL, NULL, &MTime, NULL,
&FileParams.SourceSize);
FileParams.SourceTimestamp = UnixToDateTime(MTime,
FTerminal->SessionData->DSTMode);
FileParams.DestSize = File->Size;
FileParams.DestTimestamp = File->Modification;
Answer = ConfirmOverwrite(FileName, FileNameOnly, osRemote,
&FileParams, CopyParam, Params, OperationProgress);
}
switch (Answer)
{
case qaYes:
CanProceed = true;
break;
case qaCancel:
OperationProgress->SetCancelAtLeast(csCancel);
case qaNo:
CanProceed = false;
break;
default:
DebugFail();
break;
}
}
else
{
CanProceed = true;
}
}
else
{
CanProceed = true;
}
if (CanProceed)
{
if (FTerminal->SessionData->CacheDirectories)
{
FTerminal->DirectoryModified(TargetDir, false);
if (DirectoryExists(ApiPath(FileName)))
{
FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
FileNameOnly, true);
}
}
void * Item = static_cast<void *>(FilesToCopy->Objects[IFile]);
try
{
SCPSource(FileName, TargetDirFull,
CopyParam, Params, OperationProgress, 0);
FTerminal->OperationFinish(OperationProgress, Item, FileName, true, OnceDoneOperation);
}
catch (EScpFileSkipped &E)
{
TQueryParams Params(qpAllowContinueOnError);
TSuspendFileOperationProgress Suspend(OperationProgress);
if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
qaOK | qaAbort, &Params, qtError) == qaAbort)
{
OperationProgress->SetCancel(csCancel);
}
FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
if (!FTerminal->HandleException(&E))
{
throw;
}
}
catch (ESkipFile &E)
{
FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
{
TSuspendFileOperationProgress Suspend(OperationProgress);
// If ESkipFile occurs, just log it and continue with next file
if (!FTerminal->HandleException(&E))
{
throw;
}
}
}
catch (...)
{
FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
throw;
}
}
}
Failed = false;
}
__finally
{
// Tell remote side, that we're done.
if (FTerminal->Active)
{
try
{
if (!GotLastLine)
{
if (CopyBatchStarted && !FScpFatalError)
{
// What about case, remote side sends fatal error ???
// (Not sure, if it causes remote side to terminate scp)
FSecureShell->SendLine(L"E");
SCPResponse();
}
/* TODO 1 : Show stderror to user? */
FSecureShell->ClearStdError();
ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
(Failed ? 0 : coRaiseExcept));
}
}
catch (Exception &E)
{
// Only log error message (it should always succeed, but
// some pending error maybe in queue) }
FTerminal->Log->AddException(&E);
}
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Source(
TLocalFileHandle & /*Handle*/, const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/,
const TCopyParamType * /*CopyParam*/, int /*Params*/,
TFileOperationProgressType * /*OperationProgress*/, unsigned int /*Flags*/,
TUploadSessionAction & /*Action*/, bool & /*ChildError*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName,
const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
TFileOperationProgressType * OperationProgress, int Level)
{
UnicodeString DestFileName =
FTerminal->ChangeFileName(
CopyParam, ExtractFileName(FileName), osLocal, Level == 0);
FTerminal->LogEvent(FORMAT(L"File: \"%s\"", (FileName)));
OperationProgress->SetFile(FileName, false);
if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
{
throw ESkipFile();
}
TLocalFileHandle Handle;
FTerminal->OpenLocalFile(FileName, GENERIC_READ, Handle);
OperationProgress->SetFileInProgress();
if (Handle.Directory)
{
SCPDirectorySource(FileName, TargetDir, CopyParam, Params, OperationProgress, Level);
}
else
{
UnicodeString AbsoluteFileName = FTerminal->AbsolutePath(TargetDir + DestFileName, false);
DebugAssert(Handle.Handle);
std::unique_ptr<TStream> Stream(new TSafeHandleStream((THandle)Handle.Handle));
// File is regular file (not directory)
FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
OperationProgress->SetLocalSize(Handle.Size);
// Suppose same data size to transfer as to read
// (not true with ASCII transfer)
OperationProgress->SetTransferSize(OperationProgress->LocalSize);
OperationProgress->SetTransferringFile(false);
FTerminal->SelectSourceTransferMode(Handle, CopyParam);
TUploadSessionAction Action(FTerminal->ActionLog);
Action.FileName(ExpandUNCFileName(FileName));
Action.Destination(AbsoluteFileName);
TRights Rights = CopyParam->RemoteFileRights(Handle.Attrs);
try
{
// During ASCII transfer we will load whole file to this buffer
// than convert EOL and send it at once, because before converting EOL
// we can't know its size
TFileBuffer AsciiBuf;
bool ConvertToken = false;
do
{
// Buffer for one block of data
TFileBuffer BlockBuf;
// This is crucial, if it fails during file transfer, it's fatal error
FILE_OPERATION_LOOP_BEGIN
{
BlockBuf.LoadStream(Stream.get(), OperationProgress->LocalBlockSize(), true);
}
FILE_OPERATION_LOOP_END_EX(
FMTLOAD(READ_ERROR, (FileName)),
FLAGMASK(!OperationProgress->TransferringFile, folAllowSkip));
OperationProgress->AddLocallyUsed(BlockBuf.Size);
// We do ASCII transfer: convert EOL of current block
// (we don't convert whole buffer, cause it would produce
// huge memory-transfers while inserting/deleting EOL characters)
// Than we add current block to file buffer
if (OperationProgress->AsciiTransfer)
{
int ConvertParams =
FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
FTerminal->SessionData->EOLType,
ConvertParams, ConvertToken);
BlockBuf.Memory->Seek(0, soFromBeginning);
AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
// We don't need it any more
BlockBuf.Memory->Clear();
// Calculate total size to sent (assume that ratio between
// size of source and size of EOL-transformed data would remain same)
// First check if file contains anything (div by zero!)
if (OperationProgress->LocallyUsed)
{
__int64 X = OperationProgress->LocalSize;
X *= AsciiBuf.Size;
X /= OperationProgress->LocallyUsed;
OperationProgress->ChangeTransferSize(X);
}
else
{
OperationProgress->ChangeTransferSize(0);
}
}
// We send file information on first pass during BINARY transfer
// and on last pass during ASCII transfer
// BINARY: We succeeded reading first buffer from file, hopefully
// we will be able to read whole, so we send file info to remote side
// This is done, because when reading fails we can't interrupt sending
// (don't know how to tell other side that it failed)
if (!OperationProgress->TransferringFile &&
(!OperationProgress->AsciiTransfer || OperationProgress->IsLocallyDone()))
{
UnicodeString Buf;
if (CopyParam->PreserveTime)
{
// Send last file access and modification time
// TVarRec don't understand 'unsigned int' -> we use sprintf()
Buf.sprintf(L"T%lu 0 %lu 0", static_cast<unsigned long>(Handle.MTime),
static_cast<unsigned long>(Handle.ATime));
FSecureShell->SendLine(Buf);
SCPResponse();
}
// Send file modes (rights), filesize and file name
// TVarRec don't understand 'unsigned int' -> we use sprintf()
Buf.sprintf(L"C%s %Ld %s",
Rights.Octal.data(),
(OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
OperationProgress->LocalSize),
DestFileName.data());
FSecureShell->SendLine(Buf);
SCPResponse();
// Indicate we started transferring file, we need to finish it
// If not, it's fatal error
OperationProgress->SetTransferringFile(true);
// If we're doing ASCII transfer, this is last pass
// so we send whole file
/* TODO : We can't send file above 32bit size in ASCII mode! */
if (OperationProgress->AsciiTransfer)
{
FTerminal->LogEvent(FORMAT(L"Sending ASCII data (%u bytes)",
(AsciiBuf.Size)));
// Should be equal, just in case it's rounded (see above)
OperationProgress->ChangeTransferSize(AsciiBuf.Size);
while (!OperationProgress->IsTransferDone())
{
unsigned long BlockSize = OperationProgress->TransferBlockSize();
FSecureShell->Send(
reinterpret_cast<unsigned char *>(AsciiBuf.Data + (unsigned int)OperationProgress->TransferredSize),
BlockSize);
OperationProgress->AddTransferred(BlockSize);
if (OperationProgress->Cancel == csCancelTransfer)
{
throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
}
}
}
}
// At end of BINARY transfer pass, send current block
if (!OperationProgress->AsciiTransfer)
{
if (!OperationProgress->TransferredSize)
{
FTerminal->LogEvent(FORMAT(L"Sending BINARY data (first block, %u bytes)",
(BlockBuf.Size)));
}
else if (FTerminal->Configuration->ActualLogProtocol >= 1)
{
FTerminal->LogEvent(FORMAT(L"Sending BINARY data (%u bytes)",
(BlockBuf.Size)));
}
FSecureShell->Send(reinterpret_cast<const unsigned char *>(BlockBuf.Data), BlockBuf.Size);
OperationProgress->AddTransferred(BlockBuf.Size);
}
if ((OperationProgress->Cancel == csCancelTransfer) ||
(OperationProgress->Cancel == csCancel && !OperationProgress->TransferringFile))
{
throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
}
}
while (!OperationProgress->IsLocallyDone() || !OperationProgress->IsTransferDone());
FSecureShell->SendNull();
try
{
SCPResponse();
// If one of two following exceptions occurs, it means, that remote
// side already know, that file transfer finished, even if it failed
// so we don't have to throw EFatal
}
catch (EScp &E)
{
// SCP protocol fatal error
OperationProgress->SetTransferringFile(false);
throw;
}
catch (EScpFileSkipped &E)
{
// SCP protocol non-fatal error
OperationProgress->SetTransferringFile(false);
throw;
}
// We succeeded transferring file, from now we can handle exceptions
// normally -> no fatal error
OperationProgress->SetTransferringFile(false);
}
catch (Exception &E)
{
// EScpFileSkipped is derived from ESkipFile,
// but is does not indicate file skipped by user here
if (dynamic_cast<EScpFileSkipped *>(&E) != NULL)
{
Action.Rollback(&E);
}
else
{
FTerminal->RollbackAction(Action, OperationProgress, &E);
}
// Every exception during file transfer is fatal
if (OperationProgress->TransferringFile)
{
FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
}
else
{
throw;
}
}
// With SCP we are not able to distinguish reason for failure
// (upload itself, touch or chmod).
// So we always report error with upload action and
// log touch and chmod actions only if upload succeeds.
if (CopyParam->PreserveTime)
{
TTouchSessionAction(FTerminal->ActionLog, AbsoluteFileName, Handle.Modification);
}
if (CopyParam->PreserveRights)
{
TChmodSessionAction(FTerminal->ActionLog, AbsoluteFileName,
Rights);
}
FTerminal->LogFileDone(OperationProgress, AbsoluteFileName);
// Stream is disposed here
}
Handle.Release();
FTerminal->UpdateSource(Handle, CopyParam, Params);
FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory finished.", (FileName)));
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPDirectorySource(const UnicodeString DirectoryName,
const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
TFileOperationProgressType * OperationProgress, int Level)
{
int Attrs;
FTerminal->LogEvent(FORMAT(L"Entering directory \"%s\".", (DirectoryName)));
OperationProgress->SetFile(DirectoryName);
UnicodeString DestFileName =
FTerminal->ChangeFileName(
CopyParam, ExtractFileName(DirectoryName), osLocal, Level == 0);
// Get directory attributes
FILE_OPERATION_LOOP_BEGIN
{
Attrs = FileGetAttrFix(ApiPath(DirectoryName));
if (Attrs < 0) RaiseLastOSError();
}
FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (DirectoryName)));
UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir + DestFileName);
UnicodeString Buf;
/* TODO 1: maybe send filetime */
// Send directory modes (rights), filesize and file name
Buf = FORMAT(L"D%s 0 %s",
(CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
FSecureShell->SendLine(Buf);
SCPResponse();
try
{
TSearchRecOwned SearchRec;
bool FindOK = FTerminal->LocalFindFirstLoop(IncludeTrailingBackslash(DirectoryName) + L"*.*", SearchRec);
while (FindOK && !OperationProgress->Cancel)
{
UnicodeString FileName = IncludeTrailingBackslash(DirectoryName) + SearchRec.Name;
try
{
if (SearchRec.IsRealFile())
{
SCPSource(FileName, TargetDirFull, CopyParam, Params, OperationProgress, Level + 1);
}
}
// Previously we caught ESkipFile, making error being displayed
// even when file was excluded by mask. Now the ESkipFile is special
// case without error message.
catch (EScpFileSkipped &E)
{
TQueryParams Params(qpAllowContinueOnError);
TSuspendFileOperationProgress Suspend(OperationProgress);
if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
qaOK | qaAbort, &Params, qtError) == qaAbort)
{
OperationProgress->SetCancel(csCancel);
}
if (!FTerminal->HandleException(&E))
{
throw;
}
}
catch (ESkipFile &E)
{
// If ESkipFile occurs, just log it and continue with next file
TSuspendFileOperationProgress Suspend(OperationProgress);
if (!FTerminal->HandleException(&E))
{
throw;
}
}
FindOK = FTerminal->LocalFindNextLoop(SearchRec);
}
SearchRec.Close();
/* TODO : Delete also read-only directories. */
/* TODO : Show error message on failure. */
if (!OperationProgress->Cancel)
{
if (FLAGSET(Params, cpDelete))
{
RemoveDir(ApiPath(DirectoryName));
}
else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
{
FILE_OPERATION_LOOP_BEGIN
{
THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
}
FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
}
}
}
__finally
{
if (FTerminal->Active)
{
// Tell remote side, that we're done.
FTerminal->LogEvent(FORMAT(L"Leaving directory \"%s\".", (DirectoryName)));
FSecureShell->SendLine(L"E");
SCPResponse();
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
const UnicodeString TargetDir, const TCopyParamType * CopyParam,
int Params, TFileOperationProgressType * OperationProgress,
TOnceDoneOperation & OnceDoneOperation)
{
bool CloseSCP = False;
Params &= ~(cpAppend | cpResume);
UnicodeString Options = L"";
if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = L"-p";
if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
FTerminal->LogEvent(FORMAT(L"Copying %d files/directories to local directory "
"\"%s\"", (FilesToCopy->Count, TargetDir)));
if (FTerminal->Configuration->ActualLogProtocol >= 0)
{
FTerminal->LogEvent(CopyParam->LogStr);
}
try
{
for (int IFile = 0; (IFile < FilesToCopy->Count) &&
!OperationProgress->Cancel; IFile++)
{
UnicodeString FileName = FilesToCopy->Strings[IFile];
TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
DebugAssert(File);
try
{
bool Success = true; // Have to be set to True (see ::SCPSink)
SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
ARRAYOFCONST((Options, DelimitStr(FileName)))));
SkipFirstLine();
// Filename is used for error messaging and excluding files only
// Send in full path to allow path-based excluding
UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
SCPSink(TargetDir, FullFileName, UnixExtractFilePath(FullFileName),
CopyParam, Success, OperationProgress, Params, 0);
// operation succeeded (no exception), so it's ok that
// remote side closed SCP, but we continue with next file
if (OperationProgress->Cancel == csRemoteAbort)
{
OperationProgress->SetCancel(csContinue);
}
// Move operation -> delete file/directory afterwards
// but only if copying succeeded
if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
{
try
{
FTerminal->ExceptionOnFail = true;
try
{
FILE_OPERATION_LOOP_BEGIN
{
// pass full file name in FileName, in case we are not moving
// from current directory
FTerminal->DeleteFile(FileName, File);
}
FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
}
__finally
{
FTerminal->ExceptionOnFail = false;
}
}
catch (EFatal &E)
{
throw;
}
catch (...)
{
// If user selects skip (or abort), nothing special actually occurs
// we just run DoFinished with Success = False, so file won't
// be deselected in panel (depends on assigned event handler)
// On csCancel we would later try to close remote SCP, but it
// is closed already
if (OperationProgress->Cancel == csCancel)
{
OperationProgress->SetCancel(csRemoteAbort);
}
Success = false;
}
}
FTerminal->OperationFinish(
OperationProgress, File, FileName, (!OperationProgress->Cancel && Success), OnceDoneOperation);
}
catch (...)
{
FTerminal->OperationFinish(OperationProgress, File, FileName, false, OnceDoneOperation);
CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
throw;
}
}
}
__finally
{
// In case that copying doesn't cause fatal error (ie. connection is
// still active) but wasn't successful (exception or user termination)
// we need to ensure, that SCP on remote side is closed
if (FTerminal->Active && (CloseSCP ||
(OperationProgress->Cancel == csCancel) ||
(OperationProgress->Cancel == csCancelTransfer)))
{
bool LastLineRead;
// If we get LastLine, it means that remote side 'scp' is already
// terminated, so we need not to terminate it. There is also
// possibility that remote side waits for confirmation, so it will hang.
// This should not happen (hope)
UnicodeString Line = FSecureShell->ReceiveLine();
LastLineRead = IsLastLine(Line);
if (!LastLineRead)
{
SCPSendError((OperationProgress->Cancel ? L"Terminated by user." : L"Exception"), true);
}
// Just in case, remote side already sent some more data (it's probable)
// but we don't want to raise exception (user asked to terminate, it's not error)
int ECParams = coOnlyReturnCode;
if (!LastLineRead) ECParams |= coWaitForLastLine;
ReadCommandOutput(ECParams);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::Sink(
const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/,
const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/, int /*Attrs*/,
const TCopyParamType * /*CopyParam*/, int /*Params*/, TFileOperationProgressType * /*OperationProgress*/,
unsigned int /*Flags*/, TDownloadSessionAction & /*Action*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPError(const UnicodeString Message, bool Fatal)
{
SCPSendError(Message, Fatal);
throw EScpFileSkipped(NULL, Message);
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPSendError(const UnicodeString Message, bool Fatal)
{
unsigned char ErrorLevel = (char)(Fatal ? 2 : 1);
FTerminal->LogEvent(FORMAT(L"Sending SCP error (%d) to remote side:",
((int)ErrorLevel)));
FSecureShell->Send(&ErrorLevel, 1);
// We don't send exact error message, because some unspecified
// characters can terminate remote scp
FSecureShell->SendLine(L"scp: error");
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir,
const UnicodeString FileName, const UnicodeString SourceDir,
const TCopyParamType * CopyParam, bool & Success,
TFileOperationProgressType * OperationProgress, int Params,
int Level)
{
struct
{
int SetTime;
TDateTime Modification;
TRights RemoteRights;
int Attrs;
bool Exists;
} FileData;
bool SkipConfirmed = false;
bool Initialized = (Level > 0);
FileData.SetTime = 0;
FSecureShell->SendNull();
while (!OperationProgress->Cancel)
{
// See (switch ... case 'T':)
if (FileData.SetTime) FileData.SetTime--;
// In case of error occurred before control record arrived.
// We can finally use full path here, as we get current path in FileName param
// (we used to set the file into OperationProgress->FileName, but it collided
// with progress outputting, particularly for scripting)
UnicodeString FullFileName = FileName;
try
{
// Receive control record
UnicodeString Line = FSecureShell->ReceiveLine();
if (Line.Length() == 0) FTerminal->FatalError(NULL, LoadStr(SCP_EMPTY_LINE));
if (IsLastLine(Line))
{
// Remote side finished copying, so remote SCP was closed
// and we don't need to terminate it manually, see CopyToLocal()
OperationProgress->SetCancel(csRemoteAbort);
/* TODO 1 : Show stderror to user? */
FSecureShell->ClearStdError();
try
{
// coIgnoreWarnings should allow batch transfer to continue when
// download of one the files fails (user denies overwriting
// of target local file, no read permissions...)
ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
coOnlyReturnCode | coIgnoreWarnings);
if (!Initialized)
{
throw Exception(L"");
}
}
catch(Exception & E)
{
if (!Initialized && FTerminal->Active)
{
FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
}
else
{
throw;
}
}
return;
}
else
{
Initialized = true;
// First character distinguish type of control record
wchar_t Ctrl = Line[1];
Line.Delete(1, 1);
switch (Ctrl) {
case 1:
// Error (already logged by ReceiveLine())
throw EScpFileSkipped(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
case 2:
// Fatal error, terminate copying
FTerminal->TerminalError(Line);
return; // Unreachable
case L'E': // Exit
FSecureShell->SendNull();
return;
case L'T':
unsigned long MTime, ATime;
if (swscanf(Line.c_str(), L"%ld %*d %ld %*d", &MTime, &ATime) == 2)
{
FileData.Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
FSecureShell->SendNull();
// File time is only valid until next pass
FileData.SetTime = 2;
continue;
}
else
{
SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
}
case L'C':
case L'D':
break; // continue pass switch{}
default:
FTerminal->FatalError(NULL, FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
}
TFileMasks::TParams MaskParams;
MaskParams.Modification = FileData.Modification;
// We reach this point only if control record was 'C' or 'D'
try
{
FileData.RemoteRights.Octal = CutToChar(Line, L' ', True);
// do not trim leading spaces of the filename
__int64 TSize = StrToInt64(CutToChar(Line, L' ', False).TrimRight());
MaskParams.Size = TSize;
// Security fix: ensure the file ends up where we asked for it.
// (accept only filename, not path)
UnicodeString OnlyFileName = UnixExtractFileName(Line);
if (Line != OnlyFileName)
{
FTerminal->LogEvent(FORMAT(L"Warning: Remote host set a compound pathname '%s'", (Line)));
}
if ((Level == 0) && (OnlyFileName != UnixExtractFileName(FileName)))
{
SCPError(LoadStr(UNREQUESTED_FILE), False);
}
FullFileName = SourceDir + OnlyFileName;
OperationProgress->SetFile(FullFileName);
OperationProgress->SetTransferSize(TSize);
}
catch (Exception &E)
{
{
TSuspendFileOperationProgress Suspend(OperationProgress);
FTerminal->Log->AddException(&E);
}
SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
}
// last possibility to cancel transfer before it starts
if (OperationProgress->Cancel)
{
throw ESkipFile(NULL, MainInstructions(LoadStr(USER_TERMINATED)));
}
bool Dir = (Ctrl == L'D');
UnicodeString BaseFileName = FTerminal->GetBaseFileName(FullFileName);
if (!CopyParam->AllowTransfer(BaseFileName, osRemote, Dir, MaskParams, IsUnixHiddenFile(BaseFileName)))
{
FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer",
(FullFileName)));
SkipConfirmed = true;
SCPError(L"", false);
}
if (CopyParam->SkipTransfer(FullFileName, Dir))
{
SkipConfirmed = true;
SCPError(L"", false);
OperationProgress->AddSkippedFileSize(MaskParams.Size);
}
FTerminal->LogFileDetails(FileName, FileData.Modification, MaskParams.Size);
UnicodeString DestFileNameOnly =
FTerminal->ChangeFileName(
CopyParam, OperationProgress->FileName, osRemote,
Level == 0);
UnicodeString DestFileName =
IncludeTrailingBackslash(TargetDir) + DestFileNameOnly;
FileData.Attrs = FileGetAttrFix(ApiPath(DestFileName));
// If getting attrs fails, we suppose, that file/folder doesn't exists
FileData.Exists = (FileData.Attrs != -1);
if (Dir)
{
if (FileData.Exists && !(FileData.Attrs & faDirectory))
{
SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
}
if (!FileData.Exists)
{
FILE_OPERATION_LOOP_BEGIN
{
THROWOSIFFALSE(ForceDirectories(ApiPath(DestFileName)));
}
FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFileName)));
/* SCP: can we set the timestamp for directories ? */
}
UnicodeString FullFileName = SourceDir + OperationProgress->FileName;
SCPSink(DestFileName, FullFileName, UnixIncludeTrailingBackslash(FullFileName),
CopyParam, Success, OperationProgress, Params, Level + 1);
continue;
}
else if (Ctrl == L'C')
{
TDownloadSessionAction Action(FTerminal->ActionLog);
Action.FileName(FTerminal->AbsolutePath(FullFileName, true));
try
{
HANDLE File = NULL;
TStream * FileStream = NULL;
/* TODO 1 : Turn off read-only attr */
try
{
try
{
if (FileExists(ApiPath(DestFileName)))
{
__int64 MTime;
TOverwriteFileParams FileParams;
FileParams.SourceSize = OperationProgress->TransferSize;
FileParams.SourceTimestamp = FileData.Modification;
FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
NULL, NULL, NULL, &MTime, NULL,
&FileParams.DestSize);
FileParams.DestTimestamp = UnixToDateTime(MTime,
FTerminal->SessionData->DSTMode);
unsigned int Answer =
ConfirmOverwrite(OperationProgress->FileName, DestFileNameOnly, osLocal,
&FileParams, CopyParam, Params, OperationProgress);
switch (Answer)
{
case qaCancel:
OperationProgress->SetCancel(csCancel); // continue on next case
case qaNo:
SkipConfirmed = true;
EXCEPTION;
}
}
Action.Destination(DestFileName);
if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress,
&File, FLAGSET(Params, cpNoConfirmation)))
{
SkipConfirmed = true;
EXCEPTION;
}
FileStream = new TSafeHandleStream((THandle)File);
}
catch (Exception &E)
{
// In this step we can still cancel transfer, so we do it
SCPError(E.Message, false);
throw;
}
// We succeeded, so we confirm transfer to remote side
FSecureShell->SendNull();
// From now we need to finish file transfer, if not it's fatal error
OperationProgress->SetTransferringFile(true);
// Suppose same data size to transfer as to write
// (not true with ASCII transfer)
OperationProgress->SetLocalSize(OperationProgress->TransferSize);
// Will we use ASCII of BINARY file transfer?
OperationProgress->SetAsciiTransfer(
CopyParam->UseAsciiTransfer(BaseFileName, osRemote, MaskParams));
if (FTerminal->Configuration->ActualLogProtocol >= 0)
{
FTerminal->LogEvent(UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
L" transfer mode selected.");
}
try
{
// Buffer for one block of data
TFileBuffer BlockBuf;
bool ConvertToken = false;
do
{
BlockBuf.Size = OperationProgress->TransferBlockSize();
BlockBuf.Position = 0;
FSecureShell->Receive(reinterpret_cast<unsigned char *>(BlockBuf.Data), BlockBuf.Size);
OperationProgress->AddTransferred(BlockBuf.Size);
if (OperationProgress->AsciiTransfer)
{
unsigned int PrevBlockSize = BlockBuf.Size;
BlockBuf.Convert(FTerminal->SessionData->EOLType,
FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
OperationProgress->SetLocalSize(
OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
}
// This is crucial, if it fails during file transfer, it's fatal error
FILE_OPERATION_LOOP_BEGIN
{
BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
}
FILE_OPERATION_LOOP_END_EX(FMTLOAD(WRITE_ERROR, (DestFileName)), folNone);
OperationProgress->AddLocallyUsed(BlockBuf.Size);
if (OperationProgress->Cancel == csCancelTransfer)
{
throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
}
}
while (!OperationProgress->IsLocallyDone() || !
OperationProgress->IsTransferDone());
}
catch (Exception &E)
{
// Every exception during file transfer is fatal
FTerminal->FatalError(&E,
FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
}
OperationProgress->SetTransferringFile(false);
try
{
SCPResponse();
// If one of following exception occurs, we still need
// to send confirmation to other side
}
catch (EScp &E)
{
FSecureShell->SendNull();
throw;
}
catch (EScpFileSkipped &E)
{
FSecureShell->SendNull();
throw;
}
FSecureShell->SendNull();
if (FileData.SetTime && CopyParam->PreserveTime)
{
FTerminal->UpdateTargetTime(File, FileData.Modification, FTerminal->SessionData->DSTMode);
}
}
__finally
{
if (File) CloseHandle(File);
if (FileStream) delete FileStream;
}
}
catch(Exception & E)
{
if (SkipConfirmed)
{
Action.Cancel();
}
else
{
FTerminal->RollbackAction(Action, OperationProgress, &E);
}
throw;
}
if (FileData.Attrs == -1) FileData.Attrs = faArchive;
int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
if ((NewAttrs & FileData.Attrs) != NewAttrs)
{
FILE_OPERATION_LOOP_BEGIN
{
THROWOSIFFALSE(FileSetAttr(ApiPath(DestFileName), FileData.Attrs | NewAttrs) == 0);
}
FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFileName)));
}
FTerminal->LogFileDone(OperationProgress, DestFileName);
}
}
}
catch (EScpFileSkipped &E)
{
if (!SkipConfirmed)
{
TSuspendFileOperationProgress Suspend(OperationProgress);
TQueryParams Params(qpAllowContinueOnError);
if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FullFileName)),
&E, qaOK | qaAbort, &Params, qtError) == qaAbort)
{
OperationProgress->SetCancel(csCancel);
}
FTerminal->Log->AddException(&E);
}
// this was inside above condition, but then transfer was considered
// successful, even when for example user refused to overwrite file
Success = false;
}
catch (ESkipFile &E)
{
SCPSendError(E.Message, false);
Success = false;
if (!FTerminal->HandleException(&E)) throw;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
{
// NOOP
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
{
// noop
}
//---------------------------------------------------------------------------
void __fastcall TSCPFileSystem::ClearCaches()
{
// noop
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_512_0 |
crossvul-cpp_data_good_1376_4 | /*
* Copyright 2004-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
using namespace apache::thrift;
TEST(ProtocolSkipTest, SkipInt) {
IOBufQueue queue;
CompactProtocolWriter writer;
writer.setOutput(&queue);
writer.writeI32(123);
auto buf = queue.move();
CompactProtocolReader reader;
reader.setInput(buf.get());
reader.skip(TType::T_I32);
}
TEST(ProtocolSkipTest, SkipStop) {
IOBufQueue queue;
CompactProtocolWriter writer;
writer.setOutput(&queue);
writer.writeFieldStop();
auto buf = queue.move();
CompactProtocolReader reader;
reader.setInput(buf.get());
bool thrown = false;
try {
reader.skip(TType::T_STOP);
} catch (const TProtocolException& ex) {
EXPECT_EQ(TProtocolException::INVALID_DATA, ex.getType());
thrown = true;
}
EXPECT_TRUE(thrown);
}
TEST(ProtocolSkipTest, SkipStopInContainer) {
IOBufQueue queue;
CompactProtocolWriter writer;
writer.setOutput(&queue);
writer.writeListBegin(TType::T_STOP, 1u << 30);
auto buf = queue.move();
CompactProtocolReader reader;
reader.setInput(buf.get());
bool thrown = false;
try {
reader.skip(TType::T_LIST);
} catch (const TProtocolException& ex) {
EXPECT_EQ(TProtocolException::INVALID_DATA, ex.getType());
thrown = true;
}
EXPECT_TRUE(thrown);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1376_4 |
crossvul-cpp_data_good_2411_3 | /*
Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform.hpp"
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#endif
#include <string.h>
#include <new>
#include "stream_engine.hpp"
#include "io_thread.hpp"
#include "session_base.hpp"
#include "v1_encoder.hpp"
#include "v1_decoder.hpp"
#include "v2_encoder.hpp"
#include "v2_decoder.hpp"
#include "null_mechanism.hpp"
#include "plain_mechanism.hpp"
#include "curve_client.hpp"
#include "curve_server.hpp"
#include "raw_decoder.hpp"
#include "raw_encoder.hpp"
#include "config.hpp"
#include "err.hpp"
#include "ip.hpp"
#include "likely.hpp"
#include "wire.hpp"
zmq::stream_engine_t::stream_engine_t (fd_t fd_, const options_t &options_,
const std::string &endpoint_) :
s (fd_),
inpos (NULL),
insize (0),
decoder (NULL),
outpos (NULL),
outsize (0),
encoder (NULL),
handshaking (true),
greeting_size (v2_greeting_size),
greeting_bytes_read (0),
session (NULL),
options (options_),
endpoint (endpoint_),
plugged (false),
read_msg (&stream_engine_t::read_identity),
write_msg (&stream_engine_t::write_identity),
io_error (false),
subscription_required (false),
mechanism (NULL),
input_stopped (false),
output_stopped (false),
socket (NULL)
{
int rc = tx_msg.init ();
errno_assert (rc == 0);
// Put the socket into non-blocking mode.
unblock_socket (s);
if (!get_peer_ip_address (s, peer_address))
peer_address = "";
#ifdef SO_NOSIGPIPE
// Make sure that SIGPIPE signal is not generated when writing to a
// connection that was already closed by the peer.
int set = 1;
rc = setsockopt (s, SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof (int));
errno_assert (rc == 0);
#endif
}
zmq::stream_engine_t::~stream_engine_t ()
{
zmq_assert (!plugged);
if (s != retired_fd) {
#ifdef ZMQ_HAVE_WINDOWS
int rc = closesocket (s);
wsa_assert (rc != SOCKET_ERROR);
#else
int rc = close (s);
errno_assert (rc == 0);
#endif
s = retired_fd;
}
int rc = tx_msg.close ();
errno_assert (rc == 0);
delete encoder;
delete decoder;
delete mechanism;
}
void zmq::stream_engine_t::plug (io_thread_t *io_thread_,
session_base_t *session_)
{
zmq_assert (!plugged);
plugged = true;
// Connect to session object.
zmq_assert (!session);
zmq_assert (session_);
session = session_;
socket = session-> get_socket ();
// Connect to I/O threads poller object.
io_object_t::plug (io_thread_);
handle = add_fd (s);
io_error = false;
if (options.raw_sock) {
// no handshaking for raw sock, instantiate raw encoder and decoders
encoder = new (std::nothrow) raw_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) raw_decoder_t (in_batch_size);
alloc_assert (decoder);
// disable handshaking for raw socket
handshaking = false;
read_msg = &stream_engine_t::pull_msg_from_session;
write_msg = &stream_engine_t::push_msg_to_session;
}
else {
// Send the 'length' and 'flags' fields of the identity message.
// The 'length' field is encoded in the long format.
outpos = greeting_send;
outpos [outsize++] = 0xff;
put_uint64 (&outpos [outsize], options.identity_size + 1);
outsize += 8;
outpos [outsize++] = 0x7f;
}
set_pollin (handle);
set_pollout (handle);
// Flush all the data that may have been already received downstream.
in_event ();
}
void zmq::stream_engine_t::unplug ()
{
zmq_assert (plugged);
plugged = false;
// Cancel all fd subscriptions.
if (!io_error)
rm_fd (handle);
// Disconnect from I/O threads poller object.
io_object_t::unplug ();
session = NULL;
}
void zmq::stream_engine_t::terminate ()
{
unplug ();
delete this;
}
void zmq::stream_engine_t::in_event ()
{
assert (!io_error);
// If still handshaking, receive and process the greeting message.
if (unlikely (handshaking))
if (!handshake ())
return;
zmq_assert (decoder);
// If there has been an I/O error, stop polling.
if (input_stopped) {
rm_fd (handle);
io_error = true;
return;
}
// If there's no data to process in the buffer...
if (!insize) {
// Retrieve the buffer and read as much data as possible.
// Note that buffer can be arbitrarily large. However, we assume
// the underlying TCP layer has fixed buffer size and thus the
// number of bytes read will be always limited.
size_t bufsize = 0;
decoder->get_buffer (&inpos, &bufsize);
int const rc = read (inpos, bufsize);
if (rc == 0) {
error ();
return;
}
if (rc == -1) {
if (errno != EAGAIN)
error ();
return;
}
// Adjust input size
insize = static_cast <size_t> (rc);
}
int rc = 0;
size_t processed = 0;
while (insize > 0) {
rc = decoder->decode (inpos, insize, processed);
zmq_assert (processed <= insize);
inpos += processed;
insize -= processed;
if (rc == 0 || rc == -1)
break;
rc = (this->*write_msg) (decoder->msg ());
if (rc == -1)
break;
}
// Tear down the connection if we have failed to decode input data
// or the session has rejected the message.
if (rc == -1) {
if (errno != EAGAIN) {
error ();
return;
}
input_stopped = true;
reset_pollin (handle);
}
session->flush ();
}
void zmq::stream_engine_t::out_event ()
{
zmq_assert (!io_error);
// If write buffer is empty, try to read new data from the encoder.
if (!outsize) {
// Even when we stop polling as soon as there is no
// data to send, the poller may invoke out_event one
// more time due to 'speculative write' optimisation.
if (unlikely (encoder == NULL)) {
zmq_assert (handshaking);
return;
}
outpos = NULL;
outsize = encoder->encode (&outpos, 0);
while (outsize < out_batch_size) {
if ((this->*read_msg) (&tx_msg) == -1)
break;
encoder->load_msg (&tx_msg);
unsigned char *bufptr = outpos + outsize;
size_t n = encoder->encode (&bufptr, out_batch_size - outsize);
zmq_assert (n > 0);
if (outpos == NULL)
outpos = bufptr;
outsize += n;
}
// If there is no data to send, stop polling for output.
if (outsize == 0) {
output_stopped = true;
reset_pollout (handle);
return;
}
}
// If there are any data to write in write buffer, write as much as
// possible to the socket. Note that amount of data to write can be
// arbitrarily large. However, we assume that underlying TCP layer has
// limited transmission buffer and thus the actual number of bytes
// written should be reasonably modest.
int nbytes = write (outpos, outsize);
// IO error has occurred. We stop waiting for output events.
// The engine is not terminated until we detect input error;
// this is necessary to prevent losing incoming messages.
if (nbytes == -1) {
reset_pollout (handle);
return;
}
outpos += nbytes;
outsize -= nbytes;
// If we are still handshaking and there are no data
// to send, stop polling for output.
if (unlikely (handshaking))
if (outsize == 0)
reset_pollout (handle);
}
void zmq::stream_engine_t::restart_output ()
{
if (unlikely (io_error))
return;
if (likely (output_stopped)) {
set_pollout (handle);
output_stopped = false;
}
// Speculative write: The assumption is that at the moment new message
// was sent by the user the socket is probably available for writing.
// Thus we try to write the data to socket avoiding polling for POLLOUT.
// Consequently, the latency should be better in request/reply scenarios.
out_event ();
}
void zmq::stream_engine_t::restart_input ()
{
zmq_assert (input_stopped);
zmq_assert (session != NULL);
zmq_assert (decoder != NULL);
int rc = (this->*write_msg) (decoder->msg ());
if (rc == -1) {
if (errno == EAGAIN)
session->flush ();
else
error ();
return;
}
while (insize > 0) {
size_t processed = 0;
rc = decoder->decode (inpos, insize, processed);
zmq_assert (processed <= insize);
inpos += processed;
insize -= processed;
if (rc == 0 || rc == -1)
break;
rc = (this->*write_msg) (decoder->msg ());
if (rc == -1)
break;
}
if (rc == -1 && errno == EAGAIN)
session->flush ();
else
if (rc == -1 || io_error)
error ();
else {
input_stopped = false;
set_pollin (handle);
session->flush ();
// Speculative read.
in_event ();
}
}
bool zmq::stream_engine_t::handshake ()
{
zmq_assert (handshaking);
zmq_assert (greeting_bytes_read < greeting_size);
// Receive the greeting.
while (greeting_bytes_read < greeting_size) {
const int n = read (greeting_recv + greeting_bytes_read,
greeting_size - greeting_bytes_read);
if (n == 0) {
error ();
return false;
}
if (n == -1) {
if (errno != EAGAIN)
error ();
return false;
}
greeting_bytes_read += n;
// We have received at least one byte from the peer.
// If the first byte is not 0xff, we know that the
// peer is using unversioned protocol.
if (greeting_recv [0] != 0xff)
break;
if (greeting_bytes_read < signature_size)
continue;
// Inspect the right-most bit of the 10th byte (which coincides
// with the 'flags' field if a regular message was sent).
// Zero indicates this is a header of identity message
// (i.e. the peer is using the unversioned protocol).
if (!(greeting_recv [9] & 0x01))
break;
// The peer is using versioned protocol.
// Send the major version number.
if (outpos + outsize == greeting_send + signature_size) {
if (outsize == 0)
set_pollout (handle);
outpos [outsize++] = 3; // Major version number
}
if (greeting_bytes_read > signature_size) {
if (outpos + outsize == greeting_send + signature_size + 1) {
if (outsize == 0)
set_pollout (handle);
// Use ZMTP/2.0 to talk to older peers.
if (greeting_recv [10] == ZMTP_1_0
|| greeting_recv [10] == ZMTP_2_0)
outpos [outsize++] = options.type;
else {
outpos [outsize++] = 0; // Minor version number
memset (outpos + outsize, 0, 20);
zmq_assert (options.mechanism == ZMQ_NULL
|| options.mechanism == ZMQ_PLAIN
|| options.mechanism == ZMQ_CURVE);
if (options.mechanism == ZMQ_NULL)
memcpy (outpos + outsize, "NULL", 4);
else
if (options.mechanism == ZMQ_PLAIN)
memcpy (outpos + outsize, "PLAIN", 5);
else
memcpy (outpos + outsize, "CURVE", 5);
outsize += 20;
memset (outpos + outsize, 0, 32);
outsize += 32;
greeting_size = v3_greeting_size;
}
}
}
}
// Position of the revision field in the greeting.
const size_t revision_pos = 10;
// Is the peer using ZMTP/1.0 with no revision number?
// If so, we send and receive rest of identity message
if (greeting_recv [0] != 0xff || !(greeting_recv [9] & 0x01)) {
if (session->zap_enabled ()) {
// Reject ZMTP 1.0 connections if ZAP is enabled
error ();
return false;
}
encoder = new (std::nothrow) v1_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v1_decoder_t (in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
// We have already sent the message header.
// Since there is no way to tell the encoder to
// skip the message header, we simply throw that
// header data away.
const size_t header_size = options.identity_size + 1 >= 255 ? 10 : 2;
unsigned char tmp [10], *bufferp = tmp;
// Prepare the identity message and load it into encoder.
// Then consume bytes we have already sent to the peer.
const int rc = tx_msg.init_size (options.identity_size);
zmq_assert (rc == 0);
memcpy (tx_msg.data (), options.identity, options.identity_size);
encoder->load_msg (&tx_msg);
size_t buffer_size = encoder->encode (&bufferp, header_size);
zmq_assert (buffer_size == header_size);
// Make sure the decoder sees the data we have already received.
inpos = greeting_recv;
insize = greeting_bytes_read;
// To allow for interoperability with peers that do not forward
// their subscriptions, we inject a phantom subscription message
// message into the incoming message stream.
if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB)
subscription_required = true;
// We are sending our identity now and the next message
// will come from the socket.
read_msg = &stream_engine_t::pull_msg_from_session;
// We are expecting identity message.
write_msg = &stream_engine_t::write_identity;
}
else
if (greeting_recv [revision_pos] == ZMTP_1_0) {
if (session->zap_enabled ()) {
// Reject ZMTP 1.0 connections if ZAP is enabled
error ();
return false;
}
encoder = new (std::nothrow) v1_encoder_t (
out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v1_decoder_t (
in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
}
else
if (greeting_recv [revision_pos] == ZMTP_2_0) {
if (session->zap_enabled ()) {
// Reject ZMTP 1.0 connections if ZAP is enabled
error ();
return false;
}
encoder = new (std::nothrow) v2_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v2_decoder_t (
in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
}
else {
encoder = new (std::nothrow) v2_encoder_t (out_batch_size);
alloc_assert (encoder);
decoder = new (std::nothrow) v2_decoder_t (
in_batch_size, options.maxmsgsize);
alloc_assert (decoder);
if (options.mechanism == ZMQ_NULL
&& memcmp (greeting_recv + 12, "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) {
mechanism = new (std::nothrow)
null_mechanism_t (session, peer_address, options);
alloc_assert (mechanism);
}
else
if (options.mechanism == ZMQ_PLAIN
&& memcmp (greeting_recv + 12, "PLAIN\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) {
mechanism = new (std::nothrow)
plain_mechanism_t (session, peer_address, options);
alloc_assert (mechanism);
}
#ifdef HAVE_LIBSODIUM
else
if (options.mechanism == ZMQ_CURVE
&& memcmp (greeting_recv + 12, "CURVE\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) {
if (options.as_server)
mechanism = new (std::nothrow)
curve_server_t (session, peer_address, options);
else
mechanism = new (std::nothrow) curve_client_t (options);
alloc_assert (mechanism);
}
#endif
else {
error ();
return false;
}
read_msg = &stream_engine_t::next_handshake_command;
write_msg = &stream_engine_t::process_handshake_command;
}
// Start polling for output if necessary.
if (outsize == 0)
set_pollout (handle);
// Handshaking was successful.
// Switch into the normal message flow.
handshaking = false;
return true;
}
int zmq::stream_engine_t::read_identity (msg_t *msg_)
{
int rc = msg_->init_size (options.identity_size);
errno_assert (rc == 0);
if (options.identity_size > 0)
memcpy (msg_->data (), options.identity, options.identity_size);
read_msg = &stream_engine_t::pull_msg_from_session;
return 0;
}
int zmq::stream_engine_t::write_identity (msg_t *msg_)
{
if (options.recv_identity) {
msg_->set_flags (msg_t::identity);
int rc = session->push_msg (msg_);
errno_assert (rc == 0);
}
else {
int rc = msg_->close ();
errno_assert (rc == 0);
rc = msg_->init ();
errno_assert (rc == 0);
}
if (subscription_required)
write_msg = &stream_engine_t::write_subscription_msg;
else
write_msg = &stream_engine_t::push_msg_to_session;
return 0;
}
int zmq::stream_engine_t::next_handshake_command (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->next_handshake_command (msg_);
if (rc == 0) {
msg_->set_flags (msg_t::command);
if (mechanism->is_handshake_complete ())
mechanism_ready ();
}
return rc;
}
int zmq::stream_engine_t::process_handshake_command (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->process_handshake_command (msg_);
if (rc == 0) {
if (mechanism->is_handshake_complete ())
mechanism_ready ();
if (output_stopped)
restart_output ();
}
return rc;
}
void zmq::stream_engine_t::zap_msg_available ()
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->zap_msg_available ();
if (rc == -1) {
error ();
return;
}
if (input_stopped)
restart_input ();
if (output_stopped)
restart_output ();
}
void zmq::stream_engine_t::mechanism_ready ()
{
if (options.recv_identity) {
msg_t identity;
mechanism->peer_identity (&identity);
const int rc = session->push_msg (&identity);
if (rc == -1 && errno == EAGAIN) {
// If the write is failing at this stage with
// an EAGAIN the pipe must be being shut down,
// so we can just bail out of the identity set.
return;
}
errno_assert (rc == 0);
session->flush ();
}
read_msg = &stream_engine_t::pull_and_encode;
write_msg = &stream_engine_t::decode_and_push;
}
int zmq::stream_engine_t::pull_msg_from_session (msg_t *msg_)
{
return session->pull_msg (msg_);
}
int zmq::stream_engine_t::push_msg_to_session (msg_t *msg_)
{
return session->push_msg (msg_);
}
int zmq::stream_engine_t::pull_and_encode (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
if (session->pull_msg (msg_) == -1)
return -1;
if (mechanism->encode (msg_) == -1)
return -1;
return 0;
}
int zmq::stream_engine_t::decode_and_push (msg_t *msg_)
{
zmq_assert (mechanism != NULL);
if (mechanism->decode (msg_) == -1)
return -1;
if (session->push_msg (msg_) == -1) {
if (errno == EAGAIN)
write_msg = &stream_engine_t::push_one_then_decode_and_push;
return -1;
}
return 0;
}
int zmq::stream_engine_t::push_one_then_decode_and_push (msg_t *msg_)
{
const int rc = session->push_msg (msg_);
if (rc == 0)
write_msg = &stream_engine_t::decode_and_push;
return rc;
}
int zmq::stream_engine_t::write_subscription_msg (msg_t *msg_)
{
msg_t subscription;
// Inject the subscription message, so that also
// ZMQ 2.x peers receive published messages.
int rc = subscription.init_size (1);
errno_assert (rc == 0);
*(unsigned char*) subscription.data () = 1;
rc = session->push_msg (&subscription);
if (rc == -1)
return -1;
write_msg = &stream_engine_t::push_msg_to_session;
return push_msg_to_session (msg_);
}
void zmq::stream_engine_t::error ()
{
zmq_assert (session);
socket->event_disconnected (endpoint, s);
session->flush ();
session->detach ();
unplug ();
delete this;
}
int zmq::stream_engine_t::write (const void *data_, size_t size_)
{
#ifdef ZMQ_HAVE_WINDOWS
int nbytes = send (s, (char*) data_, (int) size_, 0);
// If not a single byte can be written to the socket in non-blocking mode
// we'll get an error (this may happen during the speculative write).
if (nbytes == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK)
return 0;
// Signalise peer failure.
if (nbytes == SOCKET_ERROR && (
WSAGetLastError () == WSAENETDOWN ||
WSAGetLastError () == WSAENETRESET ||
WSAGetLastError () == WSAEHOSTUNREACH ||
WSAGetLastError () == WSAECONNABORTED ||
WSAGetLastError () == WSAETIMEDOUT ||
WSAGetLastError () == WSAECONNRESET))
return -1;
wsa_assert (nbytes != SOCKET_ERROR);
return nbytes;
#else
ssize_t nbytes = send (s, data_, size_, 0);
// Several errors are OK. When speculative write is being done we may not
// be able to write a single byte from the socket. Also, SIGSTOP issued
// by a debugging tool can result in EINTR error.
if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK ||
errno == EINTR))
return 0;
// Signalise peer failure.
if (nbytes == -1) {
errno_assert (errno != EACCES
&& errno != EBADF
&& errno != EDESTADDRREQ
&& errno != EFAULT
&& errno != EINVAL
&& errno != EISCONN
&& errno != EMSGSIZE
&& errno != ENOMEM
&& errno != ENOTSOCK
&& errno != EOPNOTSUPP);
return -1;
}
return static_cast <int> (nbytes);
#endif
}
int zmq::stream_engine_t::read (void *data_, size_t size_)
{
#ifdef ZMQ_HAVE_WINDOWS
const int rc = recv (s, (char*) data_, (int) size_, 0);
// If not a single byte can be read from the socket in non-blocking mode
// we'll get an error (this may happen during the speculative read).
if (rc == SOCKET_ERROR) {
if (WSAGetLastError () == WSAEWOULDBLOCK)
errno = EAGAIN;
else {
wsa_assert (WSAGetLastError () == WSAENETDOWN
|| WSAGetLastError () == WSAENETRESET
|| WSAGetLastError () == WSAECONNABORTED
|| WSAGetLastError () == WSAETIMEDOUT
|| WSAGetLastError () == WSAECONNRESET
|| WSAGetLastError () == WSAECONNREFUSED
|| WSAGetLastError () == WSAENOTCONN);
errno = wsa_error_to_errno (WSAGetLastError ());
}
}
return rc == SOCKET_ERROR? -1: rc;
#else
const ssize_t rc = recv (s, data_, size_, 0);
// Several errors are OK. When speculative read is being done we may not
// be able to read a single byte from the socket. Also, SIGSTOP issued
// by a debugging tool can result in EINTR error.
if (rc == -1) {
errno_assert (errno != EBADF
&& errno != EFAULT
&& errno != EINVAL
&& errno != ENOMEM
&& errno != ENOTSOCK);
if (errno == EWOULDBLOCK || errno == EINTR)
errno = EAGAIN;
}
return static_cast <int> (rc);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_2411_3 |
crossvul-cpp_data_good_3201_1 | /*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2014 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#include "abstractwebapplication.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QNetworkCookie>
#include <QTemporaryFile>
#include <QTimer>
#include "base/preferences.h"
#include "base/utils/fs.h"
#include "base/utils/random.h"
#include "websessiondata.h"
// UnbanTimer
class UnbanTimer: public QTimer
{
public:
UnbanTimer(const QHostAddress& peer_ip, QObject *parent)
: QTimer(parent), m_peerIp(peer_ip)
{
setSingleShot(true);
setInterval(BAN_TIME);
}
inline const QHostAddress& peerIp() const { return m_peerIp; }
private:
QHostAddress m_peerIp;
};
// WebSession
struct WebSession
{
const QString id;
uint timestamp;
WebSessionData data;
WebSession(const QString& id)
: id(id)
{
updateTimestamp();
}
void updateTimestamp()
{
timestamp = QDateTime::currentDateTime().toTime_t();
}
};
// AbstractWebApplication
AbstractWebApplication::AbstractWebApplication(QObject *parent)
: Http::ResponseBuilder(parent)
, session_(0)
{
QTimer *timer = new QTimer(this);
timer->setInterval(60000); // 1 min.
connect(timer, SIGNAL(timeout()), SLOT(removeInactiveSessions()));
}
AbstractWebApplication::~AbstractWebApplication()
{
// cleanup sessions data
qDeleteAll(sessions_);
}
Http::Response AbstractWebApplication::processRequest(const Http::Request &request, const Http::Environment &env)
{
session_ = 0;
request_ = request;
env_ = env;
// clear response
clear();
// avoid clickjacking attacks
header(Http::HEADER_X_FRAME_OPTIONS, "SAMEORIGIN");
sessionInitialize();
if (!sessionActive() && !isAuthNeeded())
sessionStart();
if (isBanned()) {
status(403, "Forbidden");
print(QObject::tr("Your IP address has been banned after too many failed authentication attempts."), Http::CONTENT_TYPE_TXT);
}
else {
processRequest();
}
return response();
}
void AbstractWebApplication::UnbanTimerEvent()
{
UnbanTimer* ubantimer = static_cast<UnbanTimer*>(sender());
qDebug("Ban period has expired for %s", qPrintable(ubantimer->peerIp().toString()));
clientFailedAttempts_.remove(ubantimer->peerIp());
ubantimer->deleteLater();
}
void AbstractWebApplication::removeInactiveSessions()
{
const uint now = QDateTime::currentDateTime().toTime_t();
foreach (const QString &id, sessions_.keys()) {
if ((now - sessions_[id]->timestamp) > INACTIVE_TIME)
delete sessions_.take(id);
}
}
bool AbstractWebApplication::sessionInitialize()
{
static const QString SID_START = QLatin1String(C_SID) + QLatin1String("=");
if (session_ == 0)
{
QString cookie = request_.headers.value("cookie");
//qDebug() << Q_FUNC_INFO << "cookie: " << cookie;
QString sessionId;
int pos = cookie.indexOf(SID_START);
if (pos >= 0) {
pos += SID_START.length();
int end = cookie.indexOf(QRegExp("[,;]"), pos);
sessionId = cookie.mid(pos, end >= 0 ? end - pos : end);
}
// TODO: Additional session check
if (!sessionId.isNull()) {
if (sessions_.contains(sessionId)) {
session_ = sessions_[sessionId];
session_->updateTimestamp();
return true;
}
else {
qDebug() << Q_FUNC_INFO << "session does not exist!";
}
}
}
return false;
}
bool AbstractWebApplication::readFile(const QString& path, QByteArray &data, QString &type)
{
QString ext = "";
int index = path.lastIndexOf('.') + 1;
if (index > 0)
ext = path.mid(index);
// find translated file in cache
if (translatedFiles_.contains(path)) {
data = translatedFiles_[path];
}
else {
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
qDebug("File %s was not found!", qPrintable(path));
return false;
}
data = file.readAll();
file.close();
// Translate the file
if ((ext == "html") || ((ext == "js") && !path.endsWith("excanvas-compressed.js"))) {
QString dataStr = QString::fromUtf8(data.constData());
translateDocument(dataStr);
if (path.endsWith("about.html") || path.endsWith("index.html") || path.endsWith("client.js"))
dataStr.replace("${VERSION}", VERSION);
data = dataStr.toUtf8();
translatedFiles_[path] = data; // cashing translated file
}
}
type = CONTENT_TYPE_BY_EXT[ext];
return true;
}
WebSessionData *AbstractWebApplication::session()
{
Q_ASSERT(session_ != 0);
return &session_->data;
}
QString AbstractWebApplication::generateSid()
{
QString sid;
do {
const size_t size = 6;
quint32 tmp[size];
for (size_t i = 0; i < size; ++i)
tmp[i] = Utils::Random::rand();
sid = QByteArray::fromRawData(reinterpret_cast<const char *>(tmp), sizeof(quint32) * size).toBase64();
}
while (sessions_.contains(sid));
return sid;
}
void AbstractWebApplication::translateDocument(QString& data)
{
const QRegExp regex("QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR(\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\])?");
const QRegExp mnemonic("\\(?&([a-zA-Z]?\\))?");
const std::string contexts[] = {
"TransferListFiltersWidget", "TransferListWidget", "PropertiesWidget",
"HttpServer", "confirmDeletionDlg", "TrackerList", "TorrentFilesModel",
"options_imp", "Preferences", "TrackersAdditionDlg", "ScanFoldersModel",
"PropTabBar", "TorrentModel", "downloadFromURL", "MainWindow", "misc",
"StatusBar", "AboutDlg", "about", "PeerListWidget", "StatusFiltersWidget",
"CategoryFiltersList", "TransferListDelegate"
};
const size_t context_count = sizeof(contexts) / sizeof(contexts[0]);
int i = 0;
bool found = true;
const QString locale = Preferences::instance()->getLocale();
bool isTranslationNeeded = !locale.startsWith("en") || locale.startsWith("en_AU") || locale.startsWith("en_GB");
while(i < data.size() && found) {
i = regex.indexIn(data, i);
if (i >= 0) {
//qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data());
QByteArray word = regex.cap(1).toUtf8();
QString translation = word;
if (isTranslationNeeded) {
QString context = regex.cap(4);
if (context.length() > 0) {
#ifndef QBT_USES_QT5
translation = qApp->translate(context.toUtf8().constData(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1);
#else
translation = qApp->translate(context.toUtf8().constData(), word.constData(), 0, 1);
#endif
}
else {
size_t context_index = 0;
while ((context_index < context_count) && (translation == word)) {
#ifndef QBT_USES_QT5
translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1);
#else
translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, 1);
#endif
++context_index;
}
}
}
// Remove keyboard shortcuts
translation.replace(mnemonic, "");
// Use HTML code for quotes to prevent issues with JS
translation.replace("'", "'");
translation.replace("\"", """);
data.replace(i, regex.matchedLength(), translation);
i += translation.length();
}
else {
found = false; // no more translatable strings
}
}
}
bool AbstractWebApplication::isBanned() const
{
return clientFailedAttempts_.value(env_.clientAddress, 0) >= MAX_AUTH_FAILED_ATTEMPTS;
}
int AbstractWebApplication::failedAttempts() const
{
return clientFailedAttempts_.value(env_.clientAddress, 0);
}
void AbstractWebApplication::resetFailedAttempts()
{
clientFailedAttempts_.remove(env_.clientAddress);
}
void AbstractWebApplication::increaseFailedAttempts()
{
const int nb_fail = clientFailedAttempts_.value(env_.clientAddress, 0) + 1;
clientFailedAttempts_[env_.clientAddress] = nb_fail;
if (nb_fail == MAX_AUTH_FAILED_ATTEMPTS) {
// Max number of failed attempts reached
// Start ban period
UnbanTimer* ubantimer = new UnbanTimer(env_.clientAddress, this);
connect(ubantimer, SIGNAL(timeout()), SLOT(UnbanTimerEvent()));
ubantimer->start();
}
}
bool AbstractWebApplication::isAuthNeeded()
{
return (env_.clientAddress != QHostAddress::LocalHost
&& env_.clientAddress != QHostAddress::LocalHostIPv6
&& env_.clientAddress != QHostAddress("::ffff:127.0.0.1"))
|| Preferences::instance()->isWebUiLocalAuthEnabled();
}
void AbstractWebApplication::printFile(const QString& path)
{
QByteArray data;
QString type;
if (!readFile(path, data, type)) {
status(404, "Not Found");
return;
}
print(data, type);
}
bool AbstractWebApplication::sessionStart()
{
if (session_ == 0) {
session_ = new WebSession(generateSid());
sessions_[session_->id] = session_;
QNetworkCookie cookie(C_SID, session_->id.toUtf8());
cookie.setPath(QLatin1String("/"));
header(Http::HEADER_SET_COOKIE, cookie.toRawForm());
return true;
}
return false;
}
bool AbstractWebApplication::sessionEnd()
{
if ((session_ != 0) && (sessions_.contains(session_->id))) {
QNetworkCookie cookie(C_SID, session_->id.toUtf8());
cookie.setPath(QLatin1String("/"));
cookie.setExpirationDate(QDateTime::currentDateTime());
sessions_.remove(session_->id);
delete session_;
session_ = 0;
header(Http::HEADER_SET_COOKIE, cookie.toRawForm());
return true;
}
return false;
}
QString AbstractWebApplication::saveTmpFile(const QByteArray &data)
{
QTemporaryFile tmpfile(Utils::Fs::tempPath() + "XXXXXX.torrent");
tmpfile.setAutoRemove(false);
if (tmpfile.open()) {
tmpfile.write(data);
tmpfile.close();
return tmpfile.fileName();
}
qWarning() << "I/O Error: Could not create temporary file";
return QString();
}
QStringMap AbstractWebApplication::initializeContentTypeByExtMap()
{
QStringMap map;
map["htm"] = Http::CONTENT_TYPE_HTML;
map["html"] = Http::CONTENT_TYPE_HTML;
map["css"] = Http::CONTENT_TYPE_CSS;
map["gif"] = Http::CONTENT_TYPE_GIF;
map["png"] = Http::CONTENT_TYPE_PNG;
map["js"] = Http::CONTENT_TYPE_JS;
return map;
}
const QStringMap AbstractWebApplication::CONTENT_TYPE_BY_EXT = AbstractWebApplication::initializeContentTypeByExtMap();
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_3201_1 |
crossvul-cpp_data_good_3594_0 | /***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevector.h>
#include <tdebug.h>
#include <xiphcomment.h>
using namespace TagLib;
class Ogg::XiphComment::XiphCommentPrivate
{
public:
FieldListMap fieldListMap;
String vendorID;
String commentField;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
Ogg::XiphComment::XiphComment() : TagLib::Tag()
{
d = new XiphCommentPrivate;
}
Ogg::XiphComment::XiphComment(const ByteVector &data) : TagLib::Tag()
{
d = new XiphCommentPrivate;
parse(data);
}
Ogg::XiphComment::~XiphComment()
{
delete d;
}
String Ogg::XiphComment::title() const
{
if(d->fieldListMap["TITLE"].isEmpty())
return String::null;
return d->fieldListMap["TITLE"].front();
}
String Ogg::XiphComment::artist() const
{
if(d->fieldListMap["ARTIST"].isEmpty())
return String::null;
return d->fieldListMap["ARTIST"].front();
}
String Ogg::XiphComment::album() const
{
if(d->fieldListMap["ALBUM"].isEmpty())
return String::null;
return d->fieldListMap["ALBUM"].front();
}
String Ogg::XiphComment::comment() const
{
if(!d->fieldListMap["DESCRIPTION"].isEmpty()) {
d->commentField = "DESCRIPTION";
return d->fieldListMap["DESCRIPTION"].front();
}
if(!d->fieldListMap["COMMENT"].isEmpty()) {
d->commentField = "COMMENT";
return d->fieldListMap["COMMENT"].front();
}
return String::null;
}
String Ogg::XiphComment::genre() const
{
if(d->fieldListMap["GENRE"].isEmpty())
return String::null;
return d->fieldListMap["GENRE"].front();
}
TagLib::uint Ogg::XiphComment::year() const
{
if(!d->fieldListMap["DATE"].isEmpty())
return d->fieldListMap["DATE"].front().toInt();
if(!d->fieldListMap["YEAR"].isEmpty())
return d->fieldListMap["YEAR"].front().toInt();
return 0;
}
TagLib::uint Ogg::XiphComment::track() const
{
if(!d->fieldListMap["TRACKNUMBER"].isEmpty())
return d->fieldListMap["TRACKNUMBER"].front().toInt();
if(!d->fieldListMap["TRACKNUM"].isEmpty())
return d->fieldListMap["TRACKNUM"].front().toInt();
return 0;
}
void Ogg::XiphComment::setTitle(const String &s)
{
addField("TITLE", s);
}
void Ogg::XiphComment::setArtist(const String &s)
{
addField("ARTIST", s);
}
void Ogg::XiphComment::setAlbum(const String &s)
{
addField("ALBUM", s);
}
void Ogg::XiphComment::setComment(const String &s)
{
addField(d->commentField.isEmpty() ? "DESCRIPTION" : d->commentField, s);
}
void Ogg::XiphComment::setGenre(const String &s)
{
addField("GENRE", s);
}
void Ogg::XiphComment::setYear(uint i)
{
removeField("YEAR");
if(i == 0)
removeField("DATE");
else
addField("DATE", String::number(i));
}
void Ogg::XiphComment::setTrack(uint i)
{
removeField("TRACKNUM");
if(i == 0)
removeField("TRACKNUMBER");
else
addField("TRACKNUMBER", String::number(i));
}
bool Ogg::XiphComment::isEmpty() const
{
FieldListMap::ConstIterator it = d->fieldListMap.begin();
for(; it != d->fieldListMap.end(); ++it)
if(!(*it).second.isEmpty())
return false;
return true;
}
TagLib::uint Ogg::XiphComment::fieldCount() const
{
uint count = 0;
FieldListMap::ConstIterator it = d->fieldListMap.begin();
for(; it != d->fieldListMap.end(); ++it)
count += (*it).second.size();
return count;
}
const Ogg::FieldListMap &Ogg::XiphComment::fieldListMap() const
{
return d->fieldListMap;
}
String Ogg::XiphComment::vendorID() const
{
return d->vendorID;
}
void Ogg::XiphComment::addField(const String &key, const String &value, bool replace)
{
if(replace)
removeField(key.upper());
if(!key.isEmpty() && !value.isEmpty())
d->fieldListMap[key.upper()].append(value);
}
void Ogg::XiphComment::removeField(const String &key, const String &value)
{
if(!value.isNull()) {
StringList::Iterator it = d->fieldListMap[key].begin();
while(it != d->fieldListMap[key].end()) {
if(value == *it)
it = d->fieldListMap[key].erase(it);
else
it++;
}
}
else
d->fieldListMap.erase(key);
}
bool Ogg::XiphComment::contains(const String &key) const
{
return d->fieldListMap.contains(key) && !d->fieldListMap[key].isEmpty();
}
ByteVector Ogg::XiphComment::render() const
{
return render(true);
}
ByteVector Ogg::XiphComment::render(bool addFramingBit) const
{
ByteVector data;
// Add the vendor ID length and the vendor ID. It's important to use the
// length of the data(String::UTF8) rather than the length of the the string
// since this is UTF8 text and there may be more characters in the data than
// in the UTF16 string.
ByteVector vendorData = d->vendorID.data(String::UTF8);
data.append(ByteVector::fromUInt(vendorData.size(), false));
data.append(vendorData);
// Add the number of fields.
data.append(ByteVector::fromUInt(fieldCount(), false));
// Iterate over the the field lists. Our iterator returns a
// std::pair<String, StringList> where the first String is the field name and
// the StringList is the values associated with that field.
FieldListMap::ConstIterator it = d->fieldListMap.begin();
for(; it != d->fieldListMap.end(); ++it) {
// And now iterate over the values of the current list.
String fieldName = (*it).first;
StringList values = (*it).second;
StringList::ConstIterator valuesIt = values.begin();
for(; valuesIt != values.end(); ++valuesIt) {
ByteVector fieldData = fieldName.data(String::UTF8);
fieldData.append('=');
fieldData.append((*valuesIt).data(String::UTF8));
data.append(ByteVector::fromUInt(fieldData.size(), false));
data.append(fieldData);
}
}
// Append the "framing bit".
if(addFramingBit)
data.append(char(1));
return data;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void Ogg::XiphComment::parse(const ByteVector &data)
{
// The first thing in the comment data is the vendor ID length, followed by a
// UTF8 string with the vendor ID.
int pos = 0;
int vendorLength = data.mid(0, 4).toUInt(false);
pos += 4;
d->vendorID = String(data.mid(pos, vendorLength), String::UTF8);
pos += vendorLength;
// Next the number of fields in the comment vector.
uint commentFields = data.mid(pos, 4).toUInt(false);
pos += 4;
if(commentFields > (data.size() - 8) / 4) {
return;
}
for(uint i = 0; i < commentFields; i++) {
// Each comment field is in the format "KEY=value" in a UTF8 string and has
// 4 bytes before the text starts that gives the length.
uint commentLength = data.mid(pos, 4).toUInt(false);
pos += 4;
String comment = String(data.mid(pos, commentLength), String::UTF8);
pos += commentLength;
if(pos > data.size()) {
break;
}
int commentSeparatorPosition = comment.find("=");
if(commentSeparatorPosition == -1) {
break;
}
String key = comment.substr(0, commentSeparatorPosition);
String value = comment.substr(commentSeparatorPosition + 1);
addField(key, value, false);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_3594_0 |
crossvul-cpp_data_good_600_1 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/test/HTTPParallelCodecTest.h>
#include <proxygen/lib/http/codec/test/MockHTTPCodec.h>
#include <folly/io/Cursor.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/test/HTTP2FramerTest.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <folly/portability/GTest.h>
#include <folly/portability/GMock.h>
#include <random>
using namespace proxygen;
using namespace proxygen::compress;
using namespace folly;
using namespace folly::io;
using namespace std;
using namespace testing;
TEST(HTTP2CodecConstantsTest, HTTPContantsAreCommonHeaders) {
// The purpose of this test is to verify some basic assumptions that should
// never change but to make clear that the following http2 header constants
// map to the respective common headers. Should this test ever fail, the
// H2Codec would need to be updated in the corresponding places when creating
// compress/Header objects.
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kMethod),
HTTP_HEADER_COLON_METHOD);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kScheme),
HTTP_HEADER_COLON_SCHEME);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kPath),
HTTP_HEADER_COLON_PATH);
EXPECT_EQ(
HTTPCommonHeaders::hash(headers::kAuthority),
HTTP_HEADER_COLON_AUTHORITY);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kStatus),
HTTP_HEADER_COLON_STATUS);
}
class HTTP2CodecTest : public HTTPParallelCodecTest {
public:
HTTP2CodecTest()
:HTTPParallelCodecTest(upstreamCodec_, downstreamCodec_) {}
void SetUp() override {
HTTPParallelCodecTest::SetUp();
}
void testHeaderListSize(bool oversized);
void testFrameSizeLimit(bool oversized);
protected:
HTTP2Codec upstreamCodec_{TransportDirection::UPSTREAM};
HTTP2Codec downstreamCodec_{TransportDirection::DOWNSTREAM};
};
TEST_F(HTTP2CodecTest, IgnoreUnknownSettings) {
auto numSettings = downstreamCodec_.getIngressSettings()->getNumSettings();
std::deque<SettingPair> settings;
for (uint32_t i = 200; i < (200 + 1024); i++) {
settings.push_back(SettingPair(SettingsId(i), i));
}
http2::writeSettings(output_, settings);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(numSettings,
downstreamCodec_.getIngressSettings()->getNumSettings());
}
TEST_F(HTTP2CodecTest, NoExHeaders) {
// do not emit ENABLE_EX_HEADERS setting, if disabled
SetUpUpstreamTest();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.numSettings, 0);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
parseUpstream();
EXPECT_EQ(callbacks_.settings, 1);
// only 3 standard settings: HEADER_TABLE_SIZE, ENABLE_PUSH, MAX_FRAME_SIZE.
EXPECT_EQ(callbacks_.numSettings, 3);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersSetting) {
// disable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, EnableExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
EXPECT_EQ(true, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, InvalidExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
// attempt to set a invalid ENABLE_EX_HEADERS value
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 110)});
parse();
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeader) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, RequestFromServer) {
// this is to test EX_HEADERS frame, which carrys the HTTP request initiated
// by server side
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
SetUpUpstreamTest();
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
upstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true),
true);
parseUpstream();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, ResponseFromClient) {
// this is to test EX_HEADERS frame, which carrys the HTTP response replied by
// client side
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, resp,
HTTPCodec::ExAttributes(controlStream, true), true);
parse();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, ExHeadersWithPriority) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
auto req = getGetRequest();
auto pri = HTTPMessage::HTTPPriority(0, false, 7);
req.setHTTP2Priority(pri);
upstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.msg->getHTTP2Priority(), pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersIfNotEnabled) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
HTTPMessage req = getGetRequest("/guacamole");
downstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaders) {
static const std::string v1("GET");
static const std::string v2("/");
static const std::string v3("http");
static const std::string v4("foo.com");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 7);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPseudoHeaders) {
static const std::string v1("POST");
static const std::string v2("http");
static const std::string n3("foo");
static const std::string v3("bar");
static const std::string v4("/");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kScheme, v2),
Header::makeHeaderForTest(n3, v3),
Header::makeHeaderForTest(headers::kPath, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderValues) {
static const std::string v1("--1");
static const std::string v2("\13\10protocol-attack");
static const std::string v3("\13");
static const std::string v4("abc.com\\13\\10");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders;
allHeaders.push_back(reqHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 4);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
/**
* Ingress bytes with an empty header name
*/
const uint8_t kBufEmptyHeader[] = {
0x00, 0x00, 0x1d, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x82,
0x87, 0x44, 0x87, 0x62, 0x6b, 0x46, 0x41, 0xd2, 0x7a, 0x0b,
0x41, 0x89, 0xf1, 0xe3, 0xc2, 0xf2, 0x9c, 0xeb, 0x90, 0xf4,
0xff, 0x40, 0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7
};
TEST_F(HTTP2CodecTest, EmptyHeaderName) {
output_.append(IOBuf::copyBuffer(kBufEmptyHeader, sizeof(kBufEmptyHeader)));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicConnect) {
std::string authority = "myhost:1234";
HTTPMessage request;
request.setMethod(HTTPMethod::CONNECT);
request.getHeaders().add(proxygen::HTTP_HEADER_HOST, authority);
upstreamCodec_.generateHeader(output_, 1, request, false /* eom */);
parse();
callbacks_.expectMessage(false, 1, "");
EXPECT_EQ(HTTPMethod::CONNECT, callbacks_.msg->getMethod());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(authority, headers.getSingleOrEmpty(proxygen::HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, BadConnect) {
std::string v1 = "CONNECT";
std::string v2 = "somehost:576";
std::vector<proxygen::compress::Header> goodHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kAuthority, v2),
};
// See https://tools.ietf.org/html/rfc7540#section-8.3
std::string v3 = "/foobar";
std::vector<proxygen::compress::Header> badHeaders = {
Header::makeHeaderForTest(headers::kScheme, headers::kHttp),
Header::makeHeaderForTest(headers::kPath, v3),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < badHeaders.size(); i++, stream += 2) {
auto allHeaders = goodHeaders;
allHeaders.push_back(badHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, badHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
void HTTP2CodecTest::testHeaderListSize(bool oversized) {
if (oversized) {
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
}
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("x-long-long-header",
"supercalafragalisticexpialadoshus");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
void HTTP2CodecTest::testFrameSizeLimit(bool oversized) {
HTTPMessage req = getBigGetRequest("/guacamole");
auto settings = downstreamCodec_.getEgressSettings();
parse(); // consume preface
if (oversized) {
// trick upstream for sending a 2x bigger HEADERS frame
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin * 2);
downstreamCodec_.generateSettings(output_);
parseUpstream();
}
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
TEST_F(HTTP2CodecTest, NormalSizeHeader) {
testHeaderListSize(false);
}
TEST_F(HTTP2CodecTest, OversizedHeader) {
testHeaderListSize(true);
}
TEST_F(HTTP2CodecTest, NormalSizeFrame) {
testFrameSizeLimit(false);
}
TEST_F(HTTP2CodecTest, OversizedFrame) {
testFrameSizeLimit(true);
}
TEST_F(HTTP2CodecTest, BigHeaderCompressed) {
SetUpUpstreamTest();
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
downstreamCodec_.generateSettings(output_);
parseUpstream();
SetUp();
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeaderReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
// HTTP/2 doesnt support serialization - instead you get the default
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadHeadersReply) {
static const std::string v1("200");
static const vector<proxygen::compress::Header> respHeaders = {
Header::makeHeaderForTest(headers::kStatus, v1),
};
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, Cookies) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add("Cookie", "chocolate-chip=1");
req.getHeaders().add("Cookie", "rainbow-chip=2");
req.getHeaders().add("Cookie", "butterscotch=3");
req.getHeaders().add("Cookie", "oatmeal-raisin=4");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, "/guacamole");
EXPECT_EQ(callbacks_.msg->getCookie("chocolate-chip"), "1");
EXPECT_EQ(callbacks_.msg->getCookie("rainbow-chip"), "2");
EXPECT_EQ(callbacks_.msg->getCookie("butterscotch"), "3");
EXPECT_EQ(callbacks_.msg->getCookie("oatmeal-raisin"), "4");
}
TEST_F(HTTP2CodecTest, BasicContinuation) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicContinuationEndStream) {
// CONTINUATION with END_STREAM flag set on the preceding HEADERS frame
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadContinuation) {
// CONTINUATION with no preceding HEADERS
auto fakeHeaders = makeBuf(5);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, MissingContinuation) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, MissingContinuationBadFrame) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert an invalid frame
auto frame = makeBuf(http2::kFrameHeaderSize + 4134);
*((uint32_t *)frame->writableData()) = 0xfa000000;
output_.append(std::move(frame));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, BadContinuationStream) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
auto fakeHeaders = makeBuf(4134);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, FrameTooLarge) {
writeFrameHeaderManual(output_, 1 << 15, 0, 0, 1);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_TRUE(callbacks_.lastParseError->hasCodecStatusCode());
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::FRAME_SIZE_ERROR);
}
TEST_F(HTTP2CodecTest, UnknownFrameType) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// unknown frame type 17
writeFrameHeaderManual(output_, 17, 37, 0, 1);
output_.append("wicked awesome!!!");
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, ""); // + host
}
TEST_F(HTTP2CodecTest, JunkAfterConnError) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// write headers frame for stream 0
writeFrameHeaderManual(output_, 0, (uint8_t)http2::FrameType::HEADERS, 0, 0);
// now write a valid headers frame, should never be parsed
upstreamCodec_.generateHeader(output_, 1, req);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicData) {
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), data);
}
TEST_F(HTTP2CodecTest, LongData) {
// Hack the max frame size artificially low
HTTPSettings* settings = (HTTPSettings*)upstreamCodec_.getIngressSettings();
settings->setSetting(SettingsId::MAX_FRAME_SIZE, 16);
auto buf = makeBuf(100);
upstreamCodec_.generateBody(output_, 1, buf->clone(), HTTPCodec::NoPadding,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 7);
EXPECT_EQ(callbacks_.bodyLength, 100);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, MalformedPaddingLength) {
const uint8_t badInput[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x7e, 0x00, 0x6f, 0x6f, 0x6f, 0x6f,
// The padding length byte below is 0x82 (130
// in decimal) which is greater than the length
// specified by the header's length field, 126
0x01, 0x82, 0x87, 0x44, 0x87, 0x92, 0x97, 0x92,
0x92, 0x92, 0x7a, 0x0b, 0x41, 0x89, 0xf1, 0xe3,
0xc0, 0xf2, 0x9c, 0xdd, 0x90, 0xf4, 0xff, 0x40,
0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7};
output_.clear();
output_.append(badInput, sizeof(badInput));
EXPECT_EQ(output_.chainLength(), sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, MalformedPadding) {
const uint8_t badInput[] = {
0x00, 0x00, 0x0d, 0x01, 0xbe, 0x63, 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x73,
0x00, 0x00, 0x06, 0x08, 0x72, 0x00, 0x24, 0x00, 0xfa, 0x4d, 0x0d
};
output_.append(badInput, sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, NoAppByte) {
const uint8_t noAppByte[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x56, 0x00, 0x5d, 0x00, 0x00, 0x00,
0x01, 0x55, 0x00};
output_.clear();
output_.append(noAppByte, sizeof(noAppByte));
EXPECT_EQ(output_.chainLength(), sizeof(noAppByte));
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataOnFrameHeaderCall) {
using namespace testing;
NiceMock<MockHTTPCodecCallback> mockCallback;
EXPECT_CALL(mockCallback, onFrameHeader(_, _, _, _, _));
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
downstreamCodec_.setCallback(&mockCallback);
auto ingress = output_.move();
ingress->coalesce();
// Copy partial byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
downstreamCodec_.onIngress(*ingress1);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataWithNoAppByte) {
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
auto ingress = output_.move();
ingress->coalesce();
// Copy up to the padding length byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
size_t parsed = downstreamCodec_.onIngress(*ingress1);
// The 34th byte is the padding length byte which should not be parsed
EXPECT_EQ(parsed, 33);
// Copy from the padding length byte to the end
auto ingress2 = IOBuf::copyBuffer(ingress->data() + 33, 21);
parsed = downstreamCodec_.onIngress(*ingress2);
// The padding length byte should be parsed this time along with 10 bytes of
// application data and 10 bytes of padding
EXPECT_EQ(parsed, 21);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, bufSize);
// Total padding is the padding length byte and the padding bytes
EXPECT_EQ(callbacks_.paddingBytes, padding + 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, BasicRst) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicRstInvalidCode) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::_SPDY_INVALID_STREAM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicPing) {
upstreamCodec_.generatePingRequest(output_);
upstreamCodec_.generatePingReply(output_, 17);
uint64_t pingReq;
parse([&] (IOBuf* ingress) {
folly::io::Cursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
pingReq = c.read<uint64_t>();
});
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.recvPingRequest, pingReq);
EXPECT_EQ(callbacks_.recvPingReply, 17);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicWindow) {
// This test would fail if the codec had window state
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
upstreamCodec_.generateWindowUpdate(output_, 0, http2::kMaxWindowUpdateSize);
upstreamCodec_.generateWindowUpdate(output_, 1, 12);
upstreamCodec_.generateWindowUpdate(output_, 1, http2::kMaxWindowUpdateSize);
parse();
EXPECT_EQ(callbacks_.windowUpdateCalls, 4);
EXPECT_EQ(callbacks_.windowUpdates[0],
std::vector<uint32_t>({10, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.windowUpdates[1],
std::vector<uint32_t>({12, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, ZeroWindow) {
auto streamID = HTTPCodec::StreamID(1);
// First generate a frame with delta=1 so as to pass the checks, and then
// hack the frame so that delta=0 without modifying other checks
upstreamCodec_.generateWindowUpdate(output_, streamID, 1);
output_.trimEnd(http2::kFrameWindowUpdateSize);
QueueAppender appender(&output_, http2::kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(0);
parse();
// This test doesn't ensure that RST_STREAM is generated
EXPECT_EQ(callbacks_.windowUpdateCalls, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::PROTOCOL_ERROR);
}
TEST_F(HTTP2CodecTest, BasicGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_DEATH_NO_CORE(upstreamCodec_.generateGoaway(
output_, 27, ErrorCode::ENHANCE_YOUR_CALM), ".*");
}
TEST_F(HTTP2CodecTest, DoubleGoaway) {
parse();
SetUpUpstreamTest();
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::NO_ERROR);
EXPECT_TRUE(downstreamCodec_.isWaitingToDrain());
EXPECT_TRUE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
downstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parseUpstream();
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_EQ(callbacks_.goaways, 2);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parse();
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(2));
}
TEST_F(HTTP2CodecTest, DoubleGoawayWithError) {
SetUpUpstreamTest();
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
auto ret = downstreamCodec_.generateGoaway(output_, 0,
ErrorCode::NO_ERROR);
EXPECT_EQ(ret, 0);
parseUpstream();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, GoawayHandling) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
// send request
HTTPMessage req = getGetRequest();
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
EXPECT_GT(size.uncompressed, 0);
parse();
callbacks_.expectMessage(true, 1, "/");
callbacks_.reset();
SetUpUpstreamTest();
// drain after this message
downstreamCodec_.generateGoaway(output_, 1, ErrorCode::NO_ERROR);
parseUpstream();
// upstream cannot generate id > 1
upstreamCodec_.generateHeader(output_, 3, req, false, &size);
EXPECT_EQ(size.uncompressed, 0);
upstreamCodec_.generateWindowUpdate(output_, 3, 100);
upstreamCodec_.generateBody(output_, 3, makeBuf(10), HTTPCodec::NoPadding,
false);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateEOM(output_, 3);
upstreamCodec_.generateRstStream(output_, 3, ErrorCode::CANCEL);
EXPECT_EQ(output_.chainLength(), 0);
// send a push promise that will be rejected by downstream
req.getHeaders().add("foomonkey", "george");
downstreamCodec_.generatePushPromise(output_, 2, req, 1, false, &size);
EXPECT_GT(size.uncompressed, 0);
HTTPMessage resp;
resp.setStatusCode(200);
// send a push response that will be ignored
downstreamCodec_.generateHeader(output_, 2, resp, false, &size);
// window update for push doesn't make any sense, but whatever
downstreamCodec_.generateWindowUpdate(output_, 2, 100);
downstreamCodec_.generateBody(output_, 2, makeBuf(10), HTTPCodec::NoPadding,
false);
writeFrameHeaderManual(output_, 20, (uint8_t)http2::FrameType::DATA, 0, 2);
output_.append(makeBuf(10));
// tell the upstream no pushing, and parse the first batch
IOBufQueue dummy;
upstreamCodec_.generateGoaway(dummy, 0, ErrorCode::NO_ERROR);
parseUpstream();
output_.append(makeBuf(10));
downstreamCodec_.generatePriority(output_, 2,
HTTPMessage::HTTPPriority(0, true, 1));
downstreamCodec_.generateEOM(output_, 2);
downstreamCodec_.generateRstStream(output_, 2, ErrorCode::CANCEL);
// send a response that will be accepted, headers should be ok
downstreamCodec_.generateHeader(output_, 1, resp, true, &size);
EXPECT_GT(size.uncompressed, 0);
// parse the remainder
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
}
TEST_F(HTTP2CodecTest, GoawayReply) {
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
}
TEST_F(HTTP2CodecTest, BasicSetting) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS, 37);
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 12345);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.maxStreams, 37);
EXPECT_EQ(callbacks_.windowSize, 12345);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsAck) {
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.settingsAcks, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadSettings) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 0xffffffff);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BadPushSettings) {
auto settings = downstreamCodec_.getEgressSettings();
settings->clearSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 0);
SetUpUpstreamTest();
parseUpstream([&] (IOBuf* ingress) {
EXPECT_EQ(ingress->computeChainDataLength(), http2::kFrameHeaderSize);
});
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
// Only way to disable push for downstreamCodec_ is to read
// ENABLE_PUSH:0 from client
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadSettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
// This sets the max decoder table size to 8k
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
callbacks_.reset();
// Attempt to set a new max table size. This is a no-op because the first,
// setting is unacknowledged. The upstream encoder will up the table size to
// 8k per the first settings frame and the HPACK codec will send a code to
// update the decoder.
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 4096);
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSizeEarlyShrink) {
// Lower size to 2k
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 2048);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
// Parsing SETTINGS ack updates upstream decoder to 2k
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
// downstream encoder will send TSU/2k
downstreamCodec_.generateHeader(output_, 1, resp);
// sets pending table size to 512, but doesn't update it yet
settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 512);
IOBufQueue tmp{IOBufQueue::cacheChainLength()};
upstreamCodec_.generateSettings(tmp);
// Previous code would barf here, since TSU/2k is a violation of the current
// max=512
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BasicPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.priority, pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderPriority) {
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DuplicateBadHeaderPriority) {
// Sent an initial header with a circular dependency
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// Hack ingress with circular dependency.
EXPECT_TRUE(parse([&](IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
// On the same stream, send another request.
HTTPMessage nextRequest = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, nextRequest, true /* eom */);
parse();
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
class DummyQueue: public HTTPCodec::PriorityQueue {
public:
DummyQueue() {}
~DummyQueue() override {}
void addPriorityNode(HTTPCodec::StreamID id, HTTPCodec::StreamID) override {
nodes_.push_back(id);
}
std::vector<HTTPCodec::StreamID> nodes_;
};
TEST_F(HTTP2CodecTest, VirtualNodes) {
DummyQueue queue;
uint8_t level = 30;
upstreamCodec_.addPriorityNodes(queue, output_, level);
EXPECT_TRUE(parse());
for (int i = 0; i < level; i++) {
EXPECT_EQ(queue.nodes_[i], upstreamCodec_.mapPriorityToDependency(i));
}
// Out-of-range priorites are mapped to the lowest level of virtual nodes.
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level));
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level + 1));
}
TEST_F(HTTP2CodecTest, BasicPushPromise) {
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
EXPECT_FALSE(downstreamCodec_.supportsPushTransactions());
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_TRUE(upstreamCodec_.supportsPushTransactions());
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
SetUpUpstreamTest();
HTTPCodec::StreamID assocStream = 7;
for (auto i = 0; i < 2; i++) {
// Push promise
HTTPCodec::StreamID pushStream = downstreamCodec_.createStream();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, pushStream, req, assocStream);
parseUpstream();
callbacks_.expectMessage(false, 2, "/"); // + host
EXPECT_EQ(callbacks_.assocStreamId, assocStream);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
callbacks_.reset();
// Actual reply headers
HTTPMessage resp;
resp.setStatusCode(200);
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "text/plain");
downstreamCodec_.generateHeader(output_, pushStream, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("text/plain", callbacks_.msg->getHeaders().getSingleOrEmpty(
HTTP_HEADER_CONTENT_TYPE));
callbacks_.reset();
}
}
TEST_F(HTTP2CodecTest, BadPushPromise) {
// ENABLE_PUSH is now 0 by default
SetUpUpstreamTest();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicCertificateRequest) {
uint16_t requestId = 17;
std::unique_ptr<folly::IOBuf> authRequest =
folly::IOBuf::copyBuffer("authRequestData");
upstreamCodec_.generateCertificateRequest(
output_, requestId, std::move(authRequest));
parse();
EXPECT_EQ(callbacks_.certificateRequests, 1);
EXPECT_EQ(callbacks_.lastCertRequestId, requestId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authRequestData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicCertificate) {
uint16_t certId = 17;
std::unique_ptr<folly::IOBuf> authenticator =
folly::IOBuf::copyBuffer("authenticatorData");
upstreamCodec_.generateCertificate(output_, certId, std::move(authenticator));
parse();
EXPECT_EQ(callbacks_.certificates, 1);
EXPECT_EQ(callbacks_.lastCertId, certId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authenticatorData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadServerPreface) {
output_.move();
downstreamCodec_.generateWindowUpdate(output_, 0, 10);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, Normal1024Continuation) {
HTTPMessage req = getGetRequest();
string bigval(8691, '!');
bigval.append(8691, ' ');
req.getHeaders().add("x-headr", bigval);
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(bigval, headers.getSingleOrEmpty("x-headr"));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settingsAcks, 1);
}
TEST_F(HTTP2CodecTest, StreamIdOverflow) {
HTTP2Codec codec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID streamId;
codec.setNextEgressStreamId(std::numeric_limits<int32_t>::max() - 10);
while (codec.isReusable()) {
streamId = codec.createStream();
}
EXPECT_EQ(streamId, std::numeric_limits<int32_t>::max() - 2);
}
TEST_F(HTTP2CodecTest, TestMultipleDifferentContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add(HTTP_HEADER_CONTENT_LENGTH, "300");
EXPECT_EQ(req.getHeaders().getNumberOfValues(HTTP_HEADER_CONTENT_LENGTH), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the request fails before the codec finishes parsing the headers
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.lastParseError->getHttpStatusCode(), 400);
}
TEST_F(HTTP2CodecTest, TestMultipleIdenticalContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add("content-length", "200");
EXPECT_EQ(req.getHeaders().getNumberOfValues("content-length"), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the headers parsing completes correctly
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.headersComplete, 1);
}
TEST_F(HTTP2CodecTest, CleartextUpgrade) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
HTTP2Codec::requestUpgrade(req);
EXPECT_EQ(req.getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE), "h2c");
EXPECT_TRUE(req.checkForHeaderToken(HTTP_HEADER_CONNECTION,
"Upgrade", false));
EXPECT_TRUE(req.checkForHeaderToken(
HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(), false));
EXPECT_GT(
req.getHeaders().getSingleOrEmpty(http2::kProtocolSettingsHeader).length(),
0);
}
TEST_F(HTTP2CodecTest, HTTP2SettingsSuccess) {
HTTPMessage req = getGetRequest("/guacamole");
// empty settings
req.getHeaders().add(http2::kProtocolSettingsHeader, "");
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
// real settings (overwrites empty)
HTTP2Codec::requestUpgrade(req);
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2SettingsFailure) {
HTTPMessage req = getGetRequest("/guacamole");
// no settings
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
HTTPHeaders& headers = req.getHeaders();
// Not base64_url settings
headers.set(http2::kProtocolSettingsHeader, "????");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
headers.set(http2::kProtocolSettingsHeader, "AAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Too big
string bigSettings((http2::kMaxFramePayloadLength + 1) * 4 / 3, 'A');
headers.set(http2::kProtocolSettingsHeader, bigSettings);
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Malformed (not a multiple of 6)
headers.set(http2::kProtocolSettingsHeader, "AAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Two headers
headers.set(http2::kProtocolSettingsHeader, "AAAAAAAA");
headers.add(http2::kProtocolSettingsHeader, "AAAAAAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2EnableConnect) {
SetUpUpstreamTest();
// egress settings have no connect settings.
auto ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
// enable connect settings, and check.
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL, 1);
ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
EXPECT_EQ(ws_enable->value, 1);
// generateSettings.
// pass the buffer to be parsed by the codec and check for ingress settings.
upstreamCodec_.generateSettings(output_);
parseUpstream();
EXPECT_EQ(1, upstreamCodec_.peerHasWebsockets());
}
TEST_F(HTTP2CodecTest, WebsocketUpgrade) {
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
EXPECT_TRUE(callbacks_.msg->isIngressWebsocketUpgrade());
EXPECT_NE(nullptr, callbacks_.msg->getUpgradeProtocol());
EXPECT_EQ(headers::kWebsocketString, *callbacks_.msg->getUpgradeProtocol());
}
TEST_F(HTTP2CodecTest, WebsocketBadHeader) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
};
vector<proxygen::compress::Header> optionalHeaders = {
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
int stream = 1;
for (size_t i = 0; i < optionalHeaders.size(); ++i, stream += 2) {
auto headers = reqHeaders;
headers.push_back(optionalHeaders[i]);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
false,
true);
parse();
}
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, optionalHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketDupProtocol) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> headers = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
1,
folly::none,
http2::kNoPadding,
false,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketIncorrectResponse) {
parse();
SetUpUpstreamTest();
parseUpstream();
output_.clear();
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
output_.clear();
HTTPMessage resp;
resp.setStatusCode(201);
resp.setStatusMessage("OK");
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TestAllEgressFrameTypeCallbacks) {
class CallbackTypeTracker {
std::set<uint8_t> types;
public:
void add(uint8_t, uint8_t type, uint64_t, uint16_t) {
types.insert(type);
}
bool isAllFrameTypesReceived() {
http2::FrameType expectedTypes[] = {
http2::FrameType::DATA,
http2::FrameType::HEADERS,
http2::FrameType::PRIORITY,
http2::FrameType::RST_STREAM,
http2::FrameType::SETTINGS,
http2::FrameType::PUSH_PROMISE,
http2::FrameType::PING,
http2::FrameType::GOAWAY,
http2::FrameType::WINDOW_UPDATE,
http2::FrameType::CONTINUATION,
http2::FrameType::EX_HEADERS,
};
for(http2::FrameType type: expectedTypes) {
EXPECT_TRUE(types.find(static_cast<uint8_t>(type)) != types.end())
<< "callback missing for type " << static_cast<uint8_t>(type);
}
return types.size() == (sizeof(expectedTypes)/sizeof(http2::FrameType));
}
};
CallbackTypeTracker callbackTypeTracker;
NiceMock<MockHTTPCodecCallback> mockCallback;
upstreamCodec_.setCallback(&mockCallback);
downstreamCodec_.setCallback(&mockCallback);
EXPECT_CALL(mockCallback, onGenerateFrameHeader(_, _, _, _)).
WillRepeatedly(Invoke(&callbackTypeTracker, &CallbackTypeTracker::add));
// DATA frame
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
HTTPMessage req = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
upstreamCodec_.generateSettings(output_);
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
upstreamCodec_.generatePingRequest(output_);
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true));
// Tests the continuation frame
req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
EXPECT_TRUE(callbackTypeTracker.isAllFrameTypesReceived());
}
TEST_F(HTTP2CodecTest, Trailers) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersWithPseudoHeaders) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TrailersNoBody) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, TrailersContinuation) {
HTTPMessage req = getGetRequest("/guacamole");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(callbacks_.msg->getTrailers(), nullptr);
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-trailer-2", "chicken-kyiv");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ("chicken-kyiv",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-2"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithNoData) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithPseudoHeaders) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, TrailersReplyContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.msg->getStatusCode(), 200);
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyMissingContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4132);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersNotLatest) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
upstreamCodec_.generateHeader(output_, 3, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
upstreamCodec_.generateHeader(output_, 3, req);
parse();
EXPECT_EQ(callbacks_.messageBegin, 2);
EXPECT_EQ(callbacks_.headersComplete, 2);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_600_1 |
crossvul-cpp_data_good_1580_4 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: ParaNdis6-Impl.c
*
* This file contains NDIS6-specific implementation of driver's procedures.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ParaNdis6.h"
static MINIPORT_DISABLE_INTERRUPT MiniportDisableInterruptEx;
static MINIPORT_ENABLE_INTERRUPT MiniportEnableInterruptEx;
static MINIPORT_INTERRUPT_DPC MiniportInterruptDPC;
static MINIPORT_ISR MiniportInterrupt;
static MINIPORT_ENABLE_MESSAGE_INTERRUPT MiniportEnableMSIInterrupt;
static MINIPORT_DISABLE_MESSAGE_INTERRUPT MiniportDisableMSIInterrupt;
static MINIPORT_MESSAGE_INTERRUPT MiniportMSIInterrupt;
static MINIPORT_MESSAGE_INTERRUPT_DPC MiniportMSIInterruptDpc;
static MINIPORT_PROCESS_SG_LIST ProcessSGListHandler;
static MINIPORT_ALLOCATE_SHARED_MEM_COMPLETE SharedMemAllocateCompleteHandler;
static MINIPORT_PROCESS_SG_LIST ProcessSGListHandler;
/**********************************************************
Implements general-purpose memory allocation routine
Parameters:
ULONG ulRequiredSize: block size
Return value:
PVOID allocated memory block
NULL on error
***********************************************************/
PVOID ParaNdis_AllocateMemoryRaw(NDIS_HANDLE MiniportHandle, ULONG ulRequiredSize)
{
return NdisAllocateMemoryWithTagPriority(
MiniportHandle,
ulRequiredSize,
PARANDIS_MEMORY_TAG,
NormalPoolPriority);
}
PVOID ParaNdis_AllocateMemory(PARANDIS_ADAPTER *pContext, ULONG ulRequiredSize)
{
return ParaNdis_AllocateMemoryRaw(pContext->MiniportHandle, ulRequiredSize);
}
/**********************************************************
Implements opening of adapter-specific configuration
Parameters:
Return value:
NDIS_HANDLE Handle of open configuration
NULL on error
***********************************************************/
NDIS_HANDLE ParaNdis_OpenNICConfiguration(PARANDIS_ADAPTER *pContext)
{
NDIS_CONFIGURATION_OBJECT co;
NDIS_HANDLE cfg;
NDIS_STATUS status;
DEBUG_ENTRY(2);
co.Header.Type = NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT;
co.Header.Revision = NDIS_CONFIGURATION_OBJECT_REVISION_1;
co.Header.Size = sizeof(co);
co.Flags = 0;
co.NdisHandle = pContext->MiniportHandle;
status = NdisOpenConfigurationEx(&co, &cfg);
if (status != NDIS_STATUS_SUCCESS)
cfg = NULL;
DEBUG_EXIT_STATUS(status == NDIS_STATUS_SUCCESS ? 2 : 0, status);
return cfg;
}
/**********************************************************
NDIS6 implementation of shared memory allocation
Parameters:
context
tCompletePhysicalAddress *pAddresses
the structure accumulates all our knowledge
about the allocation (size, addresses, cacheability etc)
Return value:
TRUE if the allocation was successful
***********************************************************/
BOOLEAN ParaNdis_InitialAllocatePhysicalMemory(
PARANDIS_ADAPTER *pContext,
tCompletePhysicalAddress *pAddresses)
{
NdisMAllocateSharedMemory(
pContext->MiniportHandle,
pAddresses->size,
TRUE,
&pAddresses->Virtual,
&pAddresses->Physical);
return pAddresses->Virtual != NULL;
}
/**********************************************************
NDIS6 implementation of shared memory freeing
Parameters:
context
tCompletePhysicalAddress *pAddresses
the structure accumulates all our knowledge
about the allocation (size, addresses, cacheability etc)
filled by ParaNdis_InitialAllocatePhysicalMemory or
by ParaNdis_RuntimeRequestToAllocatePhysicalMemory
***********************************************************/
VOID ParaNdis_FreePhysicalMemory(
PARANDIS_ADAPTER *pContext,
tCompletePhysicalAddress *pAddresses)
{
NdisMFreeSharedMemory(
pContext->MiniportHandle,
pAddresses->size,
TRUE,
pAddresses->Virtual,
pAddresses->Physical);
}
#if (NDIS_SUPPORT_NDIS620)
typedef MINIPORT_SYNCHRONIZE_INTERRUPT_HANDLER NDIS_SYNC_PROC_TYPE;
#else
typedef PVOID NDIS_SYNC_PROC_TYPE;
#endif
BOOLEAN ParaNdis_SynchronizeWithInterrupt(
PARANDIS_ADAPTER *pContext,
ULONG messageId,
tSynchronizedProcedure procedure,
PVOID parameter)
{
tSynchronizedContext SyncContext;
NDIS_SYNC_PROC_TYPE syncProc;
#pragma warning (push)
#pragma warning (disable:4152)
syncProc = (NDIS_SYNC_PROC_TYPE) procedure;
#pragma warning (pop)
SyncContext.pContext = pContext;
SyncContext.Parameter = parameter;
return NdisMSynchronizeWithInterruptEx(pContext->InterruptHandle, messageId, syncProc, &SyncContext);
}
/**********************************************************
NDIS-required procedure for hardware interrupt registration
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
***********************************************************/
static VOID MiniportDisableInterruptEx(IN PVOID MiniportInterruptContext)
{
DEBUG_ENTRY(0);
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
/* TODO - make sure that interrups are not reenabled by the DPC callback*/
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.DisableInterrupts();
pContext->pPathBundles[i].rxPath.DisableInterrupts();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.DisableInterrupts();
}
}
/**********************************************************
NDIS-required procedure for hardware interrupt registration
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
***********************************************************/
static VOID MiniportEnableInterruptEx(IN PVOID MiniportInterruptContext)
{
DEBUG_ENTRY(0);
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.EnableInterrupts();
pContext->pPathBundles[i].rxPath.EnableInterrupts();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.EnableInterrupts();
}
}
/**********************************************************
NDIS-required procedure for hardware interrupt handling
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
OUT PBOOLEAN QueueDefaultInterruptDpc - set to TRUE for default DPC spawning
OUT PULONG TargetProcessors
Return value:
TRUE if recognized
***********************************************************/
static BOOLEAN MiniportInterrupt(
IN PVOID MiniportInterruptContext,
OUT PBOOLEAN QueueDefaultInterruptDpc,
OUT PULONG TargetProcessors
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
ULONG status = VirtIODeviceISR(pContext->IODevice);
*TargetProcessors = 0;
if((status == 0) ||
(status == VIRTIO_NET_INVALID_INTERRUPT_STATUS))
{
*QueueDefaultInterruptDpc = FALSE;
return FALSE;
}
PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext);
if(!pContext->bDeviceInitialized) {
*QueueDefaultInterruptDpc = FALSE;
return TRUE;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.DisableInterrupts();
pContext->pPathBundles[i].rxPath.DisableInterrupts();
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.DisableInterrupts();
}
*QueueDefaultInterruptDpc = TRUE;
pContext->ulIrqReceived += 1;
return true;
}
static CParaNdisAbstractPath *GetPathByMessageId(PARANDIS_ADAPTER *pContext, ULONG MessageId)
{
CParaNdisAbstractPath *path = NULL;
UINT bundleId = MessageId / 2;
if (bundleId >= pContext->nPathBundles)
{
path = &pContext->CXPath;
}
else if (MessageId % 2)
{
path = &(pContext->pPathBundles[bundleId].rxPath);
}
else
{
path = &(pContext->pPathBundles[bundleId].txPath);
}
return path;
}
/**********************************************************
NDIS-required procedure for MSI hardware interrupt handling
Parameters:
IN PVOID MiniportInterruptContext (actually Adapter context)
IN ULONG MessageId - specific interrupt index
OUT PBOOLEAN QueueDefaultInterruptDpc - - set to TRUE for default DPC spawning
OUT PULONG TargetProcessors
Return value:
TRUE if recognized
***********************************************************/
static BOOLEAN MiniportMSIInterrupt(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId,
OUT PBOOLEAN QueueDefaultInterruptDpc,
OUT PULONG TargetProcessors
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext);
*TargetProcessors = 0;
if (!pContext->bDeviceInitialized) {
*QueueDefaultInterruptDpc = FALSE;
return TRUE;
}
CParaNdisAbstractPath *path = GetPathByMessageId(pContext, MessageId);
path->DisableInterrupts();
path->ReportInterrupt();
#if NDIS_SUPPORT_NDIS620
if (path->DPCAffinity.Mask)
{
NdisMQueueDpcEx(pContext->InterruptHandle, MessageId, &path->DPCAffinity, NULL);
*QueueDefaultInterruptDpc = FALSE;
}
else
{
*QueueDefaultInterruptDpc = TRUE;
}
#else
*TargetProcessors = (ULONG)path->DPCTargetProcessor;
*QueueDefaultInterruptDpc = TRUE;
#endif
pContext->ulIrqReceived += 1;
return true;
}
#if NDIS_SUPPORT_NDIS620
static __inline
VOID GetAffinityForCurrentCpu(PGROUP_AFFINITY pAffinity)
{
PROCESSOR_NUMBER ProcNum;
KeGetCurrentProcessorNumberEx(&ProcNum);
pAffinity->Group = ProcNum.Group;
pAffinity->Mask = 1;
pAffinity->Mask <<= ProcNum.Number;
}
#endif
/**********************************************************
NDIS-required procedure for DPC handling
Parameters:
PVOID MiniportInterruptContext (Adapter context)
***********************************************************/
static VOID MiniportInterruptDPC(
IN NDIS_HANDLE MiniportInterruptContext,
IN PVOID MiniportDpcContext,
IN PVOID ReceiveThrottleParameters,
IN PVOID NdisReserved2
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
bool requiresDPCRescheduling;
#if NDIS_SUPPORT_NDIS620
PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters;
DEBUG_ENTRY(5);
RxThrottleParameters->MoreNblsPending = 0;
requiresDPCRescheduling = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate);
if (requiresDPCRescheduling)
{
GROUP_AFFINITY Affinity;
GetAffinityForCurrentCpu(&Affinity);
NdisMQueueDpcEx(pContext->InterruptHandle, 0, &Affinity, MiniportDpcContext);
}
#else /* NDIS 6.0*/
DEBUG_ENTRY(5);
UNREFERENCED_PARAMETER(ReceiveThrottleParameters);
requiresDPCRescheduling = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
if (requiresDPCRescheduling)
{
DPrintf(4, ("[%s] Queued additional DPC for %d\n", __FUNCTION__, requiresDPCRescheduling));
NdisMQueueDpc(pContext->InterruptHandle, 0, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext);
}
#endif /* NDIS_SUPPORT_NDIS620 */
UNREFERENCED_PARAMETER(NdisReserved2);
}
/**********************************************************
NDIS-required procedure for MSI DPC handling
Parameters:
PVOID MiniportInterruptContext (Adapter context)
IN ULONG MessageId - specific interrupt index
***********************************************************/
static VOID MiniportMSIInterruptDpc(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId,
IN PVOID MiniportDpcContext,
#if NDIS_SUPPORT_NDIS620
IN PVOID ReceiveThrottleParameters,
IN PVOID NdisReserved2
#else
IN PULONG NdisReserved1,
IN PULONG NdisReserved2
#endif
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
bool requireDPCRescheduling;
#if NDIS_SUPPORT_NDIS620
PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters;
RxThrottleParameters->MoreNblsPending = 0;
requireDPCRescheduling = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate);
if (requireDPCRescheduling)
{
GROUP_AFFINITY Affinity;
GetAffinityForCurrentCpu(&Affinity);
NdisMQueueDpcEx(pContext->InterruptHandle, MessageId, &Affinity, MiniportDpcContext);
}
#else
UNREFERENCED_PARAMETER(NdisReserved1);
requireDPCRescheduling = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
if (requireDPCRescheduling)
{
NdisMQueueDpc(pContext->InterruptHandle, MessageId, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext);
}
#endif
UNREFERENCED_PARAMETER(NdisReserved2);
}
static VOID MiniportDisableMSIInterrupt(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
/* TODO - How we prevent DPC procedure from re-enabling interrupt? */
CParaNdisAbstractPath *path = GetPathByMessageId(pContext, MessageId);
path->DisableInterrupts();
}
static VOID MiniportEnableMSIInterrupt(
IN PVOID MiniportInterruptContext,
IN ULONG MessageId
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext;
CParaNdisAbstractPath *path = GetPathByMessageId(pContext, MessageId);
path->EnableInterrupts();
}
/**********************************************************
NDIS required handler for run-time allocation of physical memory
Parameters:
Return value:
***********************************************************/
static VOID SharedMemAllocateCompleteHandler(
IN NDIS_HANDLE MiniportAdapterContext,
IN PVOID VirtualAddress,
IN PNDIS_PHYSICAL_ADDRESS PhysicalAddress,
IN ULONG Length,
IN PVOID Context
)
{
UNREFERENCED_PARAMETER(MiniportAdapterContext);
UNREFERENCED_PARAMETER(VirtualAddress);
UNREFERENCED_PARAMETER(PhysicalAddress);
UNREFERENCED_PARAMETER(Length);
UNREFERENCED_PARAMETER(Context);
}
NDIS_STATUS ParaNdis_ConfigureMSIXVectors(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_RESOURCES;
UINT i;
PIO_INTERRUPT_MESSAGE_INFO pTable = pContext->pMSIXInfoTable;
if (pTable && pTable->MessageCount)
{
status = NDIS_STATUS_SUCCESS;
DPrintf(0, ("[%s] Using MSIX interrupts (%d messages, irql %d)\n",
__FUNCTION__, pTable->MessageCount, pTable->UnifiedIrql));
for (i = 0; i < pContext->pMSIXInfoTable->MessageCount; ++i)
{
DPrintf(0, ("[%s] MSIX message%d=%08X=>%I64X\n",
__FUNCTION__, i,
pTable->MessageInfo[i].MessageData,
pTable->MessageInfo[i].MessageAddress));
}
for (UINT j = 0; j < pContext->nPathBundles && status == NDIS_STATUS_SUCCESS; ++j)
{
status = pContext->pPathBundles[j].rxPath.SetupMessageIndex(2 * u16(j) + 1);
status = pContext->pPathBundles[j].txPath.SetupMessageIndex(2 * u16(j));
}
if (pContext->bCXPathCreated)
{
pContext->CXPath.SetupMessageIndex(2 * u16(pContext->nPathBundles));
}
}
if (status == NDIS_STATUS_SUCCESS)
{
for (UINT j = 0; j < pContext->nPathBundles && status == NDIS_STATUS_SUCCESS; ++j)
{
DPrintf(0, ("[%s] Using messages %u/%u for RX/TX queue %u\n", __FUNCTION__, pContext->pPathBundles[j].rxPath.getMessageIndex(),
pContext->pPathBundles[j].txPath.getMessageIndex(), j));
}
if (pContext->bCXPathCreated)
{
DPrintf(0, ("[%s] Using message %u for controls\n", __FUNCTION__, pContext->CXPath.getMessageIndex()));
}
else
{
DPrintf(0, ("[%s] - No control path\n", __FUNCTION__));
}
}
DEBUG_EXIT_STATUS(2, status);
return status;
}
void ParaNdis_RestoreDeviceConfigurationAfterReset(
PARANDIS_ADAPTER *pContext)
{
ParaNdis_ConfigureMSIXVectors(pContext);
}
static void DebugParseOffloadBits()
{
NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO info;
tChecksumCheckResult res;
ULONG val = 1;
int level = 1;
while (val)
{
info.Value = (PVOID)(ULONG_PTR)val;
if (info.Receive.IpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed\n", val));
if (info.Receive.IpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK\n", val));
if (info.Receive.TcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed\n", val));
if (info.Receive.TcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK\n", val));
if (info.Receive.UdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed\n", val));
if (info.Receive.UdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK\n", val));
val = val << 1;
}
val = 1;
while (val)
{
res.value = val;
if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed\n", val));
if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK\n", val));
if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed\n", val));
if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK\n", val));
if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed\n", val));
if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK\n", val));
val = val << 1;
}
}
/**********************************************************
NDIS6-related final initialization:
Installing interrupt handler
Allocate buffer list pool
Parameters:
Return value:
***********************************************************/
NDIS_STATUS ParaNdis_FinishSpecificInitialization(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
NET_BUFFER_LIST_POOL_PARAMETERS PoolParams;
NDIS_MINIPORT_INTERRUPT_CHARACTERISTICS mic;
DEBUG_ENTRY(0);
NdisZeroMemory(&mic, sizeof(mic));
mic.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT;
mic.Header.Revision = NDIS_MINIPORT_INTERRUPT_REVISION_1;
mic.Header.Size = NDIS_SIZEOF_MINIPORT_INTERRUPT_CHARACTERISTICS_REVISION_1;
mic.DisableInterruptHandler = MiniportDisableInterruptEx;
mic.EnableInterruptHandler = MiniportEnableInterruptEx;
mic.InterruptDpcHandler = MiniportInterruptDPC;
mic.InterruptHandler = MiniportInterrupt;
if (pContext->bUsingMSIX)
{
mic.MsiSupported = TRUE;
mic.MsiSyncWithAllMessages = TRUE;
mic.EnableMessageInterruptHandler = MiniportEnableMSIInterrupt;
mic.DisableMessageInterruptHandler = MiniportDisableMSIInterrupt;
mic.MessageInterruptHandler = MiniportMSIInterrupt;
mic.MessageInterruptDpcHandler = MiniportMSIInterruptDpc;
}
PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
PoolParams.Header.Size = sizeof(PoolParams);
PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT;
PoolParams.fAllocateNetBuffer = TRUE;
PoolParams.ContextSize = 0;
PoolParams.PoolTag = PARANDIS_MEMORY_TAG;
PoolParams.DataSize = 0;
pContext->BufferListsPool = NdisAllocateNetBufferListPool(pContext->MiniportHandle, &PoolParams);
if (!pContext->BufferListsPool)
{
status = NDIS_STATUS_RESOURCES;
}
if (status == NDIS_STATUS_SUCCESS)
{
status = NdisMRegisterInterruptEx(pContext->MiniportHandle, pContext, &mic, &pContext->InterruptHandle);
}
#ifdef DBG
if (pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] MSIX message table %savailable, count = %u\n", __FUNCTION__, (mic.MessageInfoTable == nullptr ? "not " : ""),
(mic.MessageInfoTable == nullptr ? 0 : mic.MessageInfoTable->MessageCount)));
}
else
{
DPrintf(0, ("[%s] Not using MSIX\n", __FUNCTION__));
}
#endif
if (status == NDIS_STATUS_SUCCESS)
{
NDIS_SG_DMA_DESCRIPTION sgDesc;
sgDesc.Header.Type = NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION;
sgDesc.Header.Revision = NDIS_SG_DMA_DESCRIPTION_REVISION_1;
sgDesc.Header.Size = sizeof(sgDesc);
sgDesc.Flags = NDIS_SG_DMA_64_BIT_ADDRESS;
sgDesc.MaximumPhysicalMapping = 0x10000; // 64K
sgDesc.ProcessSGListHandler = ProcessSGListHandler;
sgDesc.SharedMemAllocateCompleteHandler = SharedMemAllocateCompleteHandler;
sgDesc.ScatterGatherListSize = 0; // OUT value
status = NdisMRegisterScatterGatherDma(pContext->MiniportHandle, &sgDesc, &pContext->DmaHandle);
if (status != NDIS_STATUS_SUCCESS)
{
DPrintf(0, ("[%s] ERROR: NdisMRegisterScatterGatherDma failed (%X)!\n", __FUNCTION__, status));
}
else
{
DPrintf(0, ("[%s] SG recommended size %d\n", __FUNCTION__, sgDesc.ScatterGatherListSize));
}
}
if (status == NDIS_STATUS_SUCCESS)
{
if (NDIS_CONNECT_MESSAGE_BASED == mic.InterruptType)
{
pContext->pMSIXInfoTable = mic.MessageInfoTable;
}
else if (pContext->bUsingMSIX)
{
DPrintf(0, ("[%s] ERROR: Interrupt type %d, message table %p\n",
__FUNCTION__, mic.InterruptType, mic.MessageInfoTable));
status = NDIS_STATUS_RESOURCE_CONFLICT;
}
ParaNdis6_ApplyOffloadPersistentConfiguration(pContext);
DebugParseOffloadBits();
}
DEBUG_EXIT_STATUS(0, status);
return status;
}
/**********************************************************
NDIS6-related final initialization:
Uninstalling interrupt handler
Dellocate buffer list pool
Parameters:
context
***********************************************************/
VOID ParaNdis_FinalizeCleanup(PARANDIS_ADAPTER *pContext)
{
// we zero context members to be able examine them in the debugger/dump
if (pContext->InterruptHandle)
{
NdisMDeregisterInterruptEx(pContext->InterruptHandle);
pContext->InterruptHandle = NULL;
}
if (pContext->BufferListsPool)
{
NdisFreeNetBufferListPool(pContext->BufferListsPool);
pContext->BufferListsPool = NULL;
}
if (pContext->DmaHandle)
{
NdisMDeregisterScatterGatherDma(pContext->DmaHandle);
pContext->DmaHandle = NULL;
}
}
BOOLEAN ParaNdis_BindRxBufferToPacket(
PARANDIS_ADAPTER *pContext,
pRxNetDescriptor p)
{
ULONG i;
PMDL *NextMdlLinkage = &p->Holder;
for(i = PARANDIS_FIRST_RX_DATA_PAGE; i < p->PagesAllocated; i++)
{
*NextMdlLinkage = NdisAllocateMdl(pContext->MiniportHandle, p->PhysicalPages[i].Virtual, PAGE_SIZE);
if(*NextMdlLinkage == NULL) goto error_exit;
NextMdlLinkage = &(NDIS_MDL_LINKAGE(*NextMdlLinkage));
}
*NextMdlLinkage = NULL;
return TRUE;
error_exit:
ParaNdis_UnbindRxBufferFromPacket(p);
return FALSE;
}
void ParaNdis_UnbindRxBufferFromPacket(
pRxNetDescriptor p)
{
PMDL NextMdlLinkage = p->Holder;
while(NextMdlLinkage != NULL)
{
PMDL pThisMDL = NextMdlLinkage;
NextMdlLinkage = NDIS_MDL_LINKAGE(pThisMDL);
NdisAdjustMdlLength(pThisMDL, PAGE_SIZE);
NdisFreeMdl(pThisMDL);
}
}
static
void ParaNdis_AdjustRxBufferHolderLength(
pRxNetDescriptor p,
ULONG ulDataOffset)
{
PMDL NextMdlLinkage = p->Holder;
ULONG ulBytesLeft = p->PacketInfo.dataLength + ulDataOffset;
while(NextMdlLinkage != NULL)
{
ULONG ulThisMdlBytes = min(PAGE_SIZE, ulBytesLeft);
NdisAdjustMdlLength(NextMdlLinkage, ulThisMdlBytes);
ulBytesLeft -= ulThisMdlBytes;
NextMdlLinkage = NDIS_MDL_LINKAGE(NextMdlLinkage);
}
ASSERT(ulBytesLeft == 0);
}
static __inline
VOID NBLSetRSSInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO PacketInfo)
{
#if PARANDIS_SUPPORT_RSS
CNdisRWLockState lockState;
pContext->RSSParameters.rwLock.acquireReadDpr(lockState);
if(pContext->RSSParameters.RSSMode != PARANDIS_RSS_DISABLED)
{
NET_BUFFER_LIST_SET_HASH_TYPE (pNBL, PacketInfo->RSSHash.Type);
NET_BUFFER_LIST_SET_HASH_FUNCTION(pNBL, PacketInfo->RSSHash.Function);
NET_BUFFER_LIST_SET_HASH_VALUE (pNBL, PacketInfo->RSSHash.Value);
}
pContext->RSSParameters.rwLock.releaseDpr(lockState);
#else
UNREFERENCED_PARAMETER(pContext);
UNREFERENCED_PARAMETER(pNBL);
UNREFERENCED_PARAMETER(PacketInfo);
#endif
}
static __inline
VOID NBLSet8021QInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO pPacketInfo)
{
NDIS_NET_BUFFER_LIST_8021Q_INFO qInfo;
qInfo.Value = NULL;
if (IsPrioritySupported(pContext))
qInfo.TagHeader.UserPriority = pPacketInfo->Vlan.UserPriority;
if (IsVlanSupported(pContext))
qInfo.TagHeader.VlanId = pPacketInfo->Vlan.VlanId;
if(qInfo.Value != NULL)
pContext->extraStatistics.framesRxPriority++;
NET_BUFFER_LIST_INFO(pNBL, Ieee8021QNetBufferListInfo) = qInfo.Value;
}
#if PARANDIS_SUPPORT_RSC
static __inline
UINT PktGetTCPCoalescedSegmentsCount(PNET_PACKET_INFO PacketInfo, UINT nMaxTCPPayloadSize)
{
// We have no corresponding data, following is a simulation
return PacketInfo->L2PayloadLen / nMaxTCPPayloadSize +
!!(PacketInfo->L2PayloadLen % nMaxTCPPayloadSize);
}
static __inline
VOID NBLSetRSCInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL,
PNET_PACKET_INFO PacketInfo, UINT nCoalescedSegments)
{
NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;
qCSInfo.Value = NULL;
qCSInfo.Receive.IpChecksumSucceeded = TRUE;
qCSInfo.Receive.IpChecksumValueInvalid = TRUE;
qCSInfo.Receive.TcpChecksumSucceeded = TRUE;
qCSInfo.Receive.TcpChecksumValueInvalid = TRUE;
NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value;
NET_BUFFER_LIST_COALESCED_SEG_COUNT(pNBL) = (USHORT) nCoalescedSegments;
NET_BUFFER_LIST_DUP_ACK_COUNT(pNBL) = 0;
NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedOctets, PacketInfo->L2PayloadLen);
NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalesceEvents, 1);
NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedPkts, nCoalescedSegments);
}
#endif
/**********************************************************
NDIS6 implementation of packet indication
Parameters:
context
PVOID pBuffersDescriptor - VirtIO buffer descriptor of data buffer
BOOLEAN bPrepareOnly - only return NBL for further indication in batch
Return value:
TRUE is packet indicated
FALSE if not (in this case, the descriptor should be freed now)
If priority header is in the packet. it will be removed and *pLength decreased
***********************************************************/
tPacketIndicationType ParaNdis_PrepareReceivedPacket(
PARANDIS_ADAPTER *pContext,
pRxNetDescriptor pBuffersDesc,
PUINT pnCoalescedSegmentsCount)
{
PMDL pMDL = pBuffersDesc->Holder;
PNET_BUFFER_LIST pNBL = NULL;
*pnCoalescedSegmentsCount = 1;
if (pMDL)
{
ULONG nBytesStripped = 0;
PNET_PACKET_INFO pPacketInfo = &pBuffersDesc->PacketInfo;
if (pContext->ulPriorityVlanSetting && pPacketInfo->hasVlanHeader)
{
nBytesStripped = ParaNdis_StripVlanHeaderMoveHead(pPacketInfo);
}
ParaNdis_PadPacketToMinimalLength(pPacketInfo);
ParaNdis_AdjustRxBufferHolderLength(pBuffersDesc, nBytesStripped);
pNBL = NdisAllocateNetBufferAndNetBufferList(pContext->BufferListsPool, 0, 0, pMDL, nBytesStripped, pPacketInfo->dataLength);
if (pNBL)
{
virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *) pBuffersDesc->PhysicalPages[0].Virtual;
tChecksumCheckResult csRes;
pNBL->SourceHandle = pContext->MiniportHandle;
NBLSetRSSInfo(pContext, pNBL, pPacketInfo);
NBLSet8021QInfo(pContext, pNBL, pPacketInfo);
pNBL->MiniportReserved[0] = pBuffersDesc;
#if PARANDIS_SUPPORT_RSC
if(pHeader->gso_type != VIRTIO_NET_HDR_GSO_NONE)
{
*pnCoalescedSegmentsCount = PktGetTCPCoalescedSegmentsCount(pPacketInfo, pContext->MaxPacketSize.nMaxDataSize);
NBLSetRSCInfo(pContext, pNBL, pPacketInfo, *pnCoalescedSegmentsCount);
}
else
#endif
{
csRes = ParaNdis_CheckRxChecksum(
pContext,
pHeader->flags,
&pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE],
pPacketInfo->dataLength,
nBytesStripped, TRUE);
if (csRes.value)
{
NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;
qCSInfo.Value = NULL;
qCSInfo.Receive.IpChecksumFailed = csRes.flags.IpFailed;
qCSInfo.Receive.IpChecksumSucceeded = csRes.flags.IpOK;
qCSInfo.Receive.TcpChecksumFailed = csRes.flags.TcpFailed;
qCSInfo.Receive.TcpChecksumSucceeded = csRes.flags.TcpOK;
qCSInfo.Receive.UdpChecksumFailed = csRes.flags.UdpFailed;
qCSInfo.Receive.UdpChecksumSucceeded = csRes.flags.UdpOK;
NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value;
DPrintf(1, ("Reporting CS %X->%X\n", csRes.value, (ULONG)(ULONG_PTR)qCSInfo.Value));
}
}
pNBL->Status = NDIS_STATUS_SUCCESS;
#if defined(ENABLE_HISTORY_LOG)
{
tTcpIpPacketParsingResult packetReview = ParaNdis_CheckSumVerify(
RtlOffsetToPointer(pPacketInfo->headersBuffer, ETH_HEADER_SIZE),
pPacketInfo->dataLength,
pcrIpChecksum | pcrTcpChecksum | pcrUdpChecksum,
__FUNCTION__
);
ParaNdis_DebugHistory(pContext, hopPacketReceived, pNBL, pPacketInfo->dataLength, (ULONG)(ULONG_PTR)qInfo.Value, packetReview.value);
}
#endif
}
}
return pNBL;
}
/**********************************************************
NDIS procedure of returning us buffer of previously indicated packets
Parameters:
context
PNET_BUFFER_LIST pNBL - list of buffers to free
returnFlags - is dpc
The procedure frees:
received buffer descriptors back to list of RX buffers
all the allocated MDL structures
all the received NBLs back to our pool
***********************************************************/
VOID ParaNdis6_ReturnNetBufferLists(
NDIS_HANDLE miniportAdapterContext,
PNET_BUFFER_LIST pNBL,
ULONG returnFlags)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext;
UNREFERENCED_PARAMETER(returnFlags);
DEBUG_ENTRY(5);
while (pNBL)
{
PNET_BUFFER_LIST pTemp = pNBL;
pRxNetDescriptor pBuffersDescriptor = (pRxNetDescriptor)pNBL->MiniportReserved[0];
DPrintf(3, (" Returned NBL of pBuffersDescriptor %p!\n", pBuffersDescriptor));
pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL);
NET_BUFFER_LIST_NEXT_NBL(pTemp) = NULL;
NdisFreeNetBufferList(pTemp);
pBuffersDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBuffersDescriptor);
}
ParaMdis_TestPausing(pContext);
}
/**********************************************************
Pauses of restarts RX activity.
Restart is immediate, pause may be delayed until
NDIS returns all the indicated NBL
Parameters:
context
bPause 1/0 - pause or restart
ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished
Return value:
SUCCESS if finished synchronously
PENDING if not, then callback will be called
***********************************************************/
NDIS_STATUS ParaNdis6_ReceivePauseRestart(
PARANDIS_ADAPTER *pContext,
BOOLEAN bPause,
ONPAUSECOMPLETEPROC Callback
)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
if (bPause)
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0);
if (pContext->m_upstreamPacketPending != 0)
{
pContext->ReceiveState = srsPausing;
pContext->ReceivePauseCompletionProc = Callback;
status = NDIS_STATUS_PENDING;
}
else
{
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
pContext->ReceiveState = srsDisabled;
}
}
else
{
ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0);
pContext->ReceiveState = srsEnabled;
}
return status;
}
NDIS_STATUS ParaNdis_ExactSendFailureStatus(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status = NDIS_STATUS_FAILURE;
if (pContext->SendState != srsEnabled ) status = NDIS_STATUS_PAUSED;
if (!pContext->bConnected) status = NDIS_STATUS_MEDIA_DISCONNECTED;
if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED;
// override NDIS_STATUS_PAUSED is there is a specific reason of implicit paused state
if (pContext->powerState != NdisDeviceStateD0) status = NDIS_STATUS_LOW_POWER_STATE;
if (pContext->bResetInProgress) status = NDIS_STATUS_RESET_IN_PROGRESS;
return status;
}
BOOLEAN ParaNdis_IsSendPossible(PARANDIS_ADAPTER *pContext)
{
BOOLEAN b;
b = !pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled;
return b;
}
/**********************************************************
NDIS required handler for run-time allocation of scatter-gather list
Parameters:
pSGL - scatter-hather list of elements (possible NULL when called directly)
Context - (tNetBufferEntry *) for specific NET_BUFFER in NBL
Called on DPC (DDK claims it)
***********************************************************/
VOID ProcessSGListHandler(
IN PDEVICE_OBJECT pDO,
IN PVOID Reserved,
IN PSCATTER_GATHER_LIST pSGL,
IN PVOID Context
)
{
UNREFERENCED_PARAMETER(Reserved);
UNREFERENCED_PARAMETER(pDO);
auto NBHolder = static_cast<CNB*>(Context);
NBHolder->MappingDone(pSGL);
}
/**********************************************************
Pauses of restarts TX activity.
Restart is immediate, pause may be delayed until
we return all the NBLs to NDIS
Parameters:
context
bPause 1/0 - pause or restart
ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished
Return value:
SUCCESS if finished synchronously
PENDING if not, then callback will be called later
***********************************************************/
NDIS_STATUS ParaNdis6_SendPauseRestart(
PARANDIS_ADAPTER *pContext,
BOOLEAN bPause,
ONPAUSECOMPLETEPROC Callback
)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
DEBUG_ENTRY(4);
if (bPause)
{
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0);
if (pContext->SendState == srsEnabled)
{
{
CNdisPassiveWriteAutoLock tLock(pContext->m_PauseLock);
pContext->SendState = srsPausing;
pContext->SendPauseCompletionProc = Callback;
}
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
if (!pContext->pPathBundles[i].txPath.Pause())
{
status = NDIS_STATUS_PENDING;
}
}
if (status == NDIS_STATUS_SUCCESS)
{
pContext->SendState = srsDisabled;
}
}
if (status == NDIS_STATUS_SUCCESS)
{
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0);
}
}
else
{
pContext->SendState = srsEnabled;
ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0);
}
return status;
}
/**********************************************************
Required procedure of NDIS
NDIS wants to cancel sending of each list which has specified CancelID
Can be tested only under NDIS Test
***********************************************************/
VOID ParaNdis6_CancelSendNetBufferLists(
NDIS_HANDLE miniportAdapterContext,
PVOID pCancelId)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext;
DEBUG_ENTRY(0);
for (UINT i = 0; i < pContext->nPathBundles; i++)
{
pContext->pPathBundles[i].txPath.CancelNBLs(pCancelId);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1580_4 |
crossvul-cpp_data_bad_1580_1 | #include "ndis56common.h"
CNBL::CNBL(PNET_BUFFER_LIST NBL, PPARANDIS_ADAPTER Context, CParaNdisTX &ParentTXPath)
: m_NBL(NBL)
, m_Context(Context)
, m_ParentTXPath(&ParentTXPath)
{
m_NBL->Scratch = this;
m_LsoInfo.Value = NET_BUFFER_LIST_INFO(m_NBL, TcpLargeSendNetBufferListInfo);
m_CsoInfo.Value = NET_BUFFER_LIST_INFO(m_NBL, TcpIpChecksumNetBufferListInfo);
}
CNBL::~CNBL()
{
CDpcIrqlRaiser OnDpc;
m_MappedBuffers.ForEachDetached([this](CNB *NB)
{ CNB::Destroy(NB, m_Context->MiniportHandle); });
m_Buffers.ForEachDetached([this](CNB *NB)
{ CNB::Destroy(NB, m_Context->MiniportHandle); });
if(m_NBL)
{
auto NBL = DetachInternalObject();
NET_BUFFER_LIST_NEXT_NBL(NBL) = nullptr;
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, NBL, 0);
}
}
bool CNBL::ParsePriority()
{
NDIS_NET_BUFFER_LIST_8021Q_INFO priorityInfo;
priorityInfo.Value = m_Context->ulPriorityVlanSetting ?
NET_BUFFER_LIST_INFO(m_NBL, Ieee8021QNetBufferListInfo) : nullptr;
if (!priorityInfo.TagHeader.VlanId)
{
priorityInfo.TagHeader.VlanId = m_Context->VlanId;
}
if (priorityInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(m_Context, priorityInfo.TagHeader.VlanId))
{
DPrintf(0, ("[%s] Discarded invalid priority tag %p\n", __FUNCTION__, priorityInfo.Value));
return false;
}
else if (priorityInfo.Value)
{
// ignore priority, if configured
if (!IsPrioritySupported(m_Context))
priorityInfo.TagHeader.UserPriority = 0;
// ignore VlanId, if specified
if (!IsVlanSupported(m_Context))
priorityInfo.TagHeader.VlanId = 0;
if (priorityInfo.Value)
{
m_TCI = static_cast<UINT16>(priorityInfo.TagHeader.UserPriority << 13 | priorityInfo.TagHeader.VlanId);
DPrintf(1, ("[%s] Populated priority tag %p\n", __FUNCTION__, priorityInfo.Value));
}
}
return true;
}
void CNBL::RegisterNB(CNB *NB)
{
m_Buffers.PushBack(NB);
m_BuffersNumber++;
}
void CNBL::RegisterMappedNB(CNB *NB)
{
if (m_MappedBuffers.PushBack(NB) == m_BuffersNumber)
{
m_ParentTXPath->NBLMappingDone(this);
}
}
bool CNBL::ParseBuffers()
{
m_MaxDataLength = 0;
for (auto NB = NET_BUFFER_LIST_FIRST_NB(m_NBL); NB != nullptr; NB = NET_BUFFER_NEXT_NB(NB))
{
CNB *NBHolder = new (m_Context->MiniportHandle) CNB(NB, this, m_Context);
if(!NBHolder || !NBHolder->IsValid())
{
return false;
}
RegisterNB(NBHolder);
m_MaxDataLength = max(m_MaxDataLength, NBHolder->GetDataLength());
}
if(m_MaxDataLength == 0)
{
DPrintf(0, ("Empty NBL (%p) dropped\n", __FUNCTION__, m_NBL));
return false;
}
return true;
}
bool CNBL::NeedsLSO()
{
return m_MaxDataLength > m_Context->MaxPacketSize.nMaxFullSizeOS;
}
bool CNBL::FitsLSO()
{
return (m_MaxDataLength <= PARANDIS_MAX_LSO_SIZE + LsoTcpHeaderOffset() + MAX_TCP_HEADER_SIZE);
}
bool CNBL::ParseLSO()
{
ASSERT(IsLSO());
if (m_LsoInfo.LsoV1Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V1_TYPE &&
m_LsoInfo.LsoV2Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE)
{
return false;
}
if (NeedsLSO() &&
(!m_LsoInfo.LsoV2Transmit.MSS ||
!m_LsoInfo.LsoV2Transmit.TcpHeaderOffset))
{
return false;
}
if (!FitsLSO())
{
return false;
}
if (!LsoTcpHeaderOffset() != !MSS())
{
return false;
}
if ((!m_Context->Offload.flags.fTxLso || !m_Context->bOffloadv4Enabled) &&
m_LsoInfo.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv4)
{
return false;
}
if (m_LsoInfo.LsoV2Transmit.Type == NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE &&
m_LsoInfo.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv6 &&
(!m_Context->Offload.flags.fTxLsov6 || !m_Context->bOffloadv6Enabled))
{
return false;
}
return true;
}
template <typename TClassPred, typename TOffloadPred, typename TSupportedPred>
bool CNBL::ParseCSO(TClassPred IsClass, TOffloadPred IsOffload,
TSupportedPred IsSupported, LPSTR OffloadName)
{
ASSERT(IsClass());
UNREFERENCED_PARAMETER(IsClass);
if (IsOffload())
{
if(!IsSupported())
{
DPrintf(0, ("[%s] %s request when it is not supported\n", __FUNCTION__, OffloadName));
#if FAIL_UNEXPECTED
// ignore unexpected CS requests while this passes WHQL
return false;
#endif
}
}
return true;
}
bool CNBL::ParseOffloads()
{
if (IsLSO())
{
if(!ParseLSO())
{
return false;
}
}
else if (IsIP4CSO())
{
if(!ParseCSO([this] () -> bool { return IsIP4CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.TcpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxTCPChecksum && m_Context->bOffloadv4Enabled; },
"TCP4 CSO"))
{
return false;
}
else if(!ParseCSO([this] () -> bool { return IsIP4CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.UdpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxUDPChecksum && m_Context->bOffloadv4Enabled; },
"UDP4 CSO"))
{
return false;
}
if(!ParseCSO([this] () -> bool { return IsIP4CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.IpHeaderChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxIPChecksum && m_Context->bOffloadv4Enabled; },
"IP4 CSO"))
{
return false;
}
}
else if (IsIP6CSO())
{
if(!ParseCSO([this] () -> bool { return IsIP6CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.TcpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxTCPv6Checksum && m_Context->bOffloadv6Enabled; },
"TCP6 CSO"))
{
return false;
}
else if(!ParseCSO([this] () -> bool { return IsIP6CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.UdpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxUDPv6Checksum && m_Context->bOffloadv6Enabled; },
"UDP6 CSO"))
{
return false;
}
}
return true;
}
void CNBL::StartMapping()
{
CDpcIrqlRaiser OnDpc;
AddRef();
m_Buffers.ForEachDetached([this](CNB *NB)
{
if (!NB->ScheduleBuildSGListForTx())
{
m_HaveFailedMappings = true;
NB->MappingDone(nullptr);
}
});
Release();
}
void CNBL::OnLastReferenceGone()
{
Destroy(this, m_Context->MiniportHandle);
}
CParaNdisTX::CParaNdisTX()
{ }
bool CParaNdisTX::Create(PPARANDIS_ADAPTER Context, UINT DeviceQueueIndex)
{
m_Context = Context;
m_queueIndex = (u16)DeviceQueueIndex;
return m_VirtQueue.Create(DeviceQueueIndex,
m_Context->IODevice,
m_Context->MiniportHandle,
m_Context->bDoPublishIndices ? true : false,
m_Context->maxFreeTxDescriptors,
m_Context->nVirtioHeaderSize,
m_Context);
}
void CParaNdisTX::Send(PNET_BUFFER_LIST NBL)
{
PNET_BUFFER_LIST nextNBL = nullptr;
for(auto currNBL = NBL; currNBL != nullptr; currNBL = nextNBL)
{
nextNBL = NET_BUFFER_LIST_NEXT_NBL(currNBL);
NET_BUFFER_LIST_NEXT_NBL(currNBL) = nullptr;
auto NBLHolder = new (m_Context->MiniportHandle) CNBL(currNBL, m_Context, *this);
if (NBLHolder == nullptr)
{
CNBL OnStack(currNBL, m_Context, *this);
OnStack.SetStatus(NDIS_STATUS_RESOURCES);
DPrintf(0, ("ERROR: Failed to allocate CNBL instance\n"));
continue;
}
if(NBLHolder->Prepare() &&
ParaNdis_IsSendPossible(m_Context))
{
NBLHolder->StartMapping();
}
else
{
NBLHolder->SetStatus(ParaNdis_ExactSendFailureStatus(m_Context));
NBLHolder->Release();
}
}
}
void CParaNdisTX::NBLMappingDone(CNBL *NBLHolder)
{
ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
if (NBLHolder->MappingSuceeded())
{
DoWithTXLock([NBLHolder, this](){ m_SendList.PushBack(NBLHolder); });
DoPendingTasks(false);
}
else
{
NBLHolder->SetStatus(NDIS_STATUS_FAILURE);
NBLHolder->Release();
}
}
CNB *CNBL::PopMappedNB()
{
m_MappedBuffersDetached++;
return m_MappedBuffers.Pop();
}
void CNBL::PushMappedNB(CNB *NB)
{
m_MappedBuffersDetached--;
m_MappedBuffers.Push(NB);
}
//TODO: Needs review
void CNBL::NBComplete()
{
m_BuffersDone++;
m_MappedBuffersDetached--;
}
bool CNBL::IsSendDone()
{
return m_BuffersDone == m_BuffersNumber;
}
//TODO: Needs review
void CNBL::CompleteMappedBuffers()
{
m_MappedBuffers.ForEachDetached([this](CNB *NB)
{
NBComplete();
CNB::Destroy(NB, m_Context->MiniportHandle);
});
}
PNET_BUFFER_LIST CNBL::DetachInternalObject()
{
// do it for both LsoV1 and LsoV2
if (IsLSO())
{
m_LsoInfo.LsoV1TransmitComplete.TcpPayload = m_TransferSize;
}
//Flush changes made in LSO structures
NET_BUFFER_LIST_INFO(m_NBL, TcpLargeSendNetBufferListInfo) = m_LsoInfo.Value;
auto Res = m_NBL;
m_NBL = nullptr;
return Res;
}
PNET_BUFFER_LIST CParaNdisTX::ProcessWaitingList()
{
PNET_BUFFER_LIST CompletedNBLs = nullptr;
m_WaitingList.ForEachDetachedIf([](CNBL* NBL) { return NBL->IsSendDone(); },
[&](CNBL* NBL)
{
NBL->SetStatus(NDIS_STATUS_SUCCESS);
auto RawNBL = NBL->DetachInternalObject();
NBL->Release();
NET_BUFFER_LIST_NEXT_NBL(RawNBL) = CompletedNBLs;
CompletedNBLs = RawNBL;
});
return CompletedNBLs;
}
//TODO: Needs review
PNET_BUFFER_LIST CParaNdisTX::RemoveAllNonWaitingNBLs()
{
PNET_BUFFER_LIST RemovedNBLs = nullptr;
auto status = ParaNdis_ExactSendFailureStatus(m_Context);
m_SendList.ForEachDetachedIf([](CNBL *NBL) { return !NBL->HaveDetachedBuffers(); },
[&](CNBL *NBL)
{
NBL->SetStatus(status);
auto RawNBL = NBL->DetachInternalObject();
NBL->Release();
NET_BUFFER_LIST_NEXT_NBL(RawNBL) = RemovedNBLs;
RemovedNBLs = RawNBL;
});
m_SendList.ForEach([](CNBL *NBL) { NBL->CompleteMappedBuffers(); });
return RemovedNBLs;
}
bool CParaNdisTX::Pause()
{
PNET_BUFFER_LIST NBL = nullptr;
bool res;
DoWithTXLock([this, &NBL, &res]()
{
NBL = RemoveAllNonWaitingNBLs();
res = (!m_VirtQueue.HasPacketsInHW() && m_WaitingList.IsEmpty());
});
if(NBL != nullptr)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, NBL, 0);
}
return res;
}
PNET_BUFFER_LIST CParaNdisTX::BuildCancelList(PVOID CancelId)
{
PNET_BUFFER_LIST CanceledNBLs = nullptr;
TSpinLocker LockedContext(m_Lock);
m_SendList.ForEachDetachedIf([CancelId](CNBL* NBL){ return NBL->MatchCancelID(CancelId) && !NBL->HaveDetachedBuffers(); },
[this, &CanceledNBLs](CNBL* NBL)
{
NBL->SetStatus(NDIS_STATUS_SEND_ABORTED);
auto RawNBL = NBL->DetachInternalObject();
NBL->Release();
NET_BUFFER_LIST_NEXT_NBL(RawNBL) = CanceledNBLs;
CanceledNBLs = RawNBL;
});
return CanceledNBLs;
}
void CParaNdisTX::CancelNBLs(PVOID CancelId)
{
auto CanceledNBLs = BuildCancelList(CancelId);
if (CanceledNBLs != nullptr)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, CanceledNBLs, 0);
}
}
//TODO: Requires review
BOOLEAN _Function_class_(MINIPORT_SYNCHRONIZE_INTERRUPT) CParaNdisTX::RestartQueueSynchronously(tSynchronizedContext *ctx)
{
auto TXPath = static_cast<CParaNdisTX *>(ctx->Parameter);
return !TXPath->m_VirtQueue.Restart();
}
//TODO: Requires review
bool CParaNdisTX::RestartQueue(bool DoKick)
{
TSpinLocker LockedContext(m_Lock);
auto res = ParaNdis_SynchronizeWithInterrupt(m_Context,
m_messageIndex,
CParaNdisTX::RestartQueueSynchronously,
this) ? true : false;
if(DoKick)
{
Kick();
}
return res;
}
bool CParaNdisTX::SendMapped(bool IsInterrupt, PNET_BUFFER_LIST &NBLFailNow)
{
if(!ParaNdis_IsSendPossible(m_Context))
{
NBLFailNow = RemoveAllNonWaitingNBLs();
if (NBLFailNow)
{
DPrintf(0, (__FUNCTION__ " Failing send"));
}
}
else
{
bool SentOutSomeBuffers = false;
auto HaveBuffers = true;
while (HaveBuffers && HaveMappedNBLs())
{
auto NBLHolder = PopMappedNBL();
if (NBLHolder->HaveMappedBuffers())
{
auto NBHolder = NBLHolder->PopMappedNB();
auto result = m_VirtQueue.SubmitPacket(*NBHolder);
switch (result)
{
case SUBMIT_NO_PLACE_IN_QUEUE:
NBLHolder->PushMappedNB(NBHolder);
PushMappedNBL(NBLHolder);
HaveBuffers = false;
// break the loop, allow to kick and free some buffers
break;
case SUBMIT_FAILURE:
case SUBMIT_SUCCESS:
case SUBMIT_PACKET_TOO_LARGE:
// if this NBL finished?
if (!NBLHolder->HaveMappedBuffers())
{
m_WaitingList.Push(NBLHolder);
}
else
{
// no, insert it back to the queue
PushMappedNBL(NBLHolder);
}
if (result == SUBMIT_SUCCESS)
{
SentOutSomeBuffers = true;
}
else
{
NBHolder->SendComplete();
CNB::Destroy(NBHolder, m_Context->MiniportHandle);
}
break;
default:
ASSERT(false);
break;
}
}
else
{
//TODO: Refactoring needed
//This is a case when pause called, mapped list cleared but NBL is still in the send list
m_WaitingList.Push(NBLHolder);
}
}
if (SentOutSomeBuffers)
{
DPrintf(2, ("[%s] sent down\n", __FUNCTION__, SentOutSomeBuffers));
if (IsInterrupt)
{
return true;
}
else
{
m_VirtQueue.Kick();
}
}
}
return false;
}
bool CParaNdisTX::DoPendingTasks(bool IsInterrupt)
{
ONPAUSECOMPLETEPROC CallbackToCall = nullptr;
PNET_BUFFER_LIST pNBLFailNow = nullptr;
PNET_BUFFER_LIST pNBLReturnNow = nullptr;
bool bDoKick = false;
DoWithTXLock([&] ()
{
m_VirtQueue.ProcessTXCompletions();
bDoKick = SendMapped(IsInterrupt, pNBLFailNow);
pNBLReturnNow = ProcessWaitingList();
{
CNdisPassiveWriteAutoLock tLock(m_Context->m_PauseLock);
if (!m_VirtQueue.HasPacketsInHW() && m_Context->SendState == srsPausing)
{
CallbackToCall = m_Context->SendPauseCompletionProc;
m_Context->SendPauseCompletionProc = nullptr;
m_Context->SendState = srsDisabled;
}
}
});
if (pNBLFailNow)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, pNBLFailNow,
NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL);
}
if (pNBLReturnNow)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, pNBLReturnNow,
NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL);
}
if (CallbackToCall != nullptr)
{
CallbackToCall(m_Context);
}
return bDoKick;
}
void CNB::MappingDone(PSCATTER_GATHER_LIST SGL)
{
m_SGL = SGL;
m_ParentNBL->RegisterMappedNB(this);
}
CNB::~CNB()
{
ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
if(m_SGL != nullptr)
{
NdisMFreeNetBufferSGList(m_Context->DmaHandle, m_SGL, m_NB);
}
}
bool CNB::ScheduleBuildSGListForTx()
{
ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
return NdisMAllocateNetBufferSGList(m_Context->DmaHandle, m_NB, this,
NDIS_SG_LIST_WRITE_TO_DEVICE, nullptr, 0) == NDIS_STATUS_SUCCESS;
}
void CNB::PopulateIPLength(IPv4Header *IpHeader, USHORT IpLength) const
{
if ((IpHeader->ip_verlen & 0xF0) == 0x40)
{
if (!IpHeader->ip_length) {
IpHeader->ip_length = swap_short(IpLength);
}
}
}
void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
}
USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
}
void CNB::SetupCSO(virtio_net_hdr_basic *VirtioHeader, ULONG L4HeaderOffset) const
{
u16 PriorityHdrLen = m_ParentNBL->TCI() ? ETH_PRIORITY_HEADER_SIZE : 0;
VirtioHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VirtioHeader->csum_start = static_cast<u16>(L4HeaderOffset) + PriorityHdrLen;
VirtioHeader->csum_offset = m_ParentNBL->IsTcpCSO() ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET;
}
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const
{
ParaNdis_CheckSumVerifyFlat(IpHeader,
EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum,
__FUNCTION__);
}
bool CNB::FillDescriptorSGList(CTXDescriptor &Descriptor, ULONG ParsedHeadersLength) const
{
return Descriptor.SetupHeaders(ParsedHeadersLength) &&
MapDataToVirtioSGL(Descriptor, ParsedHeadersLength + NET_BUFFER_DATA_OFFSET(m_NB));
}
bool CNB::MapDataToVirtioSGL(CTXDescriptor &Descriptor, ULONG Offset) const
{
for (ULONG i = 0; i < m_SGL->NumberOfElements; i++)
{
if (Offset < m_SGL->Elements[i].Length)
{
PHYSICAL_ADDRESS PA;
PA.QuadPart = m_SGL->Elements[i].Address.QuadPart + Offset;
if (!Descriptor.AddDataChunk(PA, m_SGL->Elements[i].Length - Offset))
{
return false;
}
Offset = 0;
}
else
{
Offset -= m_SGL->Elements[i].Length;
}
}
return true;
}
bool CNB::CopyHeaders(PVOID Destination, ULONG MaxSize, ULONG &HeadersLength, ULONG &L4HeaderOffset) const
{
HeadersLength = 0;
L4HeaderOffset = 0;
if (m_ParentNBL->IsLSO() || m_ParentNBL->IsTcpCSO())
{
L4HeaderOffset = m_ParentNBL->TCPHeaderOffset();
HeadersLength = L4HeaderOffset + sizeof(TCPHeader);
Copy(Destination, HeadersLength);
}
else if (m_ParentNBL->IsUdpCSO())
{
Copy(Destination, MaxSize);
L4HeaderOffset = QueryL4HeaderOffset(Destination, m_Context->Offload.ipHeaderOffset);
HeadersLength = L4HeaderOffset + sizeof(UDPHeader);
}
else if (m_ParentNBL->IsIPHdrCSO())
{
Copy(Destination, MaxSize);
HeadersLength = QueryL4HeaderOffset(Destination, m_Context->Offload.ipHeaderOffset);
L4HeaderOffset = HeadersLength;
}
else
{
HeadersLength = ETH_HEADER_SIZE;
Copy(Destination, HeadersLength);
}
return (HeadersLength <= MaxSize);
}
void CNB::BuildPriorityHeader(PETH_HEADER EthHeader, PVLAN_HEADER VlanHeader) const
{
VlanHeader->TCI = RtlUshortByteSwap(m_ParentNBL->TCI());
if (VlanHeader->TCI != 0)
{
VlanHeader->EthType = EthHeader->EthType;
EthHeader->EthType = RtlUshortByteSwap(PRIO_HEADER_ETH_TYPE);
}
}
void CNB::PrepareOffloads(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength, ULONG L4HeaderOffset) const
{
*VirtioHeader = {};
if (m_ParentNBL->IsLSO())
{
SetupLSO(VirtioHeader, IpHeader, EthPayloadLength);
}
else if (m_ParentNBL->IsTcpCSO() || m_ParentNBL->IsUdpCSO())
{
SetupCSO(VirtioHeader, L4HeaderOffset);
}
if (m_ParentNBL->IsIPHdrCSO())
{
DoIPHdrCSO(IpHeader, EthPayloadLength);
}
}
bool CNB::BindToDescriptor(CTXDescriptor &Descriptor)
{
if (m_SGL == nullptr)
{
return false;
}
Descriptor.SetNB(this);
auto &HeadersArea = Descriptor.HeadersAreaAccessor();
auto EthHeaders = HeadersArea.EthHeadersAreaVA();
ULONG HeadersLength;
ULONG L4HeaderOffset;
if (!CopyHeaders(EthHeaders, HeadersArea.MaxEthHeadersSize(), HeadersLength, L4HeaderOffset))
{
return false;
}
BuildPriorityHeader(HeadersArea.EthHeader(), HeadersArea.VlanHeader());
PrepareOffloads(HeadersArea.VirtioHeader(),
HeadersArea.IPHeaders(),
GetDataLength() - m_Context->Offload.ipHeaderOffset,
L4HeaderOffset);
return FillDescriptorSGList(Descriptor, HeadersLength);
}
bool CNB::Copy(PVOID Dst, ULONG Length) const
{
ULONG CurrOffset = NET_BUFFER_CURRENT_MDL_OFFSET(m_NB);
ULONG Copied = 0;
for (PMDL CurrMDL = NET_BUFFER_CURRENT_MDL(m_NB);
CurrMDL != nullptr && Copied < Length;
CurrMDL = CurrMDL->Next)
{
ULONG CurrLen;
PVOID CurrAddr;
#if NDIS_SUPPORT_NDIS620
NdisQueryMdl(CurrMDL, &CurrAddr, &CurrLen, LowPagePriority | MdlMappingNoExecute);
#else
NdisQueryMdl(CurrMDL, &CurrAddr, &CurrLen, LowPagePriority);
#endif
if (CurrAddr == nullptr)
{
break;
}
CurrLen = min(CurrLen - CurrOffset, Length - Copied);
NdisMoveMemory(RtlOffsetToPointer(Dst, Copied),
RtlOffsetToPointer(CurrAddr, CurrOffset),
CurrLen);
Copied += CurrLen;
CurrOffset = 0;
}
return (Copied == Length);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1580_1 |
crossvul-cpp_data_good_1580_3 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: sw-offload.c
*
* This file contains SW Implementation of checksum computation for IP,TCP,UDP
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
// till IP header size is 8 bit
#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4)
// IPv6 Header RFC 2460 (n*8 bytes)
typedef struct _tagIPv6ExtHeader {
UCHAR ip6ext_next_header; // next header type
UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes
USHORT options; //
} IPv6ExtHeader;
// IP Pseudo Header RFC 768
typedef struct _tagIPv4PseudoHeader {
ULONG ipph_src; // Source address
ULONG ipph_dest; // Destination address
UCHAR ipph_zero; // 0
UCHAR ipph_protocol; // TCP/UDP
USHORT ipph_length; // TCP/UDP length
}tIPv4PseudoHeader;
// IPv6 Pseudo Header RFC 2460
typedef struct _tagIPv6PseudoHeader {
IPV6_ADDRESS ipph_src; // Source address
IPV6_ADDRESS ipph_dest; // Destination address
ULONG ipph_length; // TCP/UDP length
UCHAR z1; // 0
UCHAR z2; // 0
UCHAR z3; // 0
UCHAR ipph_protocol; // TCP/UDP
}tIPv6PseudoHeader;
// IP v6 extension header option
typedef struct _tagIP6_EXT_HDR_OPTION
{
UCHAR Type;
UCHAR Length;
} IP6_EXT_HDR_OPTION, *PIP6_EXT_HDR_OPTION;
#define IP6_EXT_HDR_OPTION_PAD1 (0)
#define IP6_EXT_HDR_OPTION_HOME_ADDR (201)
// IP v6 routing header
typedef struct _tagIP6_TYPE2_ROUTING_HEADER
{
UCHAR NextHdr;
UCHAR HdrLen;
UCHAR RoutingType;
UCHAR SegmentsLeft;
ULONG Reserved;
IPV6_ADDRESS Address;
} IP6_TYPE2_ROUTING_HEADER, *PIP6_TYPE2_ROUTING_HEADER;
#define PROTOCOL_TCP 6
#define PROTOCOL_UDP 17
#define IP_HEADER_LENGTH(pHeader) (((pHeader)->ip_verlen & 0x0F) << 2)
#define IP_HEADER_VERSION(pHeader) (((pHeader)->ip_verlen & 0xF0) >> 4)
#define IP_HEADER_IS_FRAGMENT(pHeader) (((pHeader)->ip_offset & ~0xC0) != 0)
#define IP6_HEADER_VERSION(pHeader) (((pHeader)->ip6_ver_tc & 0xF0) >> 4)
#define ETH_GET_VLAN_HDR(ethHdr) ((PVLAN_HEADER) RtlOffsetToPointer(ethHdr, ETH_PRIORITY_HEADER_OFFSET))
#define VLAN_GET_USER_PRIORITY(vlanHdr) ( (((PUCHAR)(vlanHdr))[2] & 0xE0) >> 5 )
#define VLAN_GET_VLAN_ID(vlanHdr) ( ((USHORT) (((PUCHAR)(vlanHdr))[2] & 0x0F) << 8) | ( ((PUCHAR)(vlanHdr))[3] ) )
#define ETH_PROTO_IP4 (0x0800)
#define ETH_PROTO_IP6 (0x86DD)
#define IP6_HDR_HOP_BY_HOP (0)
#define IP6_HDR_ROUTING (43)
#define IP6_HDR_FRAGMENT (44)
#define IP6_HDR_ESP (50)
#define IP6_HDR_AUTHENTICATION (51)
#define IP6_HDR_NONE (59)
#define IP6_HDR_DESTINATON (60)
#define IP6_HDR_MOBILITY (135)
#define IP6_EXT_HDR_GRANULARITY (8)
static UINT32 RawCheckSumCalculator(PVOID buffer, ULONG len)
{
UINT32 val = 0;
PUSHORT pus = (PUSHORT)buffer;
ULONG count = len >> 1;
while (count--) val += *pus++;
if (len & 1) val += (USHORT)*(PUCHAR)pus;
return val;
}
static __inline USHORT RawCheckSumFinalize(UINT32 val)
{
val = (((val >> 16) | (val << 16)) + val) >> 16;
return (USHORT)~val;
}
static __inline USHORT CheckSumCalculatorFlat(PVOID buffer, ULONG len)
{
return RawCheckSumFinalize(RawCheckSumCalculator(buffer, len));
}
static __inline USHORT CheckSumCalculator(tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG len)
{
tCompletePhysicalAddress *pCurrentPage = &pDataPages[0];
ULONG ulCurrPageOffset = 0;
UINT32 u32RawCSum = 0;
while(ulStartOffset > 0)
{
ulCurrPageOffset = min(pCurrentPage->size, ulStartOffset);
if(ulCurrPageOffset < ulStartOffset)
pCurrentPage++;
ulStartOffset -= ulCurrPageOffset;
}
while(len > 0)
{
PVOID pCurrentPageDataStart = RtlOffsetToPointer(pCurrentPage->Virtual, ulCurrPageOffset);
ULONG ulCurrentPageDataLength = min(len, pCurrentPage->size - ulCurrPageOffset);
u32RawCSum += RawCheckSumCalculator(pCurrentPageDataStart, ulCurrentPageDataLength);
pCurrentPage++;
ulCurrPageOffset = 0;
len -= ulCurrentPageDataLength;
}
return RawCheckSumFinalize(u32RawCSum);
}
/******************************************
IP header checksum calculator
*******************************************/
static __inline VOID CalculateIpChecksum(IPv4Header *pIpHeader)
{
pIpHeader->ip_xsum = 0;
pIpHeader->ip_xsum = CheckSumCalculatorFlat(pIpHeader, IP_HEADER_LENGTH(pIpHeader));
}
static __inline tTcpIpPacketParsingResult
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
static __inline tTcpIpPacketParsingResult
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
// may be full or not, but the datagram length is known
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
else
{
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
static __inline tTcpIpPacketParsingResult
QualifyIpPacket(IPHeader *pIpHeader, ULONG len, BOOLEAN verifyLength)
{
tTcpIpPacketParsingResult res;
res.value = 0;
if (len < 4)
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
if (len < sizeof(IPv4Header))
{
res.ipStatus = ppresNotIP;
return res;
}
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (res.ipStatus == ppresNotIP)
{
return res;
}
if (ipHeaderSize >= fullLength || ( verifyLength && len < fullLength))
{
DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d, verify = %s\n", __FUNCTION__,
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len, (verifyLength ? "true" : "false")));
res.ipCheckSum = ppresIPTooShort;
return res;
}
}
else if (ip_version == 6)
{
if (len < sizeof(IPv6Header))
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
if (verifyLength && (len < fullLength))
{
res.ipStatus = ppresNotIP;
return res;
}
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
//existing extended headers
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
//any other protocol
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
// bit "more fragments" or fragment offset mean the packet is fragmented
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
static __inline USHORT GetXxpHeaderAndPayloadLen(IPHeader *pIpHeader, tTcpIpPacketParsingResult res)
{
if (res.ipStatus == ppresIPV4)
{
USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4);
USHORT len = swap_short(pIpHeader->v4.ip_length);
return len - headerLength;
}
if (res.ipStatus == ppresIPV6)
{
USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize;
}
return 0;
}
static __inline USHORT CalculateIpv4PseudoHeaderChecksum(IPv4Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv4PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src = pIpHeader->ip_src;
ipph.ipph_dest = pIpHeader->ip_dest;
ipph.ipph_zero = 0;
ipph.ipph_protocol = pIpHeader->ip_protocol;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv6PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src[0] = pIpHeader->ip6_src_address[0];
ipph.ipph_src[1] = pIpHeader->ip6_src_address[1];
ipph.ipph_src[2] = pIpHeader->ip6_src_address[2];
ipph.ipph_src[3] = pIpHeader->ip6_src_address[3];
ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0];
ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1];
ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2];
ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3];
ipph.z1 = ipph.z2 = ipph.z3 = 0;
ipph.ipph_protocol = pIpHeader->ip6_next_header;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader,
tTcpIpPacketParsingResult res,
USHORT headerAndPayloadLen)
{
if (res.ipStatus == ppresIPV4)
return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen);
if (res.ipStatus == ppresIPV6)
return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen);
return 0;
}
static __inline BOOLEAN
CompareNetCheckSumOnEndSystem(USHORT computedChecksum, USHORT arrivedChecksum)
{
//According to RFC 1624 sec. 3
//Checksum verification mechanism should treat 0xFFFF
//checksum value from received packet as 0x0000
if(arrivedChecksum == 0xFFFF)
arrivedChecksum = 0;
return computedChecksum == arrivedChecksum;
}
/******************************************
Calculates IP header checksum calculator
it can be already calculated
the header must be complete!
*******************************************/
static __inline tTcpIpPacketParsingResult
VerifyIpChecksum(
IPv4Header *pIpHeader,
tTcpIpPacketParsingResult known,
BOOLEAN bFix)
{
tTcpIpPacketParsingResult res = known;
if (res.ipCheckSum != ppresIPTooShort)
{
USHORT saved = pIpHeader->ip_xsum;
CalculateIpChecksum(pIpHeader);
res.ipCheckSum = CompareNetCheckSumOnEndSystem(pIpHeader->ip_xsum, saved) ? ppresCSOK : ppresCSBad;
if (!bFix)
pIpHeader->ip_xsum = saved;
else
res.fixedIpCS = res.ipCheckSum == ppresCSBad;
}
return res;
}
/*********************************************
Calculates UDP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateUdpChecksumGivenPseudoCS(UDPHeader *pUdpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG udpLength)
{
pUdpHeader->udp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, udpLength);
}
/*********************************************
Calculates TCP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateTcpChecksumGivenPseudoCS(TCPHeader *pTcpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG tcpLength)
{
pTcpHeader->tcp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, tcpLength);
}
/************************************************
Checks (and fix if required) the TCP checksum
sets flags in result structure according to verification
TcpPseudoOK if valid pseudo CS was found
TcpOK if valid TCP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyTcpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pTcpHeader->tcp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (res.xxpCheckSum != ppresPCSOK || whatToFix)
{
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader)))
{
pTcpHeader->tcp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
//USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length);
pTcpHeader->tcp_xsum = phcs;
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pTcpHeader->tcp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else if (whatToFix)
{
res.xxpStatus = ppresXxpIncomplete;
}
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good TCP CS
// in such rare case we give a priority to TCP CS
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pTcpHeader->tcp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
/************************************************
Checks (and fix if required) the UDP checksum
sets flags in result structure according to verification
UdpPseudoOK if valid pseudo CS was found
UdpOK if valid UDP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyUdpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pUdpHeader->udp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader)))
{
pUdpHeader->udp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum))
{
if (res.xxpFull)
{
pUdpHeader->udp_xsum = phcs;
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pUdpHeader->udp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else
res.xxpCheckSum = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good UDP CS
// in such rare case we give a priority to UDP CS
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pUdpHeader->udp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
static LPCSTR __inline GetPacketCase(tTcpIpPacketParsingResult res)
{
static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" };
if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ?
(res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") :
(res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6");
if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP";
if (res.xxpStatus == ppresXxpOther) return "IP";
return IPCaseName[res.ipStatus];
}
static LPCSTR __inline GetIPCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" };
return CSCaseName[res.ipCheckSum];
}
static LPCSTR __inline GetXxpCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" };
return CSCaseName[res.xxpCheckSum];
}
static __inline VOID PrintOutParsingResult(
tTcpIpPacketParsingResult res,
int level,
LPCSTR procname)
{
DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s\n", procname,
GetPacketCase(res),
GetIPCSCase(res),
res.fixedIpCS ? "(fixed)" : "",
GetXxpCSCase(res),
res.fixedXxpCS ? "(fixed)" : ""));
}
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
BOOLEAN verifyLength,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength, verifyLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength);
PrintOutParsingResult(res, 1, caller);
return res;
}
static __inline
VOID AnalyzeL3Proto(
USHORT L3Proto,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isIP4 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP4));
packetInfo->isIP6 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP6));
}
static
BOOLEAN AnalyzeL2Hdr(
PNET_PACKET_INFO packetInfo)
{
PETH_HEADER dataBuffer = (PETH_HEADER) packetInfo->headersBuffer;
if (packetInfo->dataLength < ETH_HEADER_SIZE)
return FALSE;
packetInfo->ethDestAddr = dataBuffer->DstAddr;
if (ETH_IS_BROADCAST(dataBuffer))
{
packetInfo->isBroadcast = TRUE;
}
else if (ETH_IS_MULTICAST(dataBuffer))
{
packetInfo->isMulticast = TRUE;
}
else
{
packetInfo->isUnicast = TRUE;
}
if(ETH_HAS_PRIO_HEADER(dataBuffer))
{
PVLAN_HEADER vlanHdr = ETH_GET_VLAN_HDR(dataBuffer);
if(packetInfo->dataLength < ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
packetInfo->hasVlanHeader = TRUE;
packetInfo->Vlan.UserPriority = VLAN_GET_USER_PRIORITY(vlanHdr);
packetInfo->Vlan.VlanId = VLAN_GET_VLAN_ID(vlanHdr);
packetInfo->L2HdrLen = ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE;
AnalyzeL3Proto(vlanHdr->EthType, packetInfo);
}
else
{
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
AnalyzeL3Proto(dataBuffer->EthType, packetInfo);
}
packetInfo->L2PayloadLen = packetInfo->dataLength - packetInfo->L2HdrLen;
return TRUE;
}
static __inline
BOOLEAN SkipIP6ExtensionHeader(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr)
{
IPv6ExtHeader* ip6ExtHdr;
if (*ip6HdrLength + sizeof(*ip6ExtHdr) > dataLength)
return FALSE;
ip6ExtHdr = (IPv6ExtHeader *)RtlOffsetToPointer(ip6Hdr, *ip6HdrLength);
*nextHdr = ip6ExtHdr->ip6ext_next_header;
*ip6HdrLength += (ip6ExtHdr->ip6ext_hdr_len + 1) * IP6_EXT_HDR_GRANULARITY;
return TRUE;
}
static
BOOLEAN AnalyzeIP6RoutingExtension(
PIP6_TYPE2_ROUTING_HEADER routingHdr,
ULONG dataLength,
IPV6_ADDRESS **destAddr)
{
if(dataLength < sizeof(*routingHdr))
return FALSE;
if(routingHdr->RoutingType == 2)
{
if((dataLength != sizeof(*routingHdr)) || (routingHdr->SegmentsLeft != 1))
return FALSE;
*destAddr = &routingHdr->Address;
}
else *destAddr = NULL;
return TRUE;
}
static
BOOLEAN AnalyzeIP6DestinationExtension(
PVOID destHdr,
ULONG dataLength,
IPV6_ADDRESS **homeAddr)
{
while(dataLength != 0)
{
PIP6_EXT_HDR_OPTION optHdr = (PIP6_EXT_HDR_OPTION) destHdr;
ULONG optionLen;
switch(optHdr->Type)
{
case IP6_EXT_HDR_OPTION_HOME_ADDR:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
if(optHdr->Length != sizeof(IPV6_ADDRESS))
return FALSE;
*homeAddr = (IPV6_ADDRESS*) RtlOffsetToPointer(optHdr, sizeof(IP6_EXT_HDR_OPTION));
break;
case IP6_EXT_HDR_OPTION_PAD1:
optionLen = RTL_SIZEOF_THROUGH_FIELD(IP6_EXT_HDR_OPTION, Type);
break;
default:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
break;
}
destHdr = RtlOffsetToPointer(destHdr, optionLen);
if(dataLength < optionLen)
return FALSE;
dataLength -= optionLen;
}
return TRUE;
}
static
BOOLEAN AnalyzeIP6Hdr(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr,
PULONG homeAddrOffset,
PULONG destAddrOffset)
{
*homeAddrOffset = 0;
*destAddrOffset = 0;
*ip6HdrLength = sizeof(*ip6Hdr);
if(dataLength < *ip6HdrLength)
return FALSE;
*nextHdr = ip6Hdr->ip6_next_header;
for(;;)
{
switch (*nextHdr)
{
default:
case IP6_HDR_NONE:
case PROTOCOL_TCP:
case PROTOCOL_UDP:
case IP6_HDR_FRAGMENT:
return TRUE;
case IP6_HDR_DESTINATON:
{
IPV6_ADDRESS *homeAddr = NULL;
ULONG destHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6DestinationExtension(RtlOffsetToPointer(ip6Hdr, destHdrOffset),
*ip6HdrLength - destHdrOffset, &homeAddr))
return FALSE;
*homeAddrOffset = homeAddr ? RtlPointerToOffset(ip6Hdr, homeAddr) : 0;
}
break;
case IP6_HDR_ROUTING:
{
IPV6_ADDRESS *destAddr = NULL;
ULONG routingHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6RoutingExtension((PIP6_TYPE2_ROUTING_HEADER) RtlOffsetToPointer(ip6Hdr, routingHdrOffset),
*ip6HdrLength - routingHdrOffset, &destAddr))
return FALSE;
*destAddrOffset = destAddr ? RtlPointerToOffset(ip6Hdr, destAddr) : 0;
}
break;
case IP6_HDR_HOP_BY_HOP:
case IP6_HDR_ESP:
case IP6_HDR_AUTHENTICATION:
case IP6_HDR_MOBILITY:
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
break;
}
}
}
static __inline
VOID AnalyzeL4Proto(
UCHAR l4Protocol,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isTCP = (l4Protocol == PROTOCOL_TCP);
packetInfo->isUDP = (l4Protocol == PROTOCOL_UDP);
}
static
BOOLEAN AnalyzeL3Hdr(
PNET_PACKET_INFO packetInfo)
{
if(packetInfo->isIP4)
{
IPv4Header *ip4Hdr = (IPv4Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(packetInfo->dataLength < packetInfo->L2HdrLen + sizeof(*ip4Hdr))
return FALSE;
packetInfo->L3HdrLen = IP_HEADER_LENGTH(ip4Hdr);
if ((packetInfo->L3HdrLen < sizeof(*ip4Hdr)) ||
(packetInfo->dataLength < packetInfo->L2HdrLen + packetInfo->L3HdrLen))
return FALSE;
if(IP_HEADER_VERSION(ip4Hdr) != 4)
return FALSE;
packetInfo->isFragment = IP_HEADER_IS_FRAGMENT(ip4Hdr);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(ip4Hdr->ip_protocol, packetInfo);
}
}
else if(packetInfo->isIP6)
{
ULONG homeAddrOffset, destAddrOffset;
UCHAR l4Proto;
IPv6Header *ip6Hdr = (IPv6Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(IP6_HEADER_VERSION(ip6Hdr) != 6)
return FALSE;
if(!AnalyzeIP6Hdr(ip6Hdr, packetInfo->L2PayloadLen,
&packetInfo->L3HdrLen, &l4Proto, &homeAddrOffset, &destAddrOffset))
return FALSE;
if (packetInfo->L3HdrLen > MAX_SUPPORTED_IPV6_HEADERS)
return FALSE;
packetInfo->ip6HomeAddrOffset = (homeAddrOffset) ? packetInfo->L2HdrLen + homeAddrOffset : 0;
packetInfo->ip6DestAddrOffset = (destAddrOffset) ? packetInfo->L2HdrLen + destAddrOffset : 0;
packetInfo->isFragment = (l4Proto == IP6_HDR_FRAGMENT);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(l4Proto, packetInfo);
}
}
return TRUE;
}
BOOLEAN ParaNdis_AnalyzeReceivedPacket(
PVOID headersBuffer,
ULONG dataLength,
PNET_PACKET_INFO packetInfo)
{
NdisZeroMemory(packetInfo, sizeof(*packetInfo));
packetInfo->headersBuffer = headersBuffer;
packetInfo->dataLength = dataLength;
if(!AnalyzeL2Hdr(packetInfo))
return FALSE;
if (!AnalyzeL3Hdr(packetInfo))
return FALSE;
return TRUE;
}
ULONG ParaNdis_StripVlanHeaderMoveHead(PNET_PACKET_INFO packetInfo)
{
PUINT32 pData = (PUINT32) packetInfo->headersBuffer;
ASSERT(packetInfo->hasVlanHeader);
ASSERT(packetInfo->L2HdrLen == ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE);
pData[3] = pData[2];
pData[2] = pData[1];
pData[1] = pData[0];
packetInfo->headersBuffer = RtlOffsetToPointer(packetInfo->headersBuffer, ETH_PRIORITY_HEADER_SIZE);
packetInfo->dataLength -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
packetInfo->ethDestAddr = (PUCHAR) RtlOffsetToPointer(packetInfo->ethDestAddr, ETH_PRIORITY_HEADER_SIZE);
packetInfo->ip6DestAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->ip6HomeAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
return ETH_PRIORITY_HEADER_SIZE;
};
VOID ParaNdis_PadPacketToMinimalLength(PNET_PACKET_INFO packetInfo)
{
// Ethernet standard declares minimal possible packet size
// Packets smaller than that must be padded before transfer
// Ethernet HW pads packets on transmit, however in our case
// some packets do not travel over Ethernet but being routed
// guest-to-guest by virtual switch.
// In this case padding is not performed and we may
// receive packet smaller than minimal allowed size. This is not
// a problem for real life scenarios however WHQL/HCK contains
// tests that check padding of received packets.
// To make these tests happy we have to pad small packets on receive
//NOTE: This function assumes that VLAN header has been already stripped out
if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE)
{
RtlZeroMemory(
RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength),
ETH_MIN_PACKET_SIZE - packetInfo->dataLength);
packetInfo->dataLength = ETH_MIN_PACKET_SIZE;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1580_3 |
crossvul-cpp_data_bad_4220_3 | /* -*- C++ -*-
* Copyright 2019-2020 LibRaw LLC (info@libraw.org)
*
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
*/
#include "../../internal/libraw_cxx_defs.h"
void LibRaw::kodak_thumb_loader()
{
INT64 est_datasize =
T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate?
if (ID.toffset < 0)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND)
throw LIBRAW_EXCEPTION_IO_EOF;
// some kodak cameras
ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth,
s_iheight = S.iheight;
ushort s_flags = libraw_internal_data.unpacker_data.load_flags;
libraw_internal_data.unpacker_data.load_flags = 12;
int s_colors = P1.colors;
unsigned s_filters = P1.filters;
ushort(*s_image)[4] = imgdata.image;
S.height = T.theight;
S.width = T.twidth;
P1.filters = 0;
if (thumb_load_raw == &LibRaw::kodak_ycbcr_load_raw)
{
S.height += S.height & 1;
S.width += S.width & 1;
}
imgdata.image =
(ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image));
merror(imgdata.image, "LibRaw::kodak_thumb_loader()");
ID.input->seek(ID.toffset, SEEK_SET);
// read kodak thumbnail into T.image[]
try
{
(this->*thumb_load_raw)();
}
catch (...)
{
free(imgdata.image);
imgdata.image = s_image;
T.twidth = 0;
S.width = s_width;
S.iwidth = s_iwidth;
S.iheight = s_iheight;
T.theight = 0;
S.height = s_height;
T.tcolors = 0;
P1.colors = s_colors;
P1.filters = s_filters;
T.tlength = 0;
libraw_internal_data.unpacker_data.load_flags = s_flags;
return;
}
// from scale_colors
{
double dmax;
float scale_mul[4];
int c, val;
for (dmax = DBL_MAX, c = 0; c < 3; c++)
if (dmax > C.pre_mul[c])
dmax = C.pre_mul[c];
for (c = 0; c < 3; c++)
scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum;
scale_mul[3] = scale_mul[1];
size_t size = S.height * S.width;
for (unsigned i = 0; i < size * 4; i++)
{
val = imgdata.image[0][i];
if (!val)
continue;
val *= scale_mul[i & 3];
imgdata.image[0][i] = CLIP(val);
}
}
// from convert_to_rgb
ushort *img;
int row, col;
int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] =
(int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4);
merror(t_hist, "LibRaw::kodak_thumb_loader()");
float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0},
{-0.111855984, 1.73688626, -0.625030339, 0},
{-0.0379119813, -0.891268849, 1.92918086, 0}};
for (img = imgdata.image[0], row = 0; row < S.height; row++)
for (col = 0; col < S.width; col++, img += 4)
{
out[0] = out[1] = out[2] = 0;
int c;
for (c = 0; c < 3; c++)
{
out[0] += out_cam[0][c] * img[c];
out[1] += out_cam[1][c] * img[c];
out[2] += out_cam[2][c] * img[c];
}
for (c = 0; c < 3; c++)
img[c] = CLIP((int)out[c]);
for (c = 0; c < P1.colors; c++)
t_hist[c][img[c] >> 3]++;
}
// from gamma_lut
int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] =
libraw_internal_data.output_data.histogram;
libraw_internal_data.output_data.histogram = t_hist;
// make curve output curve!
ushort *t_curve = (ushort *)calloc(sizeof(C.curve), 1);
merror(t_curve, "LibRaw::kodak_thumb_loader()");
memmove(t_curve, C.curve, sizeof(C.curve));
memset(C.curve, 0, sizeof(C.curve));
{
int perc, val, total, t_white = 0x2000, c;
perc = S.width * S.height * 0.01; /* 99th percentile white level */
if (IO.fuji_width)
perc /= 2;
if (!((O.highlight & ~2) || O.no_auto_bright))
for (t_white = c = 0; c < P1.colors; c++)
{
for (val = 0x2000, total = 0; --val > 32;)
if ((total += libraw_internal_data.output_data.histogram[c][val]) >
perc)
break;
if (t_white < val)
t_white = val;
}
gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright);
}
libraw_internal_data.output_data.histogram = save_hist;
free(t_hist);
// from write_ppm_tiff - copy pixels into bitmap
int s_flip = imgdata.sizes.flip;
if (imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS)
imgdata.sizes.flip = 0;
S.iheight = S.height;
S.iwidth = S.width;
if (S.flip & 4)
SWAP(S.height, S.width);
if (T.thumb)
free(T.thumb);
T.thumb = (char *)calloc(S.width * S.height, P1.colors);
merror(T.thumb, "LibRaw::kodak_thumb_loader()");
T.tlength = S.width * S.height * P1.colors;
// from write_tiff_ppm
{
int soff = flip_index(0, 0);
int cstep = flip_index(0, 1) - soff;
int rstep = flip_index(1, 0) - flip_index(0, S.width);
for (int row = 0; row < S.height; row++, soff += rstep)
{
char *ppm = T.thumb + row * S.width * P1.colors;
for (int col = 0; col < S.width; col++, soff += cstep)
for (int c = 0; c < P1.colors; c++)
ppm[col * P1.colors + c] =
imgdata.color.curve[imgdata.image[soff][c]] >> 8;
}
}
memmove(C.curve, t_curve, sizeof(C.curve));
free(t_curve);
// restore variables
free(imgdata.image);
imgdata.image = s_image;
if (imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS)
imgdata.sizes.flip = s_flip;
T.twidth = S.width;
S.width = s_width;
S.iwidth = s_iwidth;
S.iheight = s_iheight;
T.theight = S.height;
S.height = s_height;
T.tcolors = P1.colors;
P1.colors = s_colors;
P1.filters = s_filters;
libraw_internal_data.unpacker_data.load_flags = s_flags;
}
// ������� thumbnail �� �����, ������ thumb_format � ������������ � ��������
int LibRaw::thumbOK(INT64 maxsz)
{
if (!ID.input)
return 0;
if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
load_raw == &LibRaw::broadcom_load_raw) // RPi
)
return 0;
INT64 fsize = ID.input->size();
if (fsize > 0x7fffffffU)
return 0; // No thumb for raw > 2Gb
int tsize = 0;
int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3;
if (write_thumb == &LibRaw::jpeg_thumb)
tsize = T.tlength;
else if (write_thumb == &LibRaw::ppm_thumb)
tsize = tcol * T.twidth * T.theight;
else if (write_thumb == &LibRaw::ppm16_thumb)
tsize = tcol * T.twidth * T.theight *
((imgdata.params.raw_processing_options &
LIBRAW_PROCESSING_USE_PPM16_THUMBS)
? 2
: 1);
#ifdef USE_X3FTOOLS
else if (write_thumb == &LibRaw::x3f_thumb_loader)
{
tsize = x3f_thumb_size();
}
#endif
else // Kodak => no check
tsize = 1;
if (tsize < 0)
return 0;
if (maxsz > 0 && tsize > maxsz)
return 0;
return (tsize + ID.toffset <= fsize) ? 1 : 0;
}
int LibRaw::dcraw_thumb_writer(const char *fname)
{
// CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD);
if (!fname)
return ENOENT;
FILE *tfp = fopen(fname, "wb");
if (!tfp)
return errno;
if (!T.thumb)
{
fclose(tfp);
return LIBRAW_OUT_OF_ORDER_CALL;
}
try
{
switch (T.tformat)
{
case LIBRAW_THUMBNAIL_JPEG:
jpeg_thumb_writer(tfp, T.thumb, T.tlength);
break;
case LIBRAW_THUMBNAIL_BITMAP:
fprintf(tfp, "P6\n%d %d\n255\n", T.twidth, T.theight);
fwrite(T.thumb, 1, T.tlength, tfp);
break;
default:
fclose(tfp);
return LIBRAW_UNSUPPORTED_THUMBNAIL;
}
fclose(tfp);
return 0;
}
catch (LibRaw_exceptions err)
{
fclose(tfp);
EXCEPTION_HANDLER(err);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_4220_3 |
crossvul-cpp_data_bad_1581_1 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: sw-offload.c
*
* This file contains SW Implementation of checksum computation for IP,TCP,UDP
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
// till IP header size is 8 bit
#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4)
// IPv6 Header RFC 2460 (n*8 bytes)
typedef struct _tagIPv6ExtHeader {
UCHAR ip6ext_next_header; // next header type
UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes
USHORT options; //
} IPv6ExtHeader;
// IP Pseudo Header RFC 768
typedef struct _tagIPv4PseudoHeader {
ULONG ipph_src; // Source address
ULONG ipph_dest; // Destination address
UCHAR ipph_zero; // 0
UCHAR ipph_protocol; // TCP/UDP
USHORT ipph_length; // TCP/UDP length
}tIPv4PseudoHeader;
// IPv6 Pseudo Header RFC 2460
typedef struct _tagIPv6PseudoHeader {
IPV6_ADDRESS ipph_src; // Source address
IPV6_ADDRESS ipph_dest; // Destination address
ULONG ipph_length; // TCP/UDP length
UCHAR z1; // 0
UCHAR z2; // 0
UCHAR z3; // 0
UCHAR ipph_protocol; // TCP/UDP
}tIPv6PseudoHeader;
// IP v6 extension header option
typedef struct _tagIP6_EXT_HDR_OPTION
{
UCHAR Type;
UCHAR Length;
} IP6_EXT_HDR_OPTION, *PIP6_EXT_HDR_OPTION;
#define IP6_EXT_HDR_OPTION_PAD1 (0)
#define IP6_EXT_HDR_OPTION_HOME_ADDR (201)
// IP v6 routing header
typedef struct _tagIP6_TYPE2_ROUTING_HEADER
{
UCHAR NextHdr;
UCHAR HdrLen;
UCHAR RoutingType;
UCHAR SegmentsLeft;
ULONG Reserved;
IPV6_ADDRESS Address;
} IP6_TYPE2_ROUTING_HEADER, *PIP6_TYPE2_ROUTING_HEADER;
#define PROTOCOL_TCP 6
#define PROTOCOL_UDP 17
#define IP_HEADER_LENGTH(pHeader) (((pHeader)->ip_verlen & 0x0F) << 2)
#define IP_HEADER_VERSION(pHeader) (((pHeader)->ip_verlen & 0xF0) >> 4)
#define IP_HEADER_IS_FRAGMENT(pHeader) (((pHeader)->ip_offset & ~0xC0) != 0)
#define IP6_HEADER_VERSION(pHeader) (((pHeader)->ip6_ver_tc & 0xF0) >> 4)
#define ETH_GET_VLAN_HDR(ethHdr) ((PVLAN_HEADER) RtlOffsetToPointer(ethHdr, ETH_PRIORITY_HEADER_OFFSET))
#define VLAN_GET_USER_PRIORITY(vlanHdr) ( (((PUCHAR)(vlanHdr))[2] & 0xE0) >> 5 )
#define VLAN_GET_VLAN_ID(vlanHdr) ( ((USHORT) (((PUCHAR)(vlanHdr))[2] & 0x0F) << 8) | ( ((PUCHAR)(vlanHdr))[3] ) )
#define ETH_PROTO_IP4 (0x0800)
#define ETH_PROTO_IP6 (0x86DD)
#define IP6_HDR_HOP_BY_HOP (0)
#define IP6_HDR_ROUTING (43)
#define IP6_HDR_FRAGMENT (44)
#define IP6_HDR_ESP (50)
#define IP6_HDR_AUTHENTICATION (51)
#define IP6_HDR_NONE (59)
#define IP6_HDR_DESTINATON (60)
#define IP6_HDR_MOBILITY (135)
#define IP6_EXT_HDR_GRANULARITY (8)
static UINT32 RawCheckSumCalculator(PVOID buffer, ULONG len)
{
UINT32 val = 0;
PUSHORT pus = (PUSHORT)buffer;
ULONG count = len >> 1;
while (count--) val += *pus++;
if (len & 1) val += (USHORT)*(PUCHAR)pus;
return val;
}
static __inline USHORT RawCheckSumFinalize(UINT32 val)
{
val = (((val >> 16) | (val << 16)) + val) >> 16;
return (USHORT)~val;
}
static __inline USHORT CheckSumCalculatorFlat(PVOID buffer, ULONG len)
{
return RawCheckSumFinalize(RawCheckSumCalculator(buffer, len));
}
static __inline USHORT CheckSumCalculator(tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG len)
{
tCompletePhysicalAddress *pCurrentPage = &pDataPages[0];
ULONG ulCurrPageOffset = 0;
UINT32 u32RawCSum = 0;
while(ulStartOffset > 0)
{
ulCurrPageOffset = min(pCurrentPage->size, ulStartOffset);
if(ulCurrPageOffset < ulStartOffset)
pCurrentPage++;
ulStartOffset -= ulCurrPageOffset;
}
while(len > 0)
{
PVOID pCurrentPageDataStart = RtlOffsetToPointer(pCurrentPage->Virtual, ulCurrPageOffset);
ULONG ulCurrentPageDataLength = min(len, pCurrentPage->size - ulCurrPageOffset);
u32RawCSum += RawCheckSumCalculator(pCurrentPageDataStart, ulCurrentPageDataLength);
pCurrentPage++;
ulCurrPageOffset = 0;
len -= ulCurrentPageDataLength;
}
return RawCheckSumFinalize(u32RawCSum);
}
/******************************************
IP header checksum calculator
*******************************************/
static __inline VOID CalculateIpChecksum(IPv4Header *pIpHeader)
{
pIpHeader->ip_xsum = 0;
pIpHeader->ip_xsum = CheckSumCalculatorFlat(pIpHeader, IP_HEADER_LENGTH(pIpHeader));
}
static __inline tTcpIpPacketParsingResult
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
}
return res;
}
static __inline tTcpIpPacketParsingResult
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
// may be full or not, but the datagram length is known
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
return res;
}
static __inline tTcpIpPacketParsingResult
QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
{
tTcpIpPacketParsingResult res;
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort;
if (fullLength) {}
else
{
DPrintf(2, ("ip v.%d, iplen %d\n", ip_version, fullLength));
}
}
else if (ip_version == 6)
{
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
//existing extended headers
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
//any other protocol
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
res.xxpFull = len >= fullLength ? 1 : 0;
// bit "more fragments" or fragment offset mean the packet is fragmented
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
static __inline USHORT GetXxpHeaderAndPayloadLen(IPHeader *pIpHeader, tTcpIpPacketParsingResult res)
{
if (res.ipStatus == ppresIPV4)
{
USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4);
USHORT len = swap_short(pIpHeader->v4.ip_length);
return len - headerLength;
}
if (res.ipStatus == ppresIPV6)
{
USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize;
}
return 0;
}
static __inline USHORT CalculateIpv4PseudoHeaderChecksum(IPv4Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv4PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src = pIpHeader->ip_src;
ipph.ipph_dest = pIpHeader->ip_dest;
ipph.ipph_zero = 0;
ipph.ipph_protocol = pIpHeader->ip_protocol;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv6PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src[0] = pIpHeader->ip6_src_address[0];
ipph.ipph_src[1] = pIpHeader->ip6_src_address[1];
ipph.ipph_src[2] = pIpHeader->ip6_src_address[2];
ipph.ipph_src[3] = pIpHeader->ip6_src_address[3];
ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0];
ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1];
ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2];
ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3];
ipph.z1 = ipph.z2 = ipph.z3 = 0;
ipph.ipph_protocol = pIpHeader->ip6_next_header;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader,
tTcpIpPacketParsingResult res,
USHORT headerAndPayloadLen)
{
if (res.ipStatus == ppresIPV4)
return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen);
if (res.ipStatus == ppresIPV6)
return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen);
return 0;
}
static __inline BOOLEAN
CompareNetCheckSumOnEndSystem(USHORT computedChecksum, USHORT arrivedChecksum)
{
//According to RFC 1624 sec. 3
//Checksum verification mechanism should treat 0xFFFF
//checksum value from received packet as 0x0000
if(arrivedChecksum == 0xFFFF)
arrivedChecksum = 0;
return computedChecksum == arrivedChecksum;
}
/******************************************
Calculates IP header checksum calculator
it can be already calculated
the header must be complete!
*******************************************/
static __inline tTcpIpPacketParsingResult
VerifyIpChecksum(
IPv4Header *pIpHeader,
tTcpIpPacketParsingResult known,
BOOLEAN bFix)
{
tTcpIpPacketParsingResult res = known;
if (res.ipCheckSum != ppresIPTooShort)
{
USHORT saved = pIpHeader->ip_xsum;
CalculateIpChecksum(pIpHeader);
res.ipCheckSum = CompareNetCheckSumOnEndSystem(pIpHeader->ip_xsum, saved) ? ppresCSOK : ppresCSBad;
if (!bFix)
pIpHeader->ip_xsum = saved;
else
res.fixedIpCS = res.ipCheckSum == ppresCSBad;
}
return res;
}
/*********************************************
Calculates UDP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateUdpChecksumGivenPseudoCS(UDPHeader *pUdpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG udpLength)
{
pUdpHeader->udp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, udpLength);
}
/*********************************************
Calculates TCP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateTcpChecksumGivenPseudoCS(TCPHeader *pTcpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG tcpLength)
{
pTcpHeader->tcp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, tcpLength);
}
/************************************************
Checks (and fix if required) the TCP checksum
sets flags in result structure according to verification
TcpPseudoOK if valid pseudo CS was found
TcpOK if valid TCP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyTcpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pTcpHeader->tcp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (res.xxpCheckSum != ppresPCSOK || whatToFix)
{
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader)))
{
pTcpHeader->tcp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
//USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length);
pTcpHeader->tcp_xsum = phcs;
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pTcpHeader->tcp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else if (whatToFix)
{
res.xxpStatus = ppresXxpIncomplete;
}
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good TCP CS
// in such rare case we give a priority to TCP CS
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pTcpHeader->tcp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
/************************************************
Checks (and fix if required) the UDP checksum
sets flags in result structure according to verification
UdpPseudoOK if valid pseudo CS was found
UdpOK if valid UDP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyUdpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pUdpHeader->udp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader)))
{
pUdpHeader->udp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum))
{
if (res.xxpFull)
{
pUdpHeader->udp_xsum = phcs;
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pUdpHeader->udp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else
res.xxpCheckSum = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good UDP CS
// in such rare case we give a priority to UDP CS
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pUdpHeader->udp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
static LPCSTR __inline GetPacketCase(tTcpIpPacketParsingResult res)
{
static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" };
if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ?
(res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") :
(res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6");
if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP";
if (res.xxpStatus == ppresXxpOther) return "IP";
return IPCaseName[res.ipStatus];
}
static LPCSTR __inline GetIPCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" };
return CSCaseName[res.ipCheckSum];
}
static LPCSTR __inline GetXxpCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" };
return CSCaseName[res.xxpCheckSum];
}
static __inline VOID PrintOutParsingResult(
tTcpIpPacketParsingResult res,
int level,
LPCSTR procname)
{
DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s\n", procname,
GetPacketCase(res),
GetIPCSCase(res),
res.fixedIpCS ? "(fixed)" : "",
GetXxpCSCase(res),
res.fixedXxpCS ? "(fixed)" : ""));
}
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
static __inline
VOID AnalyzeL3Proto(
USHORT L3Proto,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isIP4 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP4));
packetInfo->isIP6 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP6));
}
static
BOOLEAN AnalyzeL2Hdr(
PNET_PACKET_INFO packetInfo)
{
PETH_HEADER dataBuffer = (PETH_HEADER) packetInfo->headersBuffer;
if (packetInfo->dataLength < ETH_HEADER_SIZE)
return FALSE;
packetInfo->ethDestAddr = dataBuffer->DstAddr;
if (ETH_IS_BROADCAST(dataBuffer))
{
packetInfo->isBroadcast = TRUE;
}
else if (ETH_IS_MULTICAST(dataBuffer))
{
packetInfo->isMulticast = TRUE;
}
else
{
packetInfo->isUnicast = TRUE;
}
if(ETH_HAS_PRIO_HEADER(dataBuffer))
{
PVLAN_HEADER vlanHdr = ETH_GET_VLAN_HDR(dataBuffer);
if(packetInfo->dataLength < ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
packetInfo->hasVlanHeader = TRUE;
packetInfo->Vlan.UserPriority = VLAN_GET_USER_PRIORITY(vlanHdr);
packetInfo->Vlan.VlanId = VLAN_GET_VLAN_ID(vlanHdr);
packetInfo->L2HdrLen = ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE;
AnalyzeL3Proto(vlanHdr->EthType, packetInfo);
}
else
{
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
AnalyzeL3Proto(dataBuffer->EthType, packetInfo);
}
packetInfo->L2PayloadLen = packetInfo->dataLength - packetInfo->L2HdrLen;
return TRUE;
}
static __inline
BOOLEAN SkipIP6ExtensionHeader(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr)
{
IPv6ExtHeader* ip6ExtHdr;
if (*ip6HdrLength + sizeof(*ip6ExtHdr) > dataLength)
return FALSE;
ip6ExtHdr = (IPv6ExtHeader *)RtlOffsetToPointer(ip6Hdr, *ip6HdrLength);
*nextHdr = ip6ExtHdr->ip6ext_next_header;
*ip6HdrLength += (ip6ExtHdr->ip6ext_hdr_len + 1) * IP6_EXT_HDR_GRANULARITY;
return TRUE;
}
static
BOOLEAN AnalyzeIP6RoutingExtension(
PIP6_TYPE2_ROUTING_HEADER routingHdr,
ULONG dataLength,
IPV6_ADDRESS **destAddr)
{
if(dataLength < sizeof(*routingHdr))
return FALSE;
if(routingHdr->RoutingType == 2)
{
if((dataLength != sizeof(*routingHdr)) || (routingHdr->SegmentsLeft != 1))
return FALSE;
*destAddr = &routingHdr->Address;
}
else *destAddr = NULL;
return TRUE;
}
static
BOOLEAN AnalyzeIP6DestinationExtension(
PVOID destHdr,
ULONG dataLength,
IPV6_ADDRESS **homeAddr)
{
while(dataLength != 0)
{
PIP6_EXT_HDR_OPTION optHdr = (PIP6_EXT_HDR_OPTION) destHdr;
ULONG optionLen;
switch(optHdr->Type)
{
case IP6_EXT_HDR_OPTION_HOME_ADDR:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
if(optHdr->Length != sizeof(IPV6_ADDRESS))
return FALSE;
*homeAddr = (IPV6_ADDRESS*) RtlOffsetToPointer(optHdr, sizeof(IP6_EXT_HDR_OPTION));
break;
case IP6_EXT_HDR_OPTION_PAD1:
optionLen = RTL_SIZEOF_THROUGH_FIELD(IP6_EXT_HDR_OPTION, Type);
break;
default:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
break;
}
destHdr = RtlOffsetToPointer(destHdr, optionLen);
if(dataLength < optionLen)
return FALSE;
dataLength -= optionLen;
}
return TRUE;
}
static
BOOLEAN AnalyzeIP6Hdr(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr,
PULONG homeAddrOffset,
PULONG destAddrOffset)
{
*homeAddrOffset = 0;
*destAddrOffset = 0;
*ip6HdrLength = sizeof(*ip6Hdr);
if(dataLength < *ip6HdrLength)
return FALSE;
*nextHdr = ip6Hdr->ip6_next_header;
for(;;)
{
switch (*nextHdr)
{
default:
case IP6_HDR_NONE:
case PROTOCOL_TCP:
case PROTOCOL_UDP:
case IP6_HDR_FRAGMENT:
return TRUE;
case IP6_HDR_DESTINATON:
{
IPV6_ADDRESS *homeAddr = NULL;
ULONG destHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6DestinationExtension(RtlOffsetToPointer(ip6Hdr, destHdrOffset),
*ip6HdrLength - destHdrOffset, &homeAddr))
return FALSE;
*homeAddrOffset = homeAddr ? RtlPointerToOffset(ip6Hdr, homeAddr) : 0;
}
break;
case IP6_HDR_ROUTING:
{
IPV6_ADDRESS *destAddr = NULL;
ULONG routingHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6RoutingExtension((PIP6_TYPE2_ROUTING_HEADER) RtlOffsetToPointer(ip6Hdr, routingHdrOffset),
*ip6HdrLength - routingHdrOffset, &destAddr))
return FALSE;
*destAddrOffset = destAddr ? RtlPointerToOffset(ip6Hdr, destAddr) : 0;
}
break;
case IP6_HDR_HOP_BY_HOP:
case IP6_HDR_ESP:
case IP6_HDR_AUTHENTICATION:
case IP6_HDR_MOBILITY:
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
break;
}
}
}
static __inline
VOID AnalyzeL4Proto(
UCHAR l4Protocol,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isTCP = (l4Protocol == PROTOCOL_TCP);
packetInfo->isUDP = (l4Protocol == PROTOCOL_UDP);
}
static
BOOLEAN AnalyzeL3Hdr(
PNET_PACKET_INFO packetInfo)
{
if(packetInfo->isIP4)
{
IPv4Header *ip4Hdr = (IPv4Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(packetInfo->dataLength < packetInfo->L2HdrLen + sizeof(*ip4Hdr))
return FALSE;
packetInfo->L3HdrLen = IP_HEADER_LENGTH(ip4Hdr);
if ((packetInfo->L3HdrLen < sizeof(*ip4Hdr)) ||
(packetInfo->dataLength < packetInfo->L2HdrLen + packetInfo->L3HdrLen))
return FALSE;
if(IP_HEADER_VERSION(ip4Hdr) != 4)
return FALSE;
packetInfo->isFragment = IP_HEADER_IS_FRAGMENT(ip4Hdr);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(ip4Hdr->ip_protocol, packetInfo);
}
}
else if(packetInfo->isIP6)
{
ULONG homeAddrOffset, destAddrOffset;
UCHAR l4Proto;
IPv6Header *ip6Hdr = (IPv6Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(IP6_HEADER_VERSION(ip6Hdr) != 6)
return FALSE;
if(!AnalyzeIP6Hdr(ip6Hdr, packetInfo->L2PayloadLen,
&packetInfo->L3HdrLen, &l4Proto, &homeAddrOffset, &destAddrOffset))
return FALSE;
if (packetInfo->L3HdrLen > MAX_SUPPORTED_IPV6_HEADERS)
return FALSE;
packetInfo->ip6HomeAddrOffset = (homeAddrOffset) ? packetInfo->L2HdrLen + homeAddrOffset : 0;
packetInfo->ip6DestAddrOffset = (destAddrOffset) ? packetInfo->L2HdrLen + destAddrOffset : 0;
packetInfo->isFragment = (l4Proto == IP6_HDR_FRAGMENT);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(l4Proto, packetInfo);
}
}
return TRUE;
}
BOOLEAN ParaNdis_AnalyzeReceivedPacket(
PVOID headersBuffer,
ULONG dataLength,
PNET_PACKET_INFO packetInfo)
{
NdisZeroMemory(packetInfo, sizeof(*packetInfo));
packetInfo->headersBuffer = headersBuffer;
packetInfo->dataLength = dataLength;
if(!AnalyzeL2Hdr(packetInfo))
return FALSE;
if (!AnalyzeL3Hdr(packetInfo))
return FALSE;
return TRUE;
}
ULONG ParaNdis_StripVlanHeaderMoveHead(PNET_PACKET_INFO packetInfo)
{
PUINT32 pData = (PUINT32) packetInfo->headersBuffer;
ASSERT(packetInfo->hasVlanHeader);
ASSERT(packetInfo->L2HdrLen == ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE);
pData[3] = pData[2];
pData[2] = pData[1];
pData[1] = pData[0];
packetInfo->headersBuffer = RtlOffsetToPointer(packetInfo->headersBuffer, ETH_PRIORITY_HEADER_SIZE);
packetInfo->dataLength -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
packetInfo->ethDestAddr = (PUCHAR) RtlOffsetToPointer(packetInfo->ethDestAddr, ETH_PRIORITY_HEADER_SIZE);
packetInfo->ip6DestAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->ip6HomeAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
return ETH_PRIORITY_HEADER_SIZE;
};
VOID ParaNdis_PadPacketToMinimalLength(PNET_PACKET_INFO packetInfo)
{
// Ethernet standard declares minimal possible packet size
// Packets smaller than that must be padded before transfer
// Ethernet HW pads packets on transmit, however in our case
// some packets do not travel over Ethernet but being routed
// guest-to-guest by virtual switch.
// In this case padding is not performed and we may
// receive packet smaller than minimal allowed size. This is not
// a problem for real life scenarios however WHQL/HCK contains
// tests that check padding of received packets.
// To make these tests happy we have to pad small packets on receive
//NOTE: This function assumes that VLAN header has been already stripped out
if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE)
{
RtlZeroMemory(
RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength),
ETH_MIN_PACKET_SIZE - packetInfo->dataLength);
packetInfo->dataLength = ETH_MIN_PACKET_SIZE;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1581_1 |
crossvul-cpp_data_bad_597_0 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/session/HTTPSession.h>
#include <chrono>
#include <fizz/protocol/AsyncFizzBase.h>
#include <folly/Conv.h>
#include <folly/CppAttributes.h>
#include <folly/Random.h>
#include <wangle/acceptor/ConnectionManager.h>
#include <wangle/acceptor/SocketOptions.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/codec/HTTPChecks.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/session/HTTPSessionController.h>
#include <proxygen/lib/http/session/HTTPSessionStats.h>
#include <folly/io/async/AsyncSSLSocket.h>
#include <folly/io/Cursor.h>
#include <folly/tracing/ScopedTraceSection.h>
using fizz::AsyncFizzBase;
using folly::AsyncSSLSocket;
using folly::AsyncSocket;
using folly::AsyncTransportWrapper;
using folly::AsyncTransport;
using folly::WriteFlags;
using folly::AsyncSocketException;
using folly::io::QueueAppender;
using folly::IOBuf;
using folly::IOBufQueue;
using folly::SocketAddress;
using wangle::TransportInfo;
using std::make_unique;
using std::pair;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
static const uint32_t kMinReadSize = 1460;
static const uint32_t kWriteReadyMax = 65536;
// Lower = higher latency, better prioritization
// Higher = lower latency, less prioritization
static const uint32_t kMaxWritesPerLoop = 32;
static constexpr folly::StringPiece kClientLabel =
"EXPORTER HTTP CERTIFICATE client";
static constexpr folly::StringPiece kServerLabel =
"EXPORTER HTTP CERTIFICATE server";
} // anonymous namespace
namespace proxygen {
HTTPSession::WriteSegment::WriteSegment(
HTTPSession* session,
uint64_t length)
: session_(session),
length_(length) {
}
void
HTTPSession::WriteSegment::remove() {
DCHECK(session_);
DCHECK(listHook.is_linked());
listHook.unlink();
}
void
HTTPSession::WriteSegment::detach() {
remove();
session_ = nullptr;
}
void
HTTPSession::WriteSegment::writeSuccess() noexcept {
// Unlink this write segment from the list before calling
// the session's onWriteSuccess() callback because, in the
// case where this is the last write for the connection,
// onWriteSuccess() looks for an empty write segment list
// as one of the criteria for shutting down the connection.
remove();
// session_ should never be nullptr for a successful write
// The session is only cleared after a write error or timeout, and all
// AsyncTransport write failures are fatal. If session_ is nullptr at this
// point it means the AsyncTransport implementation is not failing
// subsequent writes correctly after an error.
session_->onWriteSuccess(length_);
delete this;
}
void
HTTPSession::WriteSegment::writeErr(size_t bytesWritten,
const AsyncSocketException& ex) noexcept {
// After one segment fails to write, we clear the session_
// pointer in all subsequent write segments, so we ignore their
// writeError() callbacks.
if (session_) {
remove();
session_->onWriteError(bytesWritten, ex);
}
delete this;
}
HTTPSession::HTTPSession(
folly::HHWheelTimer* transactionTimeouts,
AsyncTransportWrapper::UniquePtr sock,
const SocketAddress& localAddr,
const SocketAddress& peerAddr,
HTTPSessionController* controller,
unique_ptr<HTTPCodec> codec,
const TransportInfo& tinfo,
InfoCallback* infoCallback):
HTTPSession(WheelTimerInstance(transactionTimeouts), std::move(sock),
localAddr, peerAddr, controller, std::move(codec),
tinfo, infoCallback) {
}
HTTPSession::HTTPSession(
const WheelTimerInstance& timeout,
AsyncTransportWrapper::UniquePtr sock,
const SocketAddress& localAddr,
const SocketAddress& peerAddr,
HTTPSessionController* controller,
unique_ptr<HTTPCodec> codec,
const TransportInfo& tinfo,
InfoCallback* infoCallback):
HTTPSessionBase(localAddr, peerAddr, controller, tinfo, infoCallback,
std::move(codec)),
writeTimeout_(this),
txnEgressQueue_(isHTTP2CodecProtocol(codec_->getProtocol()) ?
WheelTimerInstance(timeout) :
WheelTimerInstance()),
sock_(std::move(sock)),
timeout_(timeout),
draining_(false),
started_(false),
writesDraining_(false),
resetAfterDrainingWrites_(false),
ingressError_(false),
flowControlTimeout_(this),
drainTimeout_(this),
reads_(SocketState::PAUSED),
writes_(SocketState::UNPAUSED),
ingressUpgraded_(false),
resetSocketOnShutdown_(false),
inLoopCallback_(false),
inResume_(false),
pendingPause_(false) {
byteEventTracker_ = std::make_shared<ByteEventTracker>(this);
initialReceiveWindow_ = receiveStreamWindowSize_ =
receiveSessionWindowSize_ = codec_->getDefaultWindowSize();
codec_.add<HTTPChecks>();
setupCodec();
nextEgressResults_.reserve(maxConcurrentIncomingStreams_);
if (infoCallback_) {
infoCallback_->onCreate(*this);
}
auto controllerPtr = getController();
if (controllerPtr) {
flowControlTimeout_.setTimeoutDuration(
controllerPtr->getSessionFlowControlTimeout());
}
attachToSessionController();
if (!sock_->isReplaySafe()) {
sock_->setReplaySafetyCallback(this);
}
}
uint32_t HTTPSession::getCertAuthSettingVal() {
uint32_t certAuthSettingVal = 0;
constexpr uint16_t settingLen = 4;
std::unique_ptr<folly::IOBuf> ekm;
folly::StringPiece label;
if (isUpstream()) {
label = kClientLabel;
} else {
label = kServerLabel;
}
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
ekm = fizzBase->getEkm(label, nullptr, settingLen);
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return certAuthSettingVal;
}
if (ekm && ekm->computeChainDataLength() == settingLen) {
folly::io::Cursor cursor(ekm.get());
uint32_t ekmVal = cursor.readBE<uint32_t>();
certAuthSettingVal = (ekmVal & 0x3fffffff) | 0x80000000;
}
return certAuthSettingVal;
}
bool HTTPSession::verifyCertAuthSetting(uint32_t value) {
uint32_t certAuthSettingVal = 0;
constexpr uint16_t settingLen = 4;
std::unique_ptr<folly::IOBuf> ekm;
folly::StringPiece label;
if (isUpstream()) {
label = kServerLabel;
} else {
label = kClientLabel;
}
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
ekm = fizzBase->getEkm(label, nullptr, settingLen);
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return false;
}
if (ekm && ekm->computeChainDataLength() == settingLen) {
folly::io::Cursor cursor(ekm.get());
uint32_t ekmVal = cursor.readBE<uint32_t>();
certAuthSettingVal = (ekmVal & 0x3fffffff) | 0x80000000;
} else {
return false;
}
if (certAuthSettingVal == value) {
return true;
} else {
return false;
}
}
void HTTPSession::setupCodec() {
if (!codec_->supportsParallelRequests()) {
// until we support upstream pipelining
maxConcurrentIncomingStreams_ = 1;
maxConcurrentOutgoingStreamsRemote_ = isDownstream() ? 0 : 1;
}
// If a secondary authentication manager is configured for this session, set
// the SETTINGS_HTTP_CERT_AUTH to indicate support for HTTP-layer certificate
// authentication.
uint32_t certAuthSettingVal = 0;
if (secondAuthManager_) {
certAuthSettingVal = getCertAuthSettingVal();
}
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS,
maxConcurrentIncomingStreams_);
if (certAuthSettingVal != 0) {
settings->setSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH,
certAuthSettingVal);
}
}
codec_->generateConnectionPreface(writeBuf_);
if (codec_->supportsSessionFlowControl() && !connFlowControl_) {
connFlowControl_ = new FlowControlFilter(*this, writeBuf_, codec_.call());
codec_.addFilters(std::unique_ptr<FlowControlFilter>(connFlowControl_));
// if we really support switching from spdy <-> h2, we need to update
// existing flow control filter
}
codec_.setCallback(this);
}
HTTPSession::~HTTPSession() {
VLOG(4) << *this << " closing";
CHECK(transactions_.empty());
txnEgressQueue_.dropPriorityNodes();
CHECK(txnEgressQueue_.empty());
DCHECK(!sock_->getReadCallback());
if (writeTimeout_.isScheduled()) {
writeTimeout_.cancelTimeout();
}
if (flowControlTimeout_.isScheduled()) {
flowControlTimeout_.cancelTimeout();
}
runDestroyCallbacks();
}
void HTTPSession::startNow() {
CHECK(!started_);
started_ = true;
codec_->generateSettings(writeBuf_);
if (connFlowControl_) {
connFlowControl_->setReceiveWindowSize(writeBuf_,
receiveSessionWindowSize_);
}
// For HTTP/2 if we are currently draining it means we got notified to
// shutdown before we sent a SETTINGS frame, so we defer sending a GOAWAY
// util we've started and sent SETTINGS.
if (draining_) {
codec_->generateGoaway(writeBuf_,
getGracefulGoawayAck(),
ErrorCode::NO_ERROR);
}
scheduleWrite();
resumeReads();
}
void HTTPSession::setByteEventTracker(
std::shared_ptr<ByteEventTracker> byteEventTracker) {
if (byteEventTracker && byteEventTracker_) {
byteEventTracker->absorb(std::move(*byteEventTracker_));
}
byteEventTracker_ = byteEventTracker;
if (byteEventTracker_) {
byteEventTracker_->setCallback(this);
byteEventTracker_->setTTLBAStats(sessionStats_);
}
}
void HTTPSession::setSessionStats(HTTPSessionStats* stats) {
HTTPSessionBase::setSessionStats(stats);
if (byteEventTracker_) {
byteEventTracker_->setTTLBAStats(stats);
}
}
void HTTPSession::setFlowControl(size_t initialReceiveWindow,
size_t receiveStreamWindowSize,
size_t receiveSessionWindowSize) {
CHECK(!started_);
initialReceiveWindow_ = initialReceiveWindow;
receiveStreamWindowSize_ = receiveStreamWindowSize;
receiveSessionWindowSize_ = receiveSessionWindowSize;
HTTPSessionBase::setReadBufferLimit(receiveSessionWindowSize);
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
initialReceiveWindow_);
}
}
void HTTPSession::setEgressSettings(const SettingsList& inSettings) {
VLOG_IF(4, started_) << "Must flush egress settings to peer";
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
for (const auto& setting: inSettings) {
settings->setSetting(setting.id, setting.value);
}
}
}
void HTTPSession::setMaxConcurrentIncomingStreams(uint32_t num) {
CHECK(!started_);
if (codec_->supportsParallelRequests()) {
maxConcurrentIncomingStreams_ = num;
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS,
maxConcurrentIncomingStreams_);
}
}
}
void HTTPSession::setEgressBytesLimit(uint64_t bytesLimit) {
CHECK(!started_);
egressBytesLimit_ = bytesLimit;
}
void
HTTPSession::readTimeoutExpired() noexcept {
VLOG(3) << "session-level timeout on " << *this;
if (liveTransactions_ != 0) {
// There's at least one open transaction with a read timeout scheduled.
// We got here because the session timeout == the transaction timeout.
// Ignore, since the transaction is going to timeout very soon.
VLOG(4) << *this <<
"ignoring session timeout, transaction timeout imminent";
resetTimeout();
return;
}
if (!transactions_.empty()) {
// There are one or more transactions, but none of them are live.
// That's valid if they've all received their full ingress messages
// and are waiting for their Handlers to process those messages.
VLOG(4) << *this <<
"ignoring session timeout, no transactions awaiting reads";
resetTimeout();
return;
}
VLOG(4) << *this << " Timeout with nothing pending";
setCloseReason(ConnectionCloseReason::TIMEOUT);
auto controller = getController();
if (controller) {
timeout_.scheduleTimeout(&drainTimeout_,
controller->getGracefulShutdownTimeout());
}
notifyPendingShutdown();
}
void
HTTPSession::writeTimeoutExpired() noexcept {
VLOG(4) << "Write timeout for " << *this;
CHECK(!pendingWrites_.empty());
DestructorGuard g(this);
setCloseReason(ConnectionCloseReason::TIMEOUT);
shutdownTransportWithReset(kErrorWriteTimeout);
}
void
HTTPSession::flowControlTimeoutExpired() noexcept {
VLOG(4) << "Flow control timeout for " << *this;
DestructorGuard g(this);
setCloseReason(ConnectionCloseReason::TIMEOUT);
shutdownTransport(true, true);
}
void
HTTPSession::describe(std::ostream& os) const {
os << "proto=" << getCodecProtocolString(codec_->getProtocol());
if (isDownstream()) {
os << ", UA=" << codec_->getUserAgent()
<< ", downstream=" << getPeerAddress() << ", " << getLocalAddress()
<< "=local";
} else {
os << ", local=" << getLocalAddress() << ", " << getPeerAddress()
<< "=upstream";
}
}
bool
HTTPSession::isBusy() const {
return !transactions_.empty() || codec_->isBusy();
}
void
HTTPSession::notifyPendingEgress() noexcept {
scheduleWrite();
}
void
HTTPSession::notifyPendingShutdown() {
VLOG(4) << *this << " notified pending shutdown";
drain();
}
void
HTTPSession::closeWhenIdle() {
// If drain() already called, this is a noop
drain();
// Generate the second GOAWAY now. No-op if second GOAWAY already sent.
if (codec_->generateGoaway(writeBuf_,
codec_->getLastIncomingStreamID(),
ErrorCode::NO_ERROR)) {
scheduleWrite();
}
if (!isBusy() && !hasMoreWrites()) {
// if we're already idle, close now
dropConnection();
}
}
void HTTPSession::immediateShutdown() {
if (isLoopCallbackScheduled()) {
cancelLoopCallback();
}
if (shutdownTransportCb_) {
shutdownTransportCb_.reset();
}
// checkForShutdown only closes the connection if these conditions are true
DCHECK(writesShutdown());
DCHECK(transactions_.empty());
checkForShutdown();
}
void
HTTPSession::dropConnection() {
VLOG(4) << "dropping " << *this;
if (!sock_ || (readsShutdown() && writesShutdown())) {
VLOG(4) << *this << " already shutdown";
return;
}
setCloseReason(ConnectionCloseReason::SHUTDOWN);
if (transactions_.empty() && !hasMoreWrites()) {
DestructorGuard dg(this);
shutdownTransport(true, true);
// shutdownTransport might have generated a write (goaway)
// If so, writes will not be shutdown, so fall through to
// shutdownTransportWithReset.
if (readsShutdown() && writesShutdown()) {
immediateShutdown();
return;
}
}
shutdownTransportWithReset(kErrorDropped);
}
void HTTPSession::dumpConnectionState(uint8_t /*loglevel*/) {}
bool HTTPSession::isUpstream() const {
return codec_->getTransportDirection() == TransportDirection::UPSTREAM;
}
bool HTTPSession::isDownstream() const {
return codec_->getTransportDirection() == TransportDirection::DOWNSTREAM;
}
void
HTTPSession::getReadBuffer(void** buf, size_t* bufSize) {
FOLLY_SCOPED_TRACE_SECTION("HTTPSession - getReadBuffer");
pair<void*,uint32_t> readSpace =
readBuf_.preallocate(kMinReadSize, HTTPSessionBase::maxReadBufferSize_);
*buf = readSpace.first;
*bufSize = readSpace.second;
}
void
HTTPSession::readDataAvailable(size_t readSize) noexcept {
FOLLY_SCOPED_TRACE_SECTION(
"HTTPSession - readDataAvailable", "readSize", readSize);
VLOG(10) << "read completed on " << *this << ", bytes=" << readSize;
DestructorGuard dg(this);
resetTimeout();
readBuf_.postallocate(readSize);
if (infoCallback_) {
infoCallback_->onRead(*this, readSize);
}
processReadData();
}
bool
HTTPSession::isBufferMovable() noexcept {
return true;
}
void
HTTPSession::readBufferAvailable(std::unique_ptr<IOBuf> readBuf) noexcept {
size_t readSize = readBuf->computeChainDataLength();
FOLLY_SCOPED_TRACE_SECTION(
"HTTPSession - readBufferAvailable", "readSize", readSize);
VLOG(5) << "read completed on " << *this << ", bytes=" << readSize;
DestructorGuard dg(this);
resetTimeout();
readBuf_.append(std::move(readBuf));
if (infoCallback_) {
infoCallback_->onRead(*this, readSize);
}
processReadData();
}
void
HTTPSession::processReadData() {
FOLLY_SCOPED_TRACE_SECTION("HTTPSession - processReadData");
// skip any empty IOBufs before feeding CODEC.
while (readBuf_.front() != nullptr && readBuf_.front()->length() == 0) {
readBuf_.pop_front();
}
// Pass the ingress data through the codec to parse it. The codec
// will invoke various methods of the HTTPSession as callbacks.
const IOBuf* currentReadBuf;
// It's possible for the last buffer in a chain to be empty here.
// AsyncTransport saw fd activity so asked for a read buffer, but it was
// SSL traffic and not enough to decrypt a whole record. Later we invoke
// this function from the loop callback.
while (!ingressError_ &&
readsUnpaused() &&
((currentReadBuf = readBuf_.front()) != nullptr &&
currentReadBuf->length() != 0)) {
// We're about to parse, make sure the parser is not paused
codec_->setParserPaused(false);
size_t bytesParsed = codec_->onIngress(*currentReadBuf);
if (bytesParsed == 0) {
// If the codec didn't make any progress with current input, we
// better get more.
break;
}
readBuf_.trimStart(bytesParsed);
}
}
void
HTTPSession::readEOF() noexcept {
DestructorGuard guard(this);
VLOG(4) << "EOF on " << *this;
// for SSL only: error without any bytes from the client might happen
// due to client-side issues with the SSL cert. Note that it can also
// happen if the client sends a SPDY frame header but no body.
if (infoCallback_
&& transportInfo_.secure && getNumTxnServed() == 0 && readBuf_.empty()) {
infoCallback_->onIngressError(*this, kErrorClientSilent);
}
// Shut down reads, and also shut down writes if there are no
// transactions. (If there are active transactions, leave the
// write side of the socket open so those transactions can
// finish generating responses.)
setCloseReason(ConnectionCloseReason::READ_EOF);
shutdownTransport(true, transactions_.empty());
}
void
HTTPSession::readErr(const AsyncSocketException& ex) noexcept {
DestructorGuard guard(this);
VLOG(4) << "read error on " << *this << ": " << ex.what();
auto sslEx = dynamic_cast<const folly::SSLException*>(&ex);
if (infoCallback_ && sslEx) {
if (sslEx->getSSLError() == folly::SSLError::CLIENT_RENEGOTIATION) {
infoCallback_->onIngressError(*this, kErrorClientRenegotiation);
}
}
// We're definitely finished reading. Don't close the write side
// of the socket if there are outstanding transactions, though.
// Instead, give the transactions a chance to produce any remaining
// output.
if (sslEx && sslEx->getSSLError() == folly::SSLError::SSL_ERROR) {
transportInfo_.sslError = ex.what();
}
setCloseReason(ConnectionCloseReason::IO_READ_ERROR);
shutdownTransport(true, transactions_.empty(), ex.what());
}
HTTPTransaction*
HTTPSession::newPushedTransaction(
HTTPCodec::StreamID assocStreamId,
HTTPTransaction::PushHandler* handler) noexcept {
if (!codec_->supportsPushTransactions()) {
return nullptr;
}
CHECK(isDownstream());
CHECK_NOTNULL(handler);
if (draining_ || (outgoingStreams_ >= maxConcurrentOutgoingStreamsRemote_)) {
// This session doesn't support any more push transactions
// This could be an actual problem - since a single downstream SPDY session
// might be connected to N upstream hosts, each of which send M pushes,
// which exceeds the limit.
// should we queue?
return nullptr;
}
HTTPTransaction* txn = createTransaction(codec_->createStream(),
assocStreamId,
HTTPCodec::NoExAttributes);
if (!txn) {
return nullptr;
}
DestructorGuard dg(this);
auto txnID = txn->getID();
txn->setHandler(handler);
setNewTransactionPauseState(txnID);
return txn;
}
HTTPTransaction* FOLLY_NULLABLE
HTTPSession::newExTransaction(
HTTPTransaction::Handler* handler,
HTTPCodec::StreamID controlStream,
bool unidirectional) noexcept {
CHECK(handler && controlStream > 0);
auto eSettings = codec_->getEgressSettings();
if (!eSettings || !eSettings->getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
LOG(ERROR) << getCodecProtocolString(codec_->getProtocol())
<< " does not support ExTransaction";
return nullptr;
}
if (draining_ || (outgoingStreams_ >= maxConcurrentOutgoingStreamsRemote_)) {
LOG(ERROR) << "cannot support any more transactions in " << *this;
return nullptr;
}
DCHECK(started_);
HTTPTransaction* txn =
createTransaction(codec_->createStream(),
HTTPCodec::NoStream,
HTTPCodec::ExAttributes(controlStream, unidirectional));
if (!txn) {
return nullptr;
}
DestructorGuard dg(this);
txn->setHandler(handler);
setNewTransactionPauseState(txn->getID());
return txn;
}
size_t HTTPSession::getCodecSendWindowSize() const {
const HTTPSettings* settings = codec_->getIngressSettings();
if (settings) {
return settings->getSetting(SettingsId::INITIAL_WINDOW_SIZE,
codec_->getDefaultWindowSize());
}
return codec_->getDefaultWindowSize();
}
void
HTTPSession::setNewTransactionPauseState(HTTPCodec::StreamID streamID) {
if (!egressLimitExceeded()) {
return;
}
auto txn = findTransaction(streamID);
if (txn) {
// If writes are paused, start this txn off in the egress paused state
VLOG(4) << *this << " starting streamID=" << txn->getID()
<< " egress paused, numActiveWrites_=" << numActiveWrites_;
txn->pauseEgress();
}
}
http2::PriorityUpdate
HTTPSession::getMessagePriority(const HTTPMessage* msg) {
http2::PriorityUpdate h2Pri = http2::DefaultPriority;
// if HTTP2 priorities are enabled, get them from the message
// and ignore otherwise
if (getHTTP2PrioritiesEnabled() && msg) {
auto res = msg->getHTTP2Priority();
if (res) {
h2Pri.streamDependency = std::get<0>(*res);
h2Pri.exclusive = std::get<1>(*res);
h2Pri.weight = std::get<2>(*res);
} else {
// HTTPMessage with setPriority called explicitly
h2Pri.streamDependency =
codec_->mapPriorityToDependency(msg->getPriority());
}
}
return h2Pri;
}
void
HTTPSession::onMessageBegin(HTTPCodec::StreamID streamID, HTTPMessage* msg) {
VLOG(4) << "processing new msg streamID=" << streamID << " " << *this;
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
HTTPTransaction* txn = findTransaction(streamID);
if (txn) {
if (isDownstream() && txn->isPushed()) {
// Push streams are unidirectional (half-closed). If the downstream
// attempts to send ingress, abort with STREAM_CLOSED error.
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
"Downstream attempts to send ingress, abort.");
ex.setCodecStatusCode(ErrorCode::STREAM_CLOSED);
txn->onError(ex);
}
return; // If this transaction is already registered, no need to add it now
}
http2::PriorityUpdate messagePriority = getMessagePriority(msg);
txn = createTransaction(streamID, HTTPCodec::NoStream,
HTTPCodec::NoExAttributes, messagePriority);
if (!txn) {
return; // This could happen if the socket is bad.
}
if (!codec_->supportsParallelRequests() && getPipelineStreamCount() > 1) {
// The previous transaction hasn't completed yet. Pause reads until
// it completes; this requires pausing both transactions.
// HTTP/1.1 pipeline is detected, and which is incompactible with
// ByteEventTracker. Drain all the ByteEvents
CHECK(byteEventTracker_);
byteEventTracker_->drainByteEvents();
// drainByteEvents() may detach txn(s). Don't pause read if one txn left
if (getPipelineStreamCount() < 2) {
DCHECK(readsUnpaused());
return;
}
// There must be at least two transactions (we just checked). The previous
// txns haven't completed yet. Pause reads until they complete
DCHECK_GE(transactions_.size(), 2);
for (auto it = ++transactions_.rbegin(); it != transactions_.rend(); ++it) {
DCHECK(it->second.isIngressEOMSeen());
it->second.pauseIngress();
}
transactions_.rbegin()->second.pauseIngress();
DCHECK_EQ(liveTransactions_, 0);
DCHECK(readsPaused());
}
}
void
HTTPSession::onPushMessageBegin(HTTPCodec::StreamID streamID,
HTTPCodec::StreamID assocStreamID,
HTTPMessage* msg) {
VLOG(4) << "processing new push promise streamID=" << streamID
<< " on assocStreamID=" << assocStreamID << " " << *this;
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
if (assocStreamID == 0) {
VLOG(2) << "push promise " << streamID << " should be associated with "
<< "an active stream=" << assocStreamID << " " << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
if (isDownstream()) {
VLOG(2) << "push promise cannot be sent to upstream " << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
HTTPTransaction* assocTxn = findTransaction(assocStreamID);
if (!assocTxn || assocTxn->isIngressEOMSeen()) {
VLOG(2) << "cannot find the assocTxn=" << assocTxn
<< ", or assoc stream is already closed by upstream" << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
http2::PriorityUpdate messagePriority = getMessagePriority(msg);
auto txn = createTransaction(streamID, assocStreamID,
HTTPCodec::NoExAttributes, messagePriority);
if (!txn) {
return; // This could happen if the socket is bad.
}
if (!assocTxn->onPushedTransaction(txn)) {
VLOG(1) << "Failed to add pushed txn " << streamID
<< " to assoc txn " << assocStreamID << " on " << *this;
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("Failed to add pushed transaction ", streamID));
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
onError(streamID, ex, true);
}
}
void
HTTPSession::onExMessageBegin(HTTPCodec::StreamID streamID,
HTTPCodec::StreamID controlStream,
bool unidirectional,
HTTPMessage* msg) {
VLOG(4) << "processing new ExMessage=" << streamID
<< " on controlStream=" << controlStream << ", " << *this;
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
if (controlStream == 0) {
LOG(ERROR) << "ExMessage=" << streamID << " should have an active control "
<< "stream=" << controlStream << ", " << *this;
invalidStream(streamID, ErrorCode::PROTOCOL_ERROR);
return;
}
HTTPTransaction* controlTxn = findTransaction(controlStream);
if (!controlTxn) {
// control stream is broken, or remote sends a bogus stream id
LOG(ERROR) << "no control stream=" << controlStream << ", " << *this;
return;
}
http2::PriorityUpdate messagePriority = getMessagePriority(msg);
auto txn = createTransaction(streamID,
HTTPCodec::NoStream,
HTTPCodec::ExAttributes(controlStream,
unidirectional),
messagePriority);
if (!txn) {
return; // This could happen if the socket is bad.
}
// control stream may be paused if the upstream is not ready yet
if (controlTxn->isIngressPaused()) {
txn->pauseIngress();
}
}
void
HTTPSession::onHeadersComplete(HTTPCodec::StreamID streamID,
unique_ptr<HTTPMessage> msg) {
// The codec's parser detected the end of an ingress message's
// headers.
VLOG(4) << "processing ingress headers complete for " << *this <<
", streamID=" << streamID;
if (!codec_->isReusable()) {
setCloseReason(ConnectionCloseReason::REQ_NOTREUSABLE);
}
if (infoCallback_) {
infoCallback_->onIngressMessage(*this, *msg.get());
}
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
const char* sslCipher =
transportInfo_.sslCipher ? transportInfo_.sslCipher->c_str() : nullptr;
msg->setSecureInfo(transportInfo_.sslVersion, sslCipher);
msg->setSecure(transportInfo_.secure);
auto controlStreamID = txn->getControlStream();
if (controlStreamID) {
auto controlTxn = findTransaction(*controlStreamID);
if (!controlTxn) {
VLOG(2) << "txn=" << streamID << " with a broken controlTxn="
<< *controlStreamID << " " << *this;
HTTPException ex(
HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("broken controlTxn ", *controlStreamID));
onError(streamID, ex, true);
return;
}
// Call onExTransaction() only for requests.
if (txn->isRemoteInitiated() && !controlTxn->onExTransaction(txn)) {
VLOG(2) << "Failed to add exTxn=" << streamID
<< " to controlTxn=" << *controlStreamID << ", " << *this;
HTTPException ex(
HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("Fail to add exTxn ", streamID));
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
onError(streamID, ex, true);
return;
}
} else {
setupOnHeadersComplete(txn, msg.get());
}
// The txn may have already been aborted by the handler.
// Verify that the txn still exists before ingress callbacks.
txn = findTransaction(streamID);
if (!txn) {
return;
}
if (!txn->getHandler()) {
txn->sendAbort();
return;
}
// Tell the Transaction to start processing the message now
// that the full ingress headers have arrived.
txn->onIngressHeadersComplete(std::move(msg));
}
void
HTTPSession::onBody(HTTPCodec::StreamID streamID,
unique_ptr<IOBuf> chain, uint16_t padding) {
FOLLY_SCOPED_TRACE_SECTION("HTTPSession - onBody");
DestructorGuard dg(this);
// The codec's parser detected part of the ingress message's
// entity-body.
uint64_t length = chain->computeChainDataLength();
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
if (connFlowControl_ &&
connFlowControl_->ingressBytesProcessed(writeBuf_, length)) {
scheduleWrite();
}
invalidStream(streamID);
return;
}
if (HTTPSessionBase::onBodyImpl(std::move(chain), length, padding, txn)) {
VLOG(4) << *this << " pausing due to read limit exceeded.";
pauseReads();
}
}
void HTTPSession::onChunkHeader(HTTPCodec::StreamID streamID,
size_t length) {
// The codec's parser detected a chunk header (meaning that this
// connection probably is HTTP/1.1).
//
// After calling onChunkHeader(), the codec will call onBody() zero
// or more times and then call onChunkComplete().
//
// The reason for this callback on the chunk header is to support
// an optimization. In general, the job of the codec is to present
// the HTTPSession with an abstract view of a message,
// with all the details of wire formatting hidden. However, there's
// one important case where we want to know about chunking: reverse
// proxying where both the client and server streams are HTTP/1.1.
// In that scenario, we preserve the server's chunk boundaries when
// sending the response to the client, in order to avoid possibly
// making the egress packetization worse by rechunking.
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
txn->onIngressChunkHeader(length);
}
void HTTPSession::onChunkComplete(HTTPCodec::StreamID streamID) {
// The codec's parser detected the end of the message body chunk
// associated with the most recent call to onChunkHeader().
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
txn->onIngressChunkComplete();
}
void
HTTPSession::onTrailersComplete(HTTPCodec::StreamID streamID,
unique_ptr<HTTPHeaders> trailers) {
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
txn->onIngressTrailers(std::move(trailers));
}
void
HTTPSession::onMessageComplete(HTTPCodec::StreamID streamID,
bool upgrade) {
DestructorGuard dg(this);
// The codec's parser detected the end of the ingress message for
// this transaction.
VLOG(4) << "processing ingress message complete for " << *this <<
", streamID=" << streamID;
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
invalidStream(streamID);
return;
}
if (upgrade) {
/* Send the upgrade callback to the transaction and the handler.
* Currently we support upgrades for only HTTP sessions and not SPDY
* sessions.
*/
ingressUpgraded_ = true;
txn->onIngressUpgrade(UpgradeProtocol::TCP);
return;
}
// txnIngressFinished = !1xx response
const bool txnIngressFinished =
txn->isDownstream() || !txn->extraResponseExpected();
if (txnIngressFinished) {
decrementTransactionCount(txn, true, false);
}
txn->onIngressEOM();
// The codec knows, based on the semantics of whatever protocol it
// supports, whether it's valid for any more ingress messages to arrive
// after this one. For example, an HTTP/1.1 request containing
// "Connection: close" indicates the end of the ingress, whereas a
// SPDY session generally can handle more messages at any time.
//
// If the connection is not reusable, we close the read side of it
// but not the write side. There are two reasons why more writes
// may occur after this point:
// * If there are previous writes buffered up in the pendingWrites_
// queue, we need to attempt to complete them.
// * The Handler associated with the transaction may want to
// produce more egress data when the ingress message is fully
// complete. (As a common example, an application that handles
// form POSTs may not be able to even start generating a response
// until it has received the full request body.)
//
// There may be additional checks that need to be performed that are
// specific to requests or responses, so we call the subclass too.
if (!codec_->isReusable() &&
txnIngressFinished &&
!codec_->supportsParallelRequests()) {
VLOG(4) << *this << " cannot reuse ingress";
shutdownTransport(true, false);
}
}
void HTTPSession::onError(HTTPCodec::StreamID streamID,
const HTTPException& error, bool newTxn) {
DestructorGuard dg(this);
// The codec detected an error in the ingress stream, possibly bad
// syntax, a truncated message, or bad semantics in the frame. If reads
// are paused, queue up the event; otherwise, process it now.
VLOG(4) << "Error on " << *this << ", streamID=" << streamID
<< ", " << error;
if (ingressError_) {
return;
}
if (!codec_->supportsParallelRequests()) {
// this error should only prevent us from reading/handling more errors
// on serial streams
ingressError_ = true;
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
}
if ((streamID == 0) && infoCallback_) {
infoCallback_->onIngressError(*this, kErrorMessage);
}
if (!streamID) {
ingressError_ = true;
onSessionParseError(error);
return;
}
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
if (error.hasHttpStatusCode() && streamID != 0) {
// If the error has an HTTP code, then parsing was fine, it just was
// illegal in a higher level way
txn = createTransaction(streamID, HTTPCodec::NoStream,
HTTPCodec::NoExAttributes);
if (infoCallback_) {
infoCallback_->onRequestBegin(*this);
}
if (txn) {
handleErrorDirectly(txn, error);
}
} else if (newTxn) {
onNewTransactionParseError(streamID, error);
} else {
VLOG(4) << *this << " parse error with invalid transaction";
invalidStream(streamID);
}
return;
}
if (!txn->getHandler() &&
txn->getEgressState() == HTTPTransactionEgressSM::State::Start) {
handleErrorDirectly(txn, error);
return;
}
txn->onError(error);
if (!codec_->isReusable() && transactions_.empty()) {
VLOG(4) << *this << "shutdown from onError";
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
shutdownTransport(true, true);
}
}
void HTTPSession::onAbort(HTTPCodec::StreamID streamID,
ErrorCode code) {
VLOG(4) << "stream abort on " << *this << ", streamID=" << streamID
<< ", code=" << getErrorCodeString(code);
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
VLOG(4) << *this << " abort for unrecognized transaction, streamID= "
<< streamID;
return;
}
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("Stream aborted, streamID=",
streamID, ", code=", getErrorCodeString(code)));
ex.setProxygenError(kErrorStreamAbort);
ex.setCodecStatusCode(code);
DestructorGuard dg(this);
if (isDownstream() && !txn->getAssocTxnId() && code == ErrorCode::CANCEL) {
// Cancelling the assoc txn cancels all push txns
for (auto it = txn->getPushedTransactions().begin();
it != txn->getPushedTransactions().end(); ) {
auto pushTxn = findTransaction(*it);
++it;
DCHECK(pushTxn != nullptr);
pushTxn->onError(ex);
}
}
auto exTxns = txn->getExTransactions();
for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
auto exTxn = findTransaction(*it);
if (exTxn) {
exTxn->onError(ex);
}
}
txn->onError(ex);
}
void HTTPSession::onGoaway(uint64_t lastGoodStreamID,
ErrorCode code,
std::unique_ptr<folly::IOBuf> debugData) {
DestructorGuard g(this);
VLOG(4) << "GOAWAY on " << *this << ", code=" << getErrorCodeString(code);
setCloseReason(ConnectionCloseReason::GOAWAY);
// Drain active transactions and prevent new transactions
drain();
// We give the less-forceful onGoaway() first so that transactions have
// a chance to do stat tracking before potentially getting a forceful
// onError().
invokeOnAllTransactions(&HTTPTransaction::onGoaway, code);
// Abort transactions which have been initiated but not created
// successfully at the remote end. Upstream transactions are created
// with odd transaction IDs and downstream transactions with even IDs.
vector<HTTPCodec::StreamID> ids;
auto firstStream = HTTPCodec::NoStream;
for (const auto& txn: transactions_) {
auto streamID = txn.first;
if (((bool)(streamID & 0x01) == isUpstream()) &&
(streamID > lastGoodStreamID)) {
if (firstStream == HTTPCodec::NoStream) {
// transactions_ is a set so it should be sorted by stream id.
// We will defer adding the firstStream to the id list until
// we can determine whether we have a codec error code.
firstStream = streamID;
continue;
}
ids.push_back(streamID);
}
}
if (firstStream != HTTPCodec::NoStream && code != ErrorCode::NO_ERROR) {
// If we get a codec error, we will attempt to blame the first stream
// by delivering a specific error to it and let the rest of the streams
// get a normal unacknowledged stream error.
ProxygenError err = kErrorStreamUnacknowledged;
string debugInfo = (debugData) ?
folly::to<string>(" with debug info: ", (char*)debugData->data()) : "";
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>(getErrorString(err),
" on transaction id: ", *firstStream,
" with codec error: ", getErrorCodeString(code),
debugInfo));
ex.setProxygenError(err);
errorOnTransactionId(*firstStream, std::move(ex));
} else if (firstStream != HTTPCodec::NoStream) {
ids.push_back(*firstStream);
}
errorOnTransactionIds(ids, kErrorStreamUnacknowledged);
}
void HTTPSession::onPingRequest(uint64_t uniqueID) {
VLOG(4) << *this << " got ping request with id=" << uniqueID;
TimePoint timestamp = getCurrentTime();
// Insert the ping reply to the head of writeBuf_
folly::IOBufQueue pingBuf(folly::IOBufQueue::cacheChainLength());
codec_->generatePingReply(pingBuf, uniqueID);
size_t pingSize = pingBuf.chainLength();
pingBuf.append(writeBuf_.move());
writeBuf_.append(pingBuf.move());
if (byteEventTracker_) {
byteEventTracker_->addPingByteEvent(pingSize, timestamp, bytesScheduled_);
}
scheduleWrite();
}
void HTTPSession::onPingReply(uint64_t uniqueID) {
VLOG(4) << *this << " got ping reply with id=" << uniqueID;
if (infoCallback_) {
infoCallback_->onPingReplyReceived();
}
}
void HTTPSession::onWindowUpdate(HTTPCodec::StreamID streamID,
uint32_t amount) {
VLOG(4) << *this << " got window update on streamID=" << streamID << " for "
<< amount << " bytes.";
HTTPTransaction* txn = findTransaction(streamID);
if (!txn) {
// We MUST be using SPDY/3+ if we got WINDOW_UPDATE. The spec says that -
//
// A sender should ignore all the WINDOW_UPDATE frames associated with the
// stream after it send the last frame for the stream.
//
// TODO: Only ignore if this is from some past transaction
return;
}
txn->onIngressWindowUpdate(amount);
}
void HTTPSession::onSettings(const SettingsList& settings) {
DestructorGuard g(this);
for (auto& setting : settings) {
if (setting.id == SettingsId::INITIAL_WINDOW_SIZE) {
onSetSendWindow(setting.value);
} else if (setting.id == SettingsId::MAX_CONCURRENT_STREAMS) {
onSetMaxInitiatedStreams(setting.value);
} else if (setting.id == SettingsId::SETTINGS_HTTP_CERT_AUTH) {
if (!(verifyCertAuthSetting(setting.value))) {
return;
}
}
}
if (codec_->generateSettingsAck(writeBuf_) > 0) {
scheduleWrite();
}
if (infoCallback_) {
infoCallback_->onSettings(*this, settings);
}
}
void HTTPSession::onSettingsAck() {
VLOG(4) << *this << " received settings ack";
if (infoCallback_) {
infoCallback_->onSettingsAck(*this);
}
}
void HTTPSession::onPriority(HTTPCodec::StreamID streamID,
const HTTPMessage::HTTPPriority& pri) {
if (!getHTTP2PrioritiesEnabled()) {
return;
}
http2::PriorityUpdate h2Pri{std::get<0>(pri), std::get<1>(pri),
std::get<2>(pri)};
HTTPTransaction* txn = findTransaction(streamID);
if (txn) {
// existing txn, change pri
txn->onPriorityUpdate(h2Pri);
} else {
// virtual node
txnEgressQueue_.addOrUpdatePriorityNode(streamID, h2Pri);
}
}
void HTTPSession::onCertificateRequest(uint16_t requestId,
std::unique_ptr<IOBuf> authRequest) {
DestructorGuard dg(this);
VLOG(4) << "CERTIFICATE_REQUEST on" << *this << ", requestId=" << requestId;
std::pair<uint16_t, std::unique_ptr<folly::IOBuf>> authenticator;
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
if (isUpstream()) {
authenticator =
secondAuthManager_->getAuthenticator(*fizzBase,
TransportDirection::UPSTREAM,
requestId,
std::move(authRequest));
} else {
authenticator =
secondAuthManager_->getAuthenticator(*fizzBase,
TransportDirection::DOWNSTREAM,
requestId,
std::move(authRequest));
}
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return;
}
if (codec_->generateCertificate(writeBuf_,
authenticator.first,
std::move(authenticator.second)) > 0) {
scheduleWrite();
}
}
void HTTPSession::onCertificate(uint16_t certId,
std::unique_ptr<IOBuf> authenticator) {
DestructorGuard dg(this);
VLOG(4) << "CERTIFICATE on" << *this << ", certId=" << certId;
bool isValid = false;
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
if (isUpstream()) {
isValid = secondAuthManager_->validateAuthenticator(
*fizzBase,
TransportDirection::UPSTREAM,
certId,
std::move(authenticator));
} else {
isValid = secondAuthManager_->validateAuthenticator(
*fizzBase,
TransportDirection::DOWNSTREAM,
certId,
std::move(authenticator));
}
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return;
}
if (isValid) {
VLOG(4) << "Successfully validated the authenticator provided by the peer.";
} else {
VLOG(4) << "Failed to validate the authenticator provided by the peer";
}
}
bool HTTPSession::onNativeProtocolUpgradeImpl(
HTTPCodec::StreamID streamID, std::unique_ptr<HTTPCodec> codec,
const std::string& protocolString) {
CHECK_EQ(streamID, 1);
HTTPTransaction* txn = findTransaction(streamID);
CHECK(txn);
// only HTTP1xCodec calls onNativeProtocolUpgrade
CHECK(!codec_->supportsParallelRequests());
// Reset to defaults
maxConcurrentIncomingStreams_ = 100;
maxConcurrentOutgoingStreamsRemote_ = 10000;
// overwrite destination, delay current codec deletion until the end
// of the event loop
auto oldCodec = codec_.setDestination(std::move(codec));
sock_->getEventBase()->runInLoop([oldCodec = std::move(oldCodec)] () {});
onCodecChanged();
setupCodec();
// txn will be streamID=1, have to make a placeholder
(void)codec_->createStream();
// This can happen if flow control was not explicitly set, and it got the
// HTTP1xCodec defaults. Reset to the new codec default
if (initialReceiveWindow_ == 0 || receiveStreamWindowSize_ == 0 ||
receiveSessionWindowSize_ == 0) {
initialReceiveWindow_ = receiveStreamWindowSize_ =
receiveSessionWindowSize_ = codec_->getDefaultWindowSize();
}
// trigger settings frame that would have gone out in startNow()
HTTPSettings* settings = codec_->getEgressSettings();
if (settings) {
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
initialReceiveWindow_);
}
sendSettings();
if (connFlowControl_) {
connFlowControl_->setReceiveWindowSize(writeBuf_,
receiveSessionWindowSize_);
scheduleWrite();
}
// Convert the transaction that contained the Upgrade header
txn->reset(codec_->supportsStreamFlowControl(),
initialReceiveWindow_,
receiveStreamWindowSize_,
getCodecSendWindowSize());
if (!transportInfo_.secure &&
(!transportInfo_.appProtocol ||
transportInfo_.appProtocol->empty())) {
transportInfo_.appProtocol = std::make_shared<string>(
protocolString);
}
return true;
}
void HTTPSession::onSetSendWindow(uint32_t windowSize) {
VLOG(4) << *this << " got send window size adjustment. new=" << windowSize;
invokeOnAllTransactions(&HTTPTransaction::onIngressSetSendWindow,
windowSize);
}
void HTTPSession::onSetMaxInitiatedStreams(uint32_t maxTxns) {
VLOG(4) << *this << " got new maximum number of concurrent txns "
<< "we can initiate: " << maxTxns;
const bool didSupport = supportsMoreTransactions();
maxConcurrentOutgoingStreamsRemote_ = maxTxns;
if (infoCallback_ && didSupport != supportsMoreTransactions()) {
if (didSupport) {
infoCallback_->onSettingsOutgoingStreamsFull(*this);
} else {
infoCallback_->onSettingsOutgoingStreamsNotFull(*this);
}
}
}
size_t HTTPSession::sendSettings() {
size_t size = codec_->generateSettings(writeBuf_);
scheduleWrite();
return size;
}
void HTTPSession::pauseIngress(HTTPTransaction* txn) noexcept {
VLOG(4) << *this << " pausing streamID=" << txn->getID() <<
", liveTransactions_ was " << liveTransactions_;
CHECK_GT(liveTransactions_, 0);
--liveTransactions_;
auto exTxns = txn->getExTransactions();
for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
auto exTxn = findTransaction(*it);
if (exTxn) {
exTxn->pauseIngress();
}
}
if (liveTransactions_ == 0) {
pauseReads();
}
}
void HTTPSession::resumeIngress(HTTPTransaction* txn) noexcept {
VLOG(4) << *this << " resuming streamID=" << txn->getID() <<
", liveTransactions_ was " << liveTransactions_;
++liveTransactions_;
auto exTxns = txn->getExTransactions();
for (auto it = exTxns.begin(); it != exTxns.end(); ++it) {
auto exTxn = findTransaction(*it);
if (exTxn) {
exTxn->resumeIngress();
}
}
if (liveTransactions_ == 1) {
resumeReads();
}
}
void
HTTPSession::transactionTimeout(HTTPTransaction* txn) noexcept {
// A transaction has timed out. If the transaction does not have
// a Handler yet, because we haven't yet received the full request
// headers, we give it a DirectResponseHandler that generates an
// error page.
VLOG(3) << "Transaction timeout for streamID=" << txn->getID();
if (!codec_->supportsParallelRequests()) {
// this error should only prevent us from reading/handling more errors
// on serial streams
ingressError_ = true;
}
if (!txn->getHandler() &&
txn->getEgressState() == HTTPTransactionEgressSM::State::Start) {
VLOG(4) << *this << " Timed out receiving headers";
if (infoCallback_) {
infoCallback_->onIngressError(*this, kErrorTimeout);
}
if (codec_->supportsParallelRequests()) {
// This can only happen with HTTP/2 where the HEADERS frame is incomplete
// and we time out waiting for the CONTINUATION. Abort the request.
//
// It would maybe be a little nicer to use the timeout handler for these
// also.
txn->sendAbort();
return;
}
VLOG(4) << *this << " creating direct error handler";
auto handler = getTransactionTimeoutHandler(txn);
txn->setHandler(handler);
}
// Tell the transaction about the timeout. The transaction will
// communicate the timeout to the handler, and the handler will
// decide how to proceed.
txn->onIngressTimeout();
}
void HTTPSession::sendHeaders(HTTPTransaction* txn,
const HTTPMessage& headers,
HTTPHeaderSize* size,
bool includeEOM) noexcept {
CHECK(started_);
unique_ptr<IOBuf> goawayBuf;
if (shouldShutdown()) {
// For HTTP/1.1, add Connection: close
// For SPDY, save the goaway for AFTER the request
auto writeBuf = writeBuf_.move();
drainImpl();
goawayBuf = writeBuf_.move();
writeBuf_.append(std::move(writeBuf));
}
if (isUpstream() || (txn->isPushed() && headers.isRequest())) {
// upstream picks priority
if (getHTTP2PrioritiesEnabled()) {
auto pri = getMessagePriority(&headers);
txn->onPriorityUpdate(pri);
}
}
const bool wasReusable = codec_->isReusable();
const uint64_t oldOffset = sessionByteOffset();
auto exAttributes = txn->getExAttributes();
auto assocStream = txn->getAssocTxnId();
if (exAttributes) {
codec_->generateExHeader(writeBuf_,
txn->getID(),
headers,
*exAttributes,
includeEOM,
size);
} else if (headers.isRequest() && assocStream) {
// Only PUSH_PROMISE (not push response) has an associated stream
codec_->generatePushPromise(writeBuf_,
txn->getID(),
headers,
*assocStream,
includeEOM,
size);
} else {
codec_->generateHeader(writeBuf_,
txn->getID(),
headers,
includeEOM,
size);
}
const uint64_t newOffset = sessionByteOffset();
// for push response count towards the MAX_CONCURRENT_STREAMS limit
if (isDownstream() && headers.isResponse() && txn->isPushed()) {
incrementOutgoingStreams();
}
// For all upstream headers, addFirstHeaderByteEvent should be added
// For all downstream, only response headers need addFirstHeaderByteEvent
bool shouldAddFirstHeaderByteEvent = isUpstream() ||
(isDownstream() && headers.isResponse());
if (shouldAddFirstHeaderByteEvent && newOffset > oldOffset &&
!txn->testAndSetFirstHeaderByteSent() && byteEventTracker_) {
byteEventTracker_->addFirstHeaderByteEvent(newOffset, txn);
}
if (size) {
VLOG(4) << *this << " sending headers, size=" << size->compressed
<< ", uncompressedSize=" << size->uncompressed;
}
if (goawayBuf) {
VLOG(4) << *this << " moved GOAWAY to end of writeBuf";
writeBuf_.append(std::move(goawayBuf));
}
if (includeEOM) {
commonEom(txn, 0, true);
}
scheduleWrite();
onHeadersSent(headers, wasReusable);
}
void
HTTPSession::commonEom(
HTTPTransaction* txn,
size_t encodedSize,
bool piggybacked) noexcept {
HTTPSessionBase::handleLastByteEvents(
byteEventTracker_.get(), txn, encodedSize, sessionByteOffset(),
piggybacked);
onEgressMessageFinished(txn);
}
size_t
HTTPSession::sendBody(HTTPTransaction* txn,
std::unique_ptr<folly::IOBuf> body,
bool includeEOM,
bool trackLastByteFlushed) noexcept {
uint64_t offset = sessionByteOffset();
size_t bodyLen = body ? body->computeChainDataLength(): 0;
size_t encodedSize = codec_->generateBody(writeBuf_,
txn->getID(),
std::move(body),
HTTPCodec::NoPadding,
includeEOM);
CHECK(inLoopCallback_);
pendingWriteSizeDelta_ -= bodyLen;
bodyBytesPerWriteBuf_ += bodyLen;
if (encodedSize > 0 && !txn->testAndSetFirstByteSent() && byteEventTracker_) {
byteEventTracker_->addFirstBodyByteEvent(offset, txn);
}
if (trackLastByteFlushed && encodedSize > 0 && byteEventTracker_) {
byteEventTracker_->addTrackedByteEvent(txn, offset + encodedSize);
}
if (includeEOM) {
VLOG(5) << *this << " sending EOM in body for streamID=" << txn->getID();
commonEom(txn, encodedSize, true);
}
return encodedSize;
}
size_t HTTPSession::sendChunkHeader(HTTPTransaction* txn,
size_t length) noexcept {
size_t encodedSize = codec_->generateChunkHeader(writeBuf_,
txn->getID(),
length);
scheduleWrite();
return encodedSize;
}
size_t HTTPSession::sendChunkTerminator(
HTTPTransaction* txn) noexcept {
size_t encodedSize = codec_->generateChunkTerminator(writeBuf_,
txn->getID());
scheduleWrite();
return encodedSize;
}
void
HTTPSession::onEgressMessageFinished(HTTPTransaction* txn, bool withRST) {
// If the semantics of the protocol don't permit more messages
// to be read or sent on this connection, close the socket in one or
// more directions.
CHECK(!transactions_.empty());
if (infoCallback_) {
infoCallback_->onRequestEnd(*this, txn->getMaxDeferredSize());
}
auto oldStreamCount = getPipelineStreamCount();
decrementTransactionCount(txn, false, true);
if (withRST || ((!codec_->isReusable() || readsShutdown()) &&
transactions_.size() == 1)) {
// We should shutdown reads if we are closing with RST or we aren't
// interested in any further messages (ie if we are a downstream session).
// Upgraded sessions have independent ingress and egress, and the reads
// need not be shutdown on egress finish.
if (withRST) {
// Let any queued writes complete, but send a RST when done.
VLOG(4) << *this << " resetting egress after this message";
resetAfterDrainingWrites_ = true;
setCloseReason(ConnectionCloseReason::TRANSACTION_ABORT);
shutdownTransport(true, true);
} else {
// the reason is already set (either not reusable or readshutdown).
// Defer normal shutdowns until the end of the loop. This
// handles an edge case with direct responses with Connection:
// close served before ingress EOM. The remainder of the ingress
// message may be in the parse loop, so give it a chance to
// finish out and avoid a kErrorEOF
// we can get here during shutdown, in that case do not schedule a
// shutdown callback again
if (!shutdownTransportCb_) {
// Just for safety, the following bumps the refcount on this session
// to keep it live until the loopCb runs
shutdownTransportCb_.reset(new ShutdownTransportCallback(this));
sock_->getEventBase()->runInLoop(shutdownTransportCb_.get(), true);
}
}
} else {
maybeResumePausedPipelinedTransaction(oldStreamCount,
txn->getSequenceNumber());
}
}
size_t HTTPSession::sendEOM(HTTPTransaction* txn,
const HTTPHeaders* trailers) noexcept {
VLOG(4) << *this << " sending EOM for streamID=" << txn->getID()
<< " trailers=" << (trailers ? "yes" : "no");
size_t encodedSize = 0;
if (trailers) {
encodedSize = codec_->generateTrailers(writeBuf_, txn->getID(), *trailers);
}
// Don't send EOM for HTTP2, when trailers sent.
// sendTrailers already flagged end of stream.
bool http2Trailers = trailers && isHTTP2CodecProtocol(codec_->getProtocol());
if (!http2Trailers) {
encodedSize += codec_->generateEOM(writeBuf_, txn->getID());
}
commonEom(txn, encodedSize, false);
return encodedSize;
}
size_t HTTPSession::sendAbort(HTTPTransaction* txn,
ErrorCode statusCode) noexcept {
// Ask the codec to generate an abort indicator for the transaction.
// Depending on the protocol, this may be a no-op.
// Schedule a network write to send out whatever egress we might
// have queued up.
VLOG(4) << *this << " sending abort for streamID=" << txn->getID();
// drain this transaction's writeBuf instead of flushing it
// then enqueue the abort directly into the Session buffer,
// hence with max priority.
size_t encodedSize = codec_->generateRstStream(writeBuf_,
txn->getID(),
statusCode);
if (!codec_->isReusable()) {
// HTTP 1x codec does not support per stream abort so this will
// render the codec not reusable
setCloseReason(ConnectionCloseReason::TRANSACTION_ABORT);
}
scheduleWrite();
// If the codec wasn't able to write a L7 message for the abort, then
// fall back to closing the transport with a TCP level RST
onEgressMessageFinished(txn, !encodedSize);
return encodedSize;
}
size_t HTTPSession::sendPriority(HTTPTransaction* txn,
const http2::PriorityUpdate& pri) noexcept {
return sendPriorityImpl(txn->getID(), pri);
}
void HTTPSession::setSecondAuthManager(
std::unique_ptr<SecondaryAuthManager> secondAuthManager) {
secondAuthManager_ = std::move(secondAuthManager);
}
SecondaryAuthManager* HTTPSession::getSecondAuthManager() const {
return secondAuthManager_.get();
}
/**
* Send a CERTIFICATE_REQUEST frame. If the underlying protocol doesn't
* support secondary authentication, this is a no-op and 0 is returned.
*/
size_t HTTPSession::sendCertificateRequest(
std::unique_ptr<folly::IOBuf> certificateRequestContext,
std::vector<fizz::Extension> extensions) {
// Check if both sending and receiving peer have advertised valid
// SETTINGS_HTTP_CERT_AUTH setting. Otherwise, the frames for secondary
// authentication should not be sent.
auto ingressSettings = codec_->getIngressSettings();
auto egressSettings = codec_->getEgressSettings();
if (ingressSettings && egressSettings) {
if (ingressSettings->getSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH, 0) ==
0 ||
egressSettings->getSetting(SettingsId::SETTINGS_HTTP_CERT_AUTH, 0) ==
0) {
VLOG(4) << "Secondary certificate authentication is not supported.";
return 0;
}
}
auto authRequest = secondAuthManager_->createAuthRequest(
std::move(certificateRequestContext), std::move(extensions));
auto encodedSize = codec_->generateCertificateRequest(
writeBuf_, authRequest.first, std::move(authRequest.second));
if (encodedSize > 0) {
scheduleWrite();
} else {
VLOG(4) << "Failed to generate CERTIFICATE_REQUEST frame.";
}
return encodedSize;
}
void HTTPSession::decrementTransactionCount(HTTPTransaction* txn,
bool ingressEOM,
bool egressEOM) {
if ((isUpstream() && !txn->isPushed()) ||
(isDownstream() && txn->isPushed())) {
if (ingressEOM && txn->testAndClearActive()) {
outgoingStreams_--;
}
} else {
if (egressEOM && txn->testAndClearActive()) {
incomingStreams_--;
}
}
}
// This is a kludgy function because it requires the caller to remember
// the old value of pipelineStreamCount from before it calls
// decrementTransactionCount. I'm trying to avoid yet more state in
// HTTPSession. If decrementTransactionCount actually closed a stream
// and there is still a pipelinable stream, then it was pipelining
bool
HTTPSession::maybeResumePausedPipelinedTransaction(
size_t oldStreamCount, uint32_t txnSeqn) {
if (!codec_->supportsParallelRequests() && !transactions_.empty() &&
getPipelineStreamCount() < oldStreamCount &&
getPipelineStreamCount() == 1) {
auto& nextTxn = transactions_.rbegin()->second;
DCHECK_EQ(nextTxn.getSequenceNumber(), txnSeqn + 1);
DCHECK(!nextTxn.isIngressComplete());
DCHECK(nextTxn.isIngressPaused());
VLOG(4) << "Resuming paused pipelined txn " << nextTxn;
nextTxn.resumeIngress();
return true;
}
return false;
}
void
HTTPSession::detach(HTTPTransaction* txn) noexcept {
DestructorGuard guard(this);
HTTPCodec::StreamID streamID = txn->getID();
auto txnSeqn = txn->getSequenceNumber();
auto it = transactions_.find(txn->getID());
DCHECK(it != transactions_.end());
if (txn->isIngressPaused()) {
// Someone detached a transaction that was paused. Make the resumeIngress
// call to keep liveTransactions_ in order
VLOG(4) << *this << " detached paused transaction=" << streamID;
resumeIngress(txn);
}
VLOG(4) << *this << " removing streamID=" << streamID <<
", liveTransactions was " << liveTransactions_;
CHECK_GT(liveTransactions_, 0);
liveTransactions_--;
if (txn->isPushed()) {
auto assocTxn = findTransaction(*txn->getAssocTxnId());
if (assocTxn) {
assocTxn->removePushedTransaction(streamID);
}
}
if (txn->getControlStream()) {
auto controlTxn = findTransaction(*txn->getControlStream());
if (controlTxn) {
controlTxn->removeExTransaction(streamID);
}
}
auto oldStreamCount = getPipelineStreamCount();
decrementTransactionCount(txn, true, true);
transactions_.erase(it);
if (transactions_.empty()) {
HTTPSessionBase::setLatestActive();
if (infoCallback_) {
infoCallback_->onDeactivateConnection(*this);
}
if (getConnectionManager()) {
getConnectionManager()->onDeactivated(*this);
}
} else {
if (infoCallback_) {
infoCallback_->onTransactionDetached(*this);
}
}
if (!readsShutdown()) {
if (maybeResumePausedPipelinedTransaction(oldStreamCount, txnSeqn)) {
return;
} else {
// this will resume reads if they were paused (eg: 0 HTTP transactions)
resumeReads();
}
}
if (liveTransactions_ == 0 && transactions_.empty() && !isScheduled()) {
resetTimeout();
}
// It's possible that this is the last transaction in the session,
// so check whether the conditions for shutdown are satisfied.
if (transactions_.empty()) {
if (shouldShutdown()) {
writesDraining_ = true;
}
// Handle the case where we are draining writes but all remaining
// transactions terminated with no egress.
if (writesDraining_ && !writesShutdown() && !hasMoreWrites()) {
shutdownTransport(false, true);
return;
}
}
checkForShutdown();
}
size_t
HTTPSession::sendWindowUpdate(HTTPTransaction* txn,
uint32_t bytes) noexcept {
size_t sent = codec_->generateWindowUpdate(writeBuf_, txn->getID(), bytes);
if (sent) {
scheduleWrite();
}
return sent;
}
void
HTTPSession::notifyIngressBodyProcessed(uint32_t bytes) noexcept {
if (HTTPSessionBase::notifyBodyProcessed(bytes)) {
resumeReads();
}
if (connFlowControl_ &&
connFlowControl_->ingressBytesProcessed(writeBuf_, bytes)) {
scheduleWrite();
}
}
void
HTTPSession::notifyEgressBodyBuffered(int64_t bytes) noexcept {
pendingWriteSizeDelta_ += bytes;
// any net change requires us to update pause/resume state in the
// loop callback
if (pendingWriteSizeDelta_ > 0) {
// pause inline, resume in loop
updateWriteBufSize(0);
} else if (!isLoopCallbackScheduled()) {
sock_->getEventBase()->runInLoop(this);
}
}
bool HTTPSession::getCurrentTransportInfoWithoutUpdate(
TransportInfo* tinfo) const {
auto sock = sock_->getUnderlyingTransport<AsyncSocket>();
if (sock) {
tinfo->initWithSocket(sock);
return true;
}
return false;
}
bool HTTPSession::getCurrentTransportInfo(TransportInfo* tinfo) {
if (getCurrentTransportInfoWithoutUpdate(tinfo)) {
// some fields are the same with the setup transport info
tinfo->setupTime = transportInfo_.setupTime;
tinfo->secure = transportInfo_.secure;
tinfo->sslSetupTime = transportInfo_.sslSetupTime;
tinfo->sslVersion = transportInfo_.sslVersion;
tinfo->sslCipher = transportInfo_.sslCipher;
tinfo->sslResume = transportInfo_.sslResume;
tinfo->appProtocol = transportInfo_.appProtocol;
tinfo->sslError = transportInfo_.sslError;
#if defined(__linux__) || defined(__FreeBSD__)
// update connection transport info with the latest RTT
if (tinfo->tcpinfo.tcpi_rtt > 0) {
transportInfo_.tcpinfo.tcpi_rtt = tinfo->tcpinfo.tcpi_rtt;
transportInfo_.rtt = std::chrono::microseconds(tinfo->tcpinfo.tcpi_rtt);
}
transportInfo_.rtx = tinfo->rtx;
#endif
return true;
}
return false;
}
unique_ptr<IOBuf> HTTPSession::getNextToSend(bool* cork, bool* eom) {
// limit ourselves to one outstanding write at a time (onWriteSuccess calls
// scheduleWrite)
if (numActiveWrites_ > 0 || writesShutdown()) {
VLOG(4) << "skipping write during this loop, numActiveWrites_=" <<
numActiveWrites_ << " writesShutdown()=" << writesShutdown();
return nullptr;
}
// We always tack on at least one body packet to the current write buf
// This ensures that a short HTTPS response will go out in a single SSL record
while (!txnEgressQueue_.empty()) {
uint32_t toSend = kWriteReadyMax;
if (connFlowControl_) {
if (connFlowControl_->getAvailableSend() == 0) {
VLOG(4) << "Session-level send window is full, skipping remaining "
<< "body writes this loop";
break;
}
toSend = std::min(toSend, connFlowControl_->getAvailableSend());
}
txnEgressQueue_.nextEgress(nextEgressResults_,
isSpdyCodecProtocol(codec_->getProtocol()));
CHECK(!nextEgressResults_.empty()); // Queue was non empty, so this must be
// The maximum we will send for any transaction in this loop
uint32_t txnMaxToSend = toSend * nextEgressResults_.front().second;
if (txnMaxToSend == 0) {
// toSend is smaller than the number of transactions. Give all egress
// to the first transaction
nextEgressResults_.erase(++nextEgressResults_.begin(),
nextEgressResults_.end());
txnMaxToSend = std::min(toSend, egressBodySizeLimit_);
nextEgressResults_.front().second = 1;
}
if (nextEgressResults_.size() > 1 && txnMaxToSend > egressBodySizeLimit_) {
// Cap the max to egressBodySizeLimit_, and recompute toSend accordingly
txnMaxToSend = egressBodySizeLimit_;
toSend = txnMaxToSend / nextEgressResults_.front().second;
}
// split allowed by relative weight, with some minimum
for (auto txnPair: nextEgressResults_) {
uint32_t txnAllowed = txnPair.second * toSend;
if (nextEgressResults_.size() > 1) {
CHECK_LE(txnAllowed, egressBodySizeLimit_);
}
if (connFlowControl_) {
CHECK_LE(txnAllowed, connFlowControl_->getAvailableSend());
}
if (txnAllowed == 0) {
// The ratio * toSend was so small this txn gets nothing.
VLOG(4) << *this << " breaking egress loop on 0 txnAllowed";
break;
}
VLOG(4) << *this << " egressing txnID=" << txnPair.first->getID() <<
" allowed=" << txnAllowed;
txnPair.first->onWriteReady(txnAllowed, txnPair.second);
}
nextEgressResults_.clear();
// it can be empty because of HTTPTransaction rate limiting. We should
// change rate limiting to clearPendingEgress while waiting.
if (!writeBuf_.empty()) {
break;
}
}
*eom = false;
if (byteEventTracker_) {
uint64_t needed = byteEventTracker_->preSend(cork, eom, bytesWritten_);
if (needed > 0) {
VLOG(5) << *this << " writeBuf_.chainLength(): "
<< writeBuf_.chainLength() << " txnEgressQueue_.empty(): "
<< txnEgressQueue_.empty();
if (needed < writeBuf_.chainLength()) {
// split the next EOM chunk
VLOG(5) << *this << " splitting " << needed << " bytes out of a "
<< writeBuf_.chainLength() << " bytes IOBuf";
*cork = true;
if (sessionStats_) {
sessionStats_->recordTTLBAIOBSplitByEom();
}
return writeBuf_.split(needed);
} else {
CHECK_EQ(needed, writeBuf_.chainLength());
}
}
}
// cork if there are txns with pending egress and room to send them
*cork = !txnEgressQueue_.empty() && !isConnWindowFull();
return writeBuf_.move();
}
void
HTTPSession::runLoopCallback() noexcept {
// We schedule this callback to run at the end of an event
// loop iteration if either of two conditions has happened:
// * The session has generated some egress data (see scheduleWrite())
// * Reads have become unpaused (see resumeReads())
DestructorGuard dg(this);
inLoopCallback_ = true;
auto scopeg = folly::makeGuard([this] {
inLoopCallback_ = false;
// This ScopeGuard needs to be under the above DestructorGuard
if (pendingWriteSizeDelta_) {
updateWriteBufSize(0);
}
checkForShutdown();
});
VLOG(5) << *this << " in loop callback";
for (uint32_t i = 0; i < kMaxWritesPerLoop; ++i) {
bodyBytesPerWriteBuf_ = 0;
if (isPrioritySampled()) {
invokeOnAllTransactions(
&HTTPTransaction::updateContentionsCount,
txnEgressQueue_.numPendingEgress());
}
bool cork = true;
bool eom = false;
unique_ptr<IOBuf> writeBuf = getNextToSend(&cork, &eom);
if (!writeBuf) {
break;
}
uint64_t len = writeBuf->computeChainDataLength();
VLOG(11) << *this
<< " bytes of egress to be written: " << len
<< " cork:" << cork << " eom:" << eom;
if (len == 0) {
checkForShutdown();
return;
}
if (isPrioritySampled()) {
invokeOnAllTransactions(
&HTTPTransaction::updateSessionBytesSheduled,
bodyBytesPerWriteBuf_);
}
WriteSegment* segment = new WriteSegment(this, len);
segment->setCork(cork);
segment->setEOR(eom);
pendingWrites_.push_back(*segment);
if (!writeTimeout_.isScheduled()) {
// Any performance concern here?
timeout_.scheduleTimeout(&writeTimeout_);
}
numActiveWrites_++;
VLOG(4) << *this << " writing " << len << ", activeWrites="
<< numActiveWrites_ << " cork=" << cork << " eom=" << eom;
bytesScheduled_ += len;
sock_->writeChain(segment, std::move(writeBuf), segment->getFlags());
if (numActiveWrites_ > 0) {
updateWriteCount();
pendingWriteSizeDelta_ += len;
// updateWriteBufSize called in scope guard
break;
}
// writeChain can result in a writeError and trigger the shutdown code path
}
if (numActiveWrites_ == 0 && !writesShutdown() && hasMoreWrites() &&
(!connFlowControl_ || connFlowControl_->getAvailableSend())) {
scheduleWrite();
}
if (readsUnpaused()) {
processReadData();
// Install the read callback if necessary
if (readsUnpaused() && !sock_->getReadCallback()) {
sock_->setReadCB(this);
}
}
// checkForShutdown is now in ScopeGuard
}
void
HTTPSession::scheduleWrite() {
// Do all the network writes for this connection in one batch at
// the end of the current event loop iteration. Writing in a
// batch helps us packetize the network traffic more efficiently,
// as well as saving a few system calls.
if (!isLoopCallbackScheduled() &&
(writeBuf_.front() || !txnEgressQueue_.empty())) {
VLOG(5) << *this << " scheduling write callback";
sock_->getEventBase()->runInLoop(this);
}
}
void
HTTPSession::updateWriteCount() {
if (numActiveWrites_ > 0 && writesUnpaused()) {
// Exceeded limit. Pause reading on the incoming stream.
VLOG(3) << "Pausing egress for " << *this;
writes_ = SocketState::PAUSED;
} else if (numActiveWrites_ == 0 && writesPaused()) {
// Dropped below limit. Resume reading on the incoming stream if needed.
VLOG(3) << "Resuming egress for " << *this;
writes_ = SocketState::UNPAUSED;
}
}
void
HTTPSession::updateWriteBufSize(int64_t delta) {
// This is the sum of body bytes buffered within transactions_ and in
// the sock_'s write buffer.
delta += pendingWriteSizeDelta_;
pendingWriteSizeDelta_ = 0;
bool wasExceeded = egressLimitExceeded();
updatePendingWriteSize(delta);
if (egressLimitExceeded() && !wasExceeded) {
// Exceeded limit. Pause reading on the incoming stream.
if (inResume_) {
VLOG(3) << "Pausing txn egress for " << *this << " deferred";
pendingPause_ = true;
} else {
VLOG(3) << "Pausing txn egress for " << *this;
invokeOnAllTransactions(&HTTPTransaction::pauseEgress);
}
} else if (!egressLimitExceeded() && wasExceeded) {
// Dropped below limit. Resume reading on the incoming stream if needed.
if (inResume_) {
if (pendingPause_) {
VLOG(3) << "Cancel deferred txn egress pause for " << *this;
pendingPause_ = false;
} else {
VLOG(3) << "Ignoring redundant resume for " << *this;
}
} else {
VLOG(3) << "Resuming txn egress for " << *this;
resumeTransactions();
}
}
}
void
HTTPSession::shutdownTransport(bool shutdownReads,
bool shutdownWrites,
const std::string& errorMsg) {
DestructorGuard guard(this);
// shutdowns not accounted for, shouldn't see any
setCloseReason(ConnectionCloseReason::UNKNOWN);
VLOG(4) << "shutdown request for " << *this << ": reads="
<< shutdownReads << " (currently " << readsShutdown()
<< "), writes=" << shutdownWrites << " (currently "
<< writesShutdown() << ")";
bool notifyEgressShutdown = false;
bool notifyIngressShutdown = false;
ProxygenError error;
if (!transportInfo_.sslError.empty()) {
error = kErrorSSL;
} else if (sock_->error()) {
VLOG(3) << "shutdown request for " << *this
<< " on bad socket. Shutting down writes too.";
if (getConnectionCloseReason() == ConnectionCloseReason::IO_WRITE_ERROR) {
error = kErrorWrite;
} else {
error = kErrorConnectionReset;
}
shutdownWrites = true;
} else if (getConnectionCloseReason() == ConnectionCloseReason::TIMEOUT) {
error = kErrorTimeout;
} else {
error = kErrorEOF;
}
if (shutdownReads && !shutdownWrites && flowControlTimeout_.isScheduled()) {
// reads are dead and writes are blocked on a window update that will never
// come. shutdown writes too.
VLOG(4) << *this << " Converting read shutdown to read/write due to"
" flow control";
shutdownWrites = true;
}
if (shutdownWrites && !writesShutdown()) {
if (codec_->generateGoaway(writeBuf_,
codec_->getLastIncomingStreamID(),
ErrorCode::NO_ERROR)) {
scheduleWrite();
}
if (!hasMoreWrites() &&
(transactions_.empty() || codec_->closeOnEgressComplete())) {
writes_ = SocketState::SHUTDOWN;
if (byteEventTracker_) {
byteEventTracker_->drainByteEvents();
}
if (resetAfterDrainingWrites_) {
VLOG(4) << *this << " writes drained, sending RST";
resetSocketOnShutdown_ = true;
shutdownReads = true;
} else {
VLOG(4) << *this << " writes drained, closing";
sock_->shutdownWriteNow();
}
notifyEgressShutdown = true;
} else if (!writesDraining_) {
writesDraining_ = true;
notifyEgressShutdown = true;
} // else writes are already draining; don't double notify
}
if (shutdownReads && !readsShutdown()) {
notifyIngressShutdown = true;
// TODO: send an RST if readBuf_ is non empty?
sock_->setReadCB(nullptr);
reads_ = SocketState::SHUTDOWN;
if (!transactions_.empty() && error == kErrorConnectionReset) {
if (infoCallback_ != nullptr) {
infoCallback_->onIngressError(*this, error);
}
} else if (error == kErrorEOF) {
// Report to the codec that the ingress stream has ended
codec_->onIngressEOF();
if (infoCallback_) {
infoCallback_->onIngressEOF();
}
}
// Once reads are shutdown the parser should stop processing
codec_->setParserPaused(true);
}
if (notifyIngressShutdown || notifyEgressShutdown) {
auto dir = (notifyIngressShutdown && notifyEgressShutdown)
? HTTPException::Direction::INGRESS_AND_EGRESS
: (notifyIngressShutdown ? HTTPException::Direction::INGRESS
: HTTPException::Direction::EGRESS);
HTTPException ex(
dir,
folly::to<std::string>("Shutdown transport: ", getErrorString(error),
errorMsg.empty() ? "" : " ", errorMsg, ", ",
getPeerAddress().describe()));
ex.setProxygenError(error);
invokeOnAllTransactions(&HTTPTransaction::onError, ex);
}
// Close the socket only after the onError() callback on the txns
// and handler has been detached.
checkForShutdown();
}
void HTTPSession::shutdownTransportWithReset(
ProxygenError errorCode,
const std::string& errorMsg) {
DestructorGuard guard(this);
VLOG(4) << "shutdownTransportWithReset";
if (!readsShutdown()) {
sock_->setReadCB(nullptr);
reads_ = SocketState::SHUTDOWN;
}
if (!writesShutdown()) {
writes_ = SocketState::SHUTDOWN;
IOBuf::destroy(writeBuf_.move());
while (!pendingWrites_.empty()) {
pendingWrites_.front().detach();
numActiveWrites_--;
}
VLOG(4) << *this << " cancel write timer";
writeTimeout_.cancelTimeout();
resetSocketOnShutdown_ = true;
}
errorOnAllTransactions(errorCode, errorMsg);
// drainByteEvents() can call detach(txn), which can in turn call
// shutdownTransport if we were already draining. To prevent double
// calling onError() to the transactions, we call drainByteEvents()
// after we've given the explicit error.
if (byteEventTracker_) {
byteEventTracker_->drainByteEvents();
}
// HTTPTransaction::onError could theoretically schedule more callbacks,
// so do this last.
if (isLoopCallbackScheduled()) {
cancelLoopCallback();
}
// onError() callbacks or drainByteEvents() could result in txns detaching
// due to CallbackGuards going out of scope. Close the socket only after
// the txns are detached.
checkForShutdown();
}
void
HTTPSession::checkForShutdown() {
VLOG(10) << *this << " checking for shutdown, readShutdown="
<< readsShutdown() << ", writesShutdown=" << writesShutdown()
<< ", transaction set empty=" << transactions_.empty();
// Two conditions are required to destroy the HTTPSession:
// * All writes have been finished.
// * There are no transactions remaining on the session.
if (writesShutdown() && transactions_.empty() &&
!isLoopCallbackScheduled()) {
VLOG(4) << "destroying " << *this;
sock_->setReadCB(nullptr);
auto asyncSocket = sock_->getUnderlyingTransport<folly::AsyncSocket>();
if (asyncSocket) {
asyncSocket->setBufferCallback(nullptr);
}
reads_ = SocketState::SHUTDOWN;
if (resetSocketOnShutdown_) {
sock_->closeWithReset();
} else {
sock_->closeNow();
}
destroy();
}
}
void
HTTPSession::drain() {
if (!draining_) {
VLOG(4) << *this << " draining";
draining_ = true;
setCloseReason(ConnectionCloseReason::SHUTDOWN);
if (allTransactionsStarted()) {
drainImpl();
}
if (transactions_.empty() && isUpstream()) {
// We don't do this for downstream since we need to wait for
// inflight requests to arrive
VLOG(4) << *this << " shutdown from drain";
shutdownTransport(true, true);
}
} else {
VLOG(4) << *this << " already draining";
}
}
void HTTPSession::drainImpl() {
if (codec_->isReusable() || codec_->isWaitingToDrain()) {
setCloseReason(ConnectionCloseReason::SHUTDOWN);
// For HTTP/2, if we haven't started yet then we cannot send a GOAWAY frame
// since we haven't sent the initial SETTINGS frame. Defer sending that
// GOAWAY until the initial SETTINGS is sent.
if (started_) {
codec_->generateGoaway(writeBuf_,
getGracefulGoawayAck(),
ErrorCode::NO_ERROR);
scheduleWrite();
}
}
}
bool HTTPSession::shouldShutdown() const {
return draining_ &&
allTransactionsStarted() &&
(!codec_->supportsParallelRequests() ||
isUpstream() ||
!codec_->isReusable());
}
size_t HTTPSession::sendPing() {
const size_t bytes = codec_->generatePingRequest(writeBuf_);
if (bytes) {
scheduleWrite();
}
return bytes;
}
HTTPCodec::StreamID HTTPSession::sendPriority(http2::PriorityUpdate pri) {
if (!codec_->supportsParallelRequests()) {
// For HTTP/1.1, don't call createStream()
return 0;
}
auto id = codec_->createStream();
sendPriority(id, pri);
return id;
}
size_t HTTPSession::sendPriority(HTTPCodec::StreamID id,
http2::PriorityUpdate pri) {
auto res = sendPriorityImpl(id, pri);
txnEgressQueue_.addOrUpdatePriorityNode(id, pri);
return res;
}
size_t HTTPSession::sendPriorityImpl(HTTPCodec::StreamID id,
http2::PriorityUpdate pri) {
CHECK_NE(id, 0);
const size_t bytes = codec_->generatePriority(
writeBuf_, id, std::make_tuple(pri.streamDependency,
pri.exclusive,
pri.weight));
if (bytes) {
scheduleWrite();
}
return bytes;
}
HTTPTransaction*
HTTPSession::findTransaction(HTTPCodec::StreamID streamID) {
auto it = transactions_.find(streamID);
if (it == transactions_.end()) {
return nullptr;
} else {
return &it->second;
}
}
HTTPTransaction*
HTTPSession::createTransaction(
HTTPCodec::StreamID streamID,
const folly::Optional<HTTPCodec::StreamID>& assocStreamID,
const folly::Optional<HTTPCodec::ExAttributes>& exAttributes,
const http2::PriorityUpdate& priority) {
if (!sock_->good() || transactions_.count(streamID)) {
// Refuse to add a transaction on a closing session or if a
// transaction of that ID already exists.
return nullptr;
}
if (transactions_.empty()) {
if (infoCallback_) {
infoCallback_->onActivateConnection(*this);
}
if (getConnectionManager()) {
getConnectionManager()->onActivated(*this);
}
HTTPSessionBase::onCreateTransaction();
}
auto matchPair = transactions_.emplace(
std::piecewise_construct,
std::forward_as_tuple(streamID),
std::forward_as_tuple(
codec_->getTransportDirection(), streamID, getNumTxnServed(), *this,
txnEgressQueue_, timeout_.getWheelTimer(), timeout_.getDefaultTimeout(),
sessionStats_,
codec_->supportsStreamFlowControl(),
initialReceiveWindow_,
getCodecSendWindowSize(),
priority,
assocStreamID,
exAttributes
));
CHECK(matchPair.second) << "Emplacement failed, despite earlier "
"existence check.";
HTTPTransaction* txn = &matchPair.first->second;
if (isPrioritySampled()) {
txn->setPrioritySampled(true /* sampled */);
}
if (getNumTxnServed() > 0) {
auto stats = txn->getSessionStats();
if (stats != nullptr) {
stats->recordSessionReused();
}
}
VLOG(5) << *this << " adding streamID=" << txn->getID()
<< ", liveTransactions_ was " << liveTransactions_;
++liveTransactions_;
incrementSeqNo();
txn->setReceiveWindow(receiveStreamWindowSize_);
if (isUpstream() && !txn->isPushed()) {
incrementOutgoingStreams();
// do not count towards MAX_CONCURRENT_STREAMS for PUSH_PROMISE
} else if (!(isDownstream() && txn->isPushed())) {
incomingStreams_++;
}
return txn;
}
void
HTTPSession::incrementOutgoingStreams() {
outgoingStreams_++;
HTTPSessionBase::onNewOutgoingStream(outgoingStreams_);
}
void
HTTPSession::onWriteSuccess(uint64_t bytesWritten) {
DestructorGuard dg(this);
bytesWritten_ += bytesWritten;
transportInfo_.totalBytes += bytesWritten;
CHECK(writeTimeout_.isScheduled());
if (pendingWrites_.empty()) {
VLOG(10) << "Cancel write timer on last successful write";
writeTimeout_.cancelTimeout();
} else {
VLOG(10) << "Refresh write timer on writeSuccess";
timeout_.scheduleTimeout(&writeTimeout_);
}
if (infoCallback_) {
infoCallback_->onWrite(*this, bytesWritten);
}
VLOG(5) << "total bytesWritten_: " << bytesWritten_;
// processByteEvents will return true if it has been replaced with another
// tracker in the middle and needs to be re-run. Should happen at most
// once. while with no body is intentional
while (byteEventTracker_ &&
byteEventTracker_->processByteEvents(
byteEventTracker_, bytesWritten_)) {} // pass
if ((!codec_->isReusable() || readsShutdown()) && (transactions_.empty())) {
if (!codec_->isReusable()) {
// Shouldn't happen unless there is a bug. This can only happen when
// someone calls shutdownTransport, but did not specify a reason before.
setCloseReason(ConnectionCloseReason::UNKNOWN);
}
VLOG(4) << *this << " shutdown from onWriteSuccess";
shutdownTransport(true, true);
}
numActiveWrites_--;
if (!inLoopCallback_) {
updateWriteCount();
// safe to resume here:
updateWriteBufSize(-folly::to<int64_t>(bytesWritten));
// PRIO_FIXME: this is done because of the corking business...
// in the future we may want to have a pull model
// whereby the socket asks us for a given amount of
// data to send...
if (numActiveWrites_ == 0 && hasMoreWrites()) {
runLoopCallback();
}
}
onWriteCompleted();
if (egressBytesLimit_ > 0 && bytesWritten_ >= egressBytesLimit_) {
VLOG(4) << "Egress limit reached, shutting down "
"session (egressed " << bytesWritten_ << ", limit set to "
<< egressBytesLimit_ << ")";
shutdownTransport(true, true);
}
}
void
HTTPSession::onWriteError(size_t bytesWritten,
const AsyncSocketException& ex) {
VLOG(4) << *this << " write error: " << ex.what();
if (infoCallback_) {
infoCallback_->onWrite(*this, bytesWritten);
}
auto sslEx = dynamic_cast<const folly::SSLException*>(&ex);
// Save the SSL error, if there was one. It will be recorded later
if (sslEx && sslEx->getSSLError() == folly::SSLError::SSL_ERROR) {
transportInfo_.sslError = ex.what();
}
setCloseReason(ConnectionCloseReason::IO_WRITE_ERROR);
shutdownTransportWithReset(kErrorWrite, ex.what());
}
void
HTTPSession::onWriteCompleted() {
if (!writesDraining_) {
return;
}
if (numActiveWrites_) {
return;
}
// Don't shutdown if there might be more writes
if (!pendingWrites_.empty()) {
return;
}
// All finished draining writes, so shut down the egress
shutdownTransport(false, true);
}
void HTTPSession::onSessionParseError(const HTTPException& error) {
VLOG(4) << *this << " session layer parse error. Terminate the session.";
if (error.hasCodecStatusCode()) {
std::unique_ptr<folly::IOBuf> errorMsg =
folly::IOBuf::copyBuffer(error.what());
codec_->generateGoaway(writeBuf_,
codec_->getLastIncomingStreamID(),
error.getCodecStatusCode(),
isHTTP2CodecProtocol(codec_->getProtocol()) ?
std::move(errorMsg) : nullptr);
scheduleWrite();
}
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
shutdownTransport(true, true);
}
void HTTPSession::onNewTransactionParseError(HTTPCodec::StreamID streamID,
const HTTPException& error) {
VLOG(4) << *this << " parse error with new transaction";
if (error.hasCodecStatusCode()) {
codec_->generateRstStream(writeBuf_, streamID, error.getCodecStatusCode());
scheduleWrite();
}
if (!codec_->isReusable()) {
// HTTP 1x codec does not support per stream abort so this will
// render the codec not reusable
setCloseReason(ConnectionCloseReason::SESSION_PARSE_ERROR);
}
}
void
HTTPSession::pauseReads() {
// Make sure the parser is paused. Note that if reads are shutdown
// before they are paused, we never make it past the if.
codec_->setParserPaused(true);
if (!readsUnpaused() ||
(codec_->supportsParallelRequests() &&
!ingressLimitExceeded())) {
return;
}
pauseReadsImpl();
}
void HTTPSession::pauseReadsImpl() {
VLOG(4) << *this << ": pausing reads";
if (infoCallback_) {
infoCallback_->onIngressPaused(*this);
}
cancelTimeout();
sock_->setReadCB(nullptr);
reads_ = SocketState::PAUSED;
}
void
HTTPSession::resumeReads() {
if (!readsPaused() ||
(codec_->supportsParallelRequests() &&
ingressLimitExceeded())) {
return;
}
resumeReadsImpl();
}
void HTTPSession::resumeReadsImpl() {
VLOG(4) << *this << ": resuming reads";
resetTimeout();
reads_ = SocketState::UNPAUSED;
codec_->setParserPaused(false);
if (!isLoopCallbackScheduled()) {
sock_->getEventBase()->runInLoop(this);
}
}
bool
HTTPSession::hasMoreWrites() const {
VLOG(10) << __PRETTY_FUNCTION__
<< " numActiveWrites_: " << numActiveWrites_
<< " pendingWrites_.empty(): " << pendingWrites_.empty()
<< " pendingWrites_.size(): " << pendingWrites_.size()
<< " txnEgressQueue_.empty(): " << txnEgressQueue_.empty();
return (numActiveWrites_ != 0) ||
!pendingWrites_.empty() || writeBuf_.front() ||
!txnEgressQueue_.empty();
}
void HTTPSession::errorOnAllTransactions(
ProxygenError err,
const std::string& errorMsg) {
std::vector<HTTPCodec::StreamID> ids;
for (const auto& txn: transactions_) {
ids.push_back(txn.first);
}
errorOnTransactionIds(ids, err, errorMsg);
}
void HTTPSession::errorOnTransactionIds(
const std::vector<HTTPCodec::StreamID>& ids,
ProxygenError err,
const std::string& errorMsg) {
std::string extraErrorMsg;
if (!errorMsg.empty()) {
extraErrorMsg = folly::to<std::string>(". ", errorMsg);
}
for (auto id: ids) {
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>(getErrorString(err),
" on transaction id: ", id,
extraErrorMsg));
ex.setProxygenError(err);
errorOnTransactionId(id, std::move(ex));
}
}
void HTTPSession::errorOnTransactionId(
HTTPCodec::StreamID id,
HTTPException ex) {
auto txn = findTransaction(id);
if (txn != nullptr) {
txn->onError(std::move(ex));
}
}
void HTTPSession::resumeTransactions() {
CHECK(!inResume_);
inResume_ = true;
DestructorGuard g(this);
auto resumeFn = [] (HTTP2PriorityQueue&, HTTPCodec::StreamID,
HTTPTransaction *txn, double) {
if (txn) {
txn->resumeEgress();
}
return false;
};
auto stopFn = [this] {
return (transactions_.empty() || egressLimitExceeded());
};
txnEgressQueue_.iterateBFS(resumeFn, stopFn, true /* all */);
inResume_ = false;
if (pendingPause_) {
VLOG(3) << "Pausing txn egress for " << *this;
pendingPause_ = false;
invokeOnAllTransactions(&HTTPTransaction::pauseEgress);
}
}
void HTTPSession::onConnectionSendWindowOpen() {
flowControlTimeout_.cancelTimeout();
// We can write more now. Schedule a write.
scheduleWrite();
}
void HTTPSession::onConnectionSendWindowClosed() {
if(!txnEgressQueue_.empty()) {
VLOG(4) << *this << " session stalled by flow control";
if (sessionStats_) {
sessionStats_->recordSessionStalled();
}
}
DCHECK(!flowControlTimeout_.isScheduled());
if (infoCallback_) {
infoCallback_->onFlowControlWindowClosed(*this);
}
auto timeout = flowControlTimeout_.getTimeoutDuration();
if (timeout != std::chrono::milliseconds(0)) {
timeout_.scheduleTimeout(&flowControlTimeout_, timeout);
} else {
timeout_.scheduleTimeout(&flowControlTimeout_);
}
}
HTTPCodec::StreamID HTTPSession::getGracefulGoawayAck() const {
if (!codec_->isReusable() || codec_->isWaitingToDrain()) {
// TODO: just track last stream ID inside HTTPSession since this logic
// is shared between HTTP/2 and SPDY
return codec_->getLastIncomingStreamID();
}
VLOG(4) << *this << " getGracefulGoawayAck is reusable and not draining";
// return the maximum possible stream id
return std::numeric_limits<int32_t>::max();
}
void HTTPSession::invalidStream(HTTPCodec::StreamID stream, ErrorCode code) {
if (!codec_->supportsParallelRequests()) {
LOG(ERROR) << "Invalid stream on non-parallel codec.";
return;
}
HTTPException err(HTTPException::Direction::INGRESS_AND_EGRESS,
folly::to<std::string>("invalid stream=", stream));
// TODO: Below line will change for HTTP/2 -- just call a const getter
// function for the status code.
err.setCodecStatusCode(code);
onError(stream, err, true);
}
void HTTPSession::onPingReplyLatency(int64_t latency) noexcept {
if (infoCallback_ && latency >= 0) {
infoCallback_->onPingReplySent(latency);
}
}
void HTTPSession::onDeleteAckEvent() noexcept {
if (readsShutdown()) {
shutdownTransport(true, transactions_.empty());
}
}
void HTTPSession::onEgressBuffered() {
if (infoCallback_) {
infoCallback_->onEgressBuffered(*this);
}
}
void HTTPSession::onEgressBufferCleared() {
if (infoCallback_) {
infoCallback_->onEgressBufferCleared(*this);
}
}
void HTTPSession::onReplaySafe() noexcept {
CHECK(sock_);
sock_->setReplaySafetyCallback(nullptr);
if (infoCallback_) {
infoCallback_->onFullHandshakeCompletion(*this);
}
for (auto callback : waitingForReplaySafety_) {
callback->onReplaySafe();
}
waitingForReplaySafety_.clear();
}
void HTTPSession::onLastByteEvent(
HTTPTransaction* txn, uint64_t eomOffset, bool eomTracked) noexcept {
if (!sock_->isEorTrackingEnabled() || !eomTracked) {
return;
}
if (eomOffset != sock_->getAppBytesWritten()) {
VLOG(2) << "tracking ack to last app byte " << eomOffset
<< " while " << sock_->getAppBytesWritten()
<< " app bytes have already been written";
return;
}
VLOG(5) << "tracking raw last byte " << sock_->getRawBytesWritten()
<< " while the app last byte is " << eomOffset;
byteEventTracker_->addAckByteEvent(sock_->getRawBytesWritten(), txn);
}
} // proxygen
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_597_0 |
crossvul-cpp_data_good_1580_1 | #include "ndis56common.h"
CNBL::CNBL(PNET_BUFFER_LIST NBL, PPARANDIS_ADAPTER Context, CParaNdisTX &ParentTXPath)
: m_NBL(NBL)
, m_Context(Context)
, m_ParentTXPath(&ParentTXPath)
{
m_NBL->Scratch = this;
m_LsoInfo.Value = NET_BUFFER_LIST_INFO(m_NBL, TcpLargeSendNetBufferListInfo);
m_CsoInfo.Value = NET_BUFFER_LIST_INFO(m_NBL, TcpIpChecksumNetBufferListInfo);
}
CNBL::~CNBL()
{
CDpcIrqlRaiser OnDpc;
m_MappedBuffers.ForEachDetached([this](CNB *NB)
{ CNB::Destroy(NB, m_Context->MiniportHandle); });
m_Buffers.ForEachDetached([this](CNB *NB)
{ CNB::Destroy(NB, m_Context->MiniportHandle); });
if(m_NBL)
{
auto NBL = DetachInternalObject();
NET_BUFFER_LIST_NEXT_NBL(NBL) = nullptr;
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, NBL, 0);
}
}
bool CNBL::ParsePriority()
{
NDIS_NET_BUFFER_LIST_8021Q_INFO priorityInfo;
priorityInfo.Value = m_Context->ulPriorityVlanSetting ?
NET_BUFFER_LIST_INFO(m_NBL, Ieee8021QNetBufferListInfo) : nullptr;
if (!priorityInfo.TagHeader.VlanId)
{
priorityInfo.TagHeader.VlanId = m_Context->VlanId;
}
if (priorityInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(m_Context, priorityInfo.TagHeader.VlanId))
{
DPrintf(0, ("[%s] Discarded invalid priority tag %p\n", __FUNCTION__, priorityInfo.Value));
return false;
}
else if (priorityInfo.Value)
{
// ignore priority, if configured
if (!IsPrioritySupported(m_Context))
priorityInfo.TagHeader.UserPriority = 0;
// ignore VlanId, if specified
if (!IsVlanSupported(m_Context))
priorityInfo.TagHeader.VlanId = 0;
if (priorityInfo.Value)
{
m_TCI = static_cast<UINT16>(priorityInfo.TagHeader.UserPriority << 13 | priorityInfo.TagHeader.VlanId);
DPrintf(1, ("[%s] Populated priority tag %p\n", __FUNCTION__, priorityInfo.Value));
}
}
return true;
}
void CNBL::RegisterNB(CNB *NB)
{
m_Buffers.PushBack(NB);
m_BuffersNumber++;
}
void CNBL::RegisterMappedNB(CNB *NB)
{
if (m_MappedBuffers.PushBack(NB) == m_BuffersNumber)
{
m_ParentTXPath->NBLMappingDone(this);
}
}
bool CNBL::ParseBuffers()
{
m_MaxDataLength = 0;
for (auto NB = NET_BUFFER_LIST_FIRST_NB(m_NBL); NB != nullptr; NB = NET_BUFFER_NEXT_NB(NB))
{
CNB *NBHolder = new (m_Context->MiniportHandle) CNB(NB, this, m_Context);
if(!NBHolder || !NBHolder->IsValid())
{
return false;
}
RegisterNB(NBHolder);
m_MaxDataLength = max(m_MaxDataLength, NBHolder->GetDataLength());
}
if(m_MaxDataLength == 0)
{
DPrintf(0, ("Empty NBL (%p) dropped\n", __FUNCTION__, m_NBL));
return false;
}
return true;
}
bool CNBL::NeedsLSO()
{
return m_MaxDataLength > m_Context->MaxPacketSize.nMaxFullSizeOS;
}
bool CNBL::FitsLSO()
{
return (m_MaxDataLength <= PARANDIS_MAX_LSO_SIZE + LsoTcpHeaderOffset() + MAX_TCP_HEADER_SIZE);
}
bool CNBL::ParseLSO()
{
ASSERT(IsLSO());
if (m_LsoInfo.LsoV1Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V1_TYPE &&
m_LsoInfo.LsoV2Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE)
{
return false;
}
if (NeedsLSO() &&
(!m_LsoInfo.LsoV2Transmit.MSS ||
!m_LsoInfo.LsoV2Transmit.TcpHeaderOffset))
{
return false;
}
if (!FitsLSO())
{
return false;
}
if (!LsoTcpHeaderOffset() != !MSS())
{
return false;
}
if ((!m_Context->Offload.flags.fTxLso || !m_Context->bOffloadv4Enabled) &&
m_LsoInfo.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv4)
{
return false;
}
if (m_LsoInfo.LsoV2Transmit.Type == NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE &&
m_LsoInfo.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv6 &&
(!m_Context->Offload.flags.fTxLsov6 || !m_Context->bOffloadv6Enabled))
{
return false;
}
return true;
}
template <typename TClassPred, typename TOffloadPred, typename TSupportedPred>
bool CNBL::ParseCSO(TClassPred IsClass, TOffloadPred IsOffload,
TSupportedPred IsSupported, LPSTR OffloadName)
{
ASSERT(IsClass());
UNREFERENCED_PARAMETER(IsClass);
if (IsOffload())
{
if(!IsSupported())
{
DPrintf(0, ("[%s] %s request when it is not supported\n", __FUNCTION__, OffloadName));
#if FAIL_UNEXPECTED
// ignore unexpected CS requests while this passes WHQL
return false;
#endif
}
}
return true;
}
bool CNBL::ParseOffloads()
{
if (IsLSO())
{
if(!ParseLSO())
{
return false;
}
}
else if (IsIP4CSO())
{
if(!ParseCSO([this] () -> bool { return IsIP4CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.TcpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxTCPChecksum && m_Context->bOffloadv4Enabled; },
"TCP4 CSO"))
{
return false;
}
else if(!ParseCSO([this] () -> bool { return IsIP4CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.UdpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxUDPChecksum && m_Context->bOffloadv4Enabled; },
"UDP4 CSO"))
{
return false;
}
if(!ParseCSO([this] () -> bool { return IsIP4CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.IpHeaderChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxIPChecksum && m_Context->bOffloadv4Enabled; },
"IP4 CSO"))
{
return false;
}
}
else if (IsIP6CSO())
{
if(!ParseCSO([this] () -> bool { return IsIP6CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.TcpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxTCPv6Checksum && m_Context->bOffloadv6Enabled; },
"TCP6 CSO"))
{
return false;
}
else if(!ParseCSO([this] () -> bool { return IsIP6CSO(); },
[this] () -> bool { return m_CsoInfo.Transmit.UdpChecksum; },
[this] () -> bool { return m_Context->Offload.flags.fTxUDPv6Checksum && m_Context->bOffloadv6Enabled; },
"UDP6 CSO"))
{
return false;
}
}
return true;
}
void CNBL::StartMapping()
{
CDpcIrqlRaiser OnDpc;
AddRef();
m_Buffers.ForEachDetached([this](CNB *NB)
{
if (!NB->ScheduleBuildSGListForTx())
{
m_HaveFailedMappings = true;
NB->MappingDone(nullptr);
}
});
Release();
}
void CNBL::OnLastReferenceGone()
{
Destroy(this, m_Context->MiniportHandle);
}
CParaNdisTX::CParaNdisTX()
{ }
bool CParaNdisTX::Create(PPARANDIS_ADAPTER Context, UINT DeviceQueueIndex)
{
m_Context = Context;
m_queueIndex = (u16)DeviceQueueIndex;
return m_VirtQueue.Create(DeviceQueueIndex,
m_Context->IODevice,
m_Context->MiniportHandle,
m_Context->bDoPublishIndices ? true : false,
m_Context->maxFreeTxDescriptors,
m_Context->nVirtioHeaderSize,
m_Context);
}
void CParaNdisTX::Send(PNET_BUFFER_LIST NBL)
{
PNET_BUFFER_LIST nextNBL = nullptr;
for(auto currNBL = NBL; currNBL != nullptr; currNBL = nextNBL)
{
nextNBL = NET_BUFFER_LIST_NEXT_NBL(currNBL);
NET_BUFFER_LIST_NEXT_NBL(currNBL) = nullptr;
auto NBLHolder = new (m_Context->MiniportHandle) CNBL(currNBL, m_Context, *this);
if (NBLHolder == nullptr)
{
CNBL OnStack(currNBL, m_Context, *this);
OnStack.SetStatus(NDIS_STATUS_RESOURCES);
DPrintf(0, ("ERROR: Failed to allocate CNBL instance\n"));
continue;
}
if(NBLHolder->Prepare() &&
ParaNdis_IsSendPossible(m_Context))
{
NBLHolder->StartMapping();
}
else
{
NBLHolder->SetStatus(ParaNdis_ExactSendFailureStatus(m_Context));
NBLHolder->Release();
}
}
}
void CParaNdisTX::NBLMappingDone(CNBL *NBLHolder)
{
ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
if (NBLHolder->MappingSuceeded())
{
DoWithTXLock([NBLHolder, this](){ m_SendList.PushBack(NBLHolder); });
DoPendingTasks(false);
}
else
{
NBLHolder->SetStatus(NDIS_STATUS_FAILURE);
NBLHolder->Release();
}
}
CNB *CNBL::PopMappedNB()
{
m_MappedBuffersDetached++;
return m_MappedBuffers.Pop();
}
void CNBL::PushMappedNB(CNB *NB)
{
m_MappedBuffersDetached--;
m_MappedBuffers.Push(NB);
}
//TODO: Needs review
void CNBL::NBComplete()
{
m_BuffersDone++;
m_MappedBuffersDetached--;
}
bool CNBL::IsSendDone()
{
return m_BuffersDone == m_BuffersNumber;
}
//TODO: Needs review
void CNBL::CompleteMappedBuffers()
{
m_MappedBuffers.ForEachDetached([this](CNB *NB)
{
NBComplete();
CNB::Destroy(NB, m_Context->MiniportHandle);
});
}
PNET_BUFFER_LIST CNBL::DetachInternalObject()
{
// do it for both LsoV1 and LsoV2
if (IsLSO())
{
m_LsoInfo.LsoV1TransmitComplete.TcpPayload = m_TransferSize;
}
//Flush changes made in LSO structures
NET_BUFFER_LIST_INFO(m_NBL, TcpLargeSendNetBufferListInfo) = m_LsoInfo.Value;
auto Res = m_NBL;
m_NBL = nullptr;
return Res;
}
PNET_BUFFER_LIST CParaNdisTX::ProcessWaitingList()
{
PNET_BUFFER_LIST CompletedNBLs = nullptr;
m_WaitingList.ForEachDetachedIf([](CNBL* NBL) { return NBL->IsSendDone(); },
[&](CNBL* NBL)
{
NBL->SetStatus(NDIS_STATUS_SUCCESS);
auto RawNBL = NBL->DetachInternalObject();
NBL->Release();
NET_BUFFER_LIST_NEXT_NBL(RawNBL) = CompletedNBLs;
CompletedNBLs = RawNBL;
});
return CompletedNBLs;
}
//TODO: Needs review
PNET_BUFFER_LIST CParaNdisTX::RemoveAllNonWaitingNBLs()
{
PNET_BUFFER_LIST RemovedNBLs = nullptr;
auto status = ParaNdis_ExactSendFailureStatus(m_Context);
m_SendList.ForEachDetachedIf([](CNBL *NBL) { return !NBL->HaveDetachedBuffers(); },
[&](CNBL *NBL)
{
NBL->SetStatus(status);
auto RawNBL = NBL->DetachInternalObject();
NBL->Release();
NET_BUFFER_LIST_NEXT_NBL(RawNBL) = RemovedNBLs;
RemovedNBLs = RawNBL;
});
m_SendList.ForEach([](CNBL *NBL) { NBL->CompleteMappedBuffers(); });
return RemovedNBLs;
}
bool CParaNdisTX::Pause()
{
PNET_BUFFER_LIST NBL = nullptr;
bool res;
DoWithTXLock([this, &NBL, &res]()
{
NBL = RemoveAllNonWaitingNBLs();
res = (!m_VirtQueue.HasPacketsInHW() && m_WaitingList.IsEmpty());
});
if(NBL != nullptr)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, NBL, 0);
}
return res;
}
PNET_BUFFER_LIST CParaNdisTX::BuildCancelList(PVOID CancelId)
{
PNET_BUFFER_LIST CanceledNBLs = nullptr;
TSpinLocker LockedContext(m_Lock);
m_SendList.ForEachDetachedIf([CancelId](CNBL* NBL){ return NBL->MatchCancelID(CancelId) && !NBL->HaveDetachedBuffers(); },
[this, &CanceledNBLs](CNBL* NBL)
{
NBL->SetStatus(NDIS_STATUS_SEND_ABORTED);
auto RawNBL = NBL->DetachInternalObject();
NBL->Release();
NET_BUFFER_LIST_NEXT_NBL(RawNBL) = CanceledNBLs;
CanceledNBLs = RawNBL;
});
return CanceledNBLs;
}
void CParaNdisTX::CancelNBLs(PVOID CancelId)
{
auto CanceledNBLs = BuildCancelList(CancelId);
if (CanceledNBLs != nullptr)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, CanceledNBLs, 0);
}
}
//TODO: Requires review
BOOLEAN _Function_class_(MINIPORT_SYNCHRONIZE_INTERRUPT) CParaNdisTX::RestartQueueSynchronously(tSynchronizedContext *ctx)
{
auto TXPath = static_cast<CParaNdisTX *>(ctx->Parameter);
return !TXPath->m_VirtQueue.Restart();
}
//TODO: Requires review
bool CParaNdisTX::RestartQueue(bool DoKick)
{
TSpinLocker LockedContext(m_Lock);
auto res = ParaNdis_SynchronizeWithInterrupt(m_Context,
m_messageIndex,
CParaNdisTX::RestartQueueSynchronously,
this) ? true : false;
if(DoKick)
{
Kick();
}
return res;
}
bool CParaNdisTX::SendMapped(bool IsInterrupt, PNET_BUFFER_LIST &NBLFailNow)
{
if(!ParaNdis_IsSendPossible(m_Context))
{
NBLFailNow = RemoveAllNonWaitingNBLs();
if (NBLFailNow)
{
DPrintf(0, (__FUNCTION__ " Failing send"));
}
}
else
{
bool SentOutSomeBuffers = false;
auto HaveBuffers = true;
while (HaveBuffers && HaveMappedNBLs())
{
auto NBLHolder = PopMappedNBL();
if (NBLHolder->HaveMappedBuffers())
{
auto NBHolder = NBLHolder->PopMappedNB();
auto result = m_VirtQueue.SubmitPacket(*NBHolder);
switch (result)
{
case SUBMIT_NO_PLACE_IN_QUEUE:
NBLHolder->PushMappedNB(NBHolder);
PushMappedNBL(NBLHolder);
HaveBuffers = false;
// break the loop, allow to kick and free some buffers
break;
case SUBMIT_FAILURE:
case SUBMIT_SUCCESS:
case SUBMIT_PACKET_TOO_LARGE:
// if this NBL finished?
if (!NBLHolder->HaveMappedBuffers())
{
m_WaitingList.Push(NBLHolder);
}
else
{
// no, insert it back to the queue
PushMappedNBL(NBLHolder);
}
if (result == SUBMIT_SUCCESS)
{
SentOutSomeBuffers = true;
}
else
{
NBHolder->SendComplete();
CNB::Destroy(NBHolder, m_Context->MiniportHandle);
}
break;
default:
ASSERT(false);
break;
}
}
else
{
//TODO: Refactoring needed
//This is a case when pause called, mapped list cleared but NBL is still in the send list
m_WaitingList.Push(NBLHolder);
}
}
if (SentOutSomeBuffers)
{
DPrintf(2, ("[%s] sent down\n", __FUNCTION__, SentOutSomeBuffers));
if (IsInterrupt)
{
return true;
}
else
{
m_VirtQueue.Kick();
}
}
}
return false;
}
bool CParaNdisTX::DoPendingTasks(bool IsInterrupt)
{
ONPAUSECOMPLETEPROC CallbackToCall = nullptr;
PNET_BUFFER_LIST pNBLFailNow = nullptr;
PNET_BUFFER_LIST pNBLReturnNow = nullptr;
bool bDoKick = false;
DoWithTXLock([&] ()
{
m_VirtQueue.ProcessTXCompletions();
bDoKick = SendMapped(IsInterrupt, pNBLFailNow);
pNBLReturnNow = ProcessWaitingList();
{
CNdisPassiveWriteAutoLock tLock(m_Context->m_PauseLock);
if (!m_VirtQueue.HasPacketsInHW() && m_Context->SendState == srsPausing)
{
CallbackToCall = m_Context->SendPauseCompletionProc;
m_Context->SendPauseCompletionProc = nullptr;
m_Context->SendState = srsDisabled;
}
}
});
if (pNBLFailNow)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, pNBLFailNow,
NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL);
}
if (pNBLReturnNow)
{
NdisMSendNetBufferListsComplete(m_Context->MiniportHandle, pNBLReturnNow,
NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL);
}
if (CallbackToCall != nullptr)
{
CallbackToCall(m_Context);
}
return bDoKick;
}
void CNB::MappingDone(PSCATTER_GATHER_LIST SGL)
{
m_SGL = SGL;
m_ParentNBL->RegisterMappedNB(this);
}
CNB::~CNB()
{
ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
if(m_SGL != nullptr)
{
NdisMFreeNetBufferSGList(m_Context->DmaHandle, m_SGL, m_NB);
}
}
bool CNB::ScheduleBuildSGListForTx()
{
ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
return NdisMAllocateNetBufferSGList(m_Context->DmaHandle, m_NB, this,
NDIS_SG_LIST_WRITE_TO_DEVICE, nullptr, 0) == NDIS_STATUS_SUCCESS;
}
void CNB::PopulateIPLength(IPv4Header *IpHeader, USHORT IpLength) const
{
if ((IpHeader->ip_verlen & 0xF0) == 0x40)
{
if (!IpHeader->ip_length) {
IpHeader->ip_length = swap_short(IpLength);
}
}
}
void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
FALSE,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
}
USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), FALSE, __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
}
void CNB::SetupCSO(virtio_net_hdr_basic *VirtioHeader, ULONG L4HeaderOffset) const
{
u16 PriorityHdrLen = m_ParentNBL->TCI() ? ETH_PRIORITY_HEADER_SIZE : 0;
VirtioHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VirtioHeader->csum_start = static_cast<u16>(L4HeaderOffset) + PriorityHdrLen;
VirtioHeader->csum_offset = m_ParentNBL->IsTcpCSO() ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET;
}
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const
{
ParaNdis_CheckSumVerifyFlat(IpHeader,
EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum, FALSE,
__FUNCTION__);
}
bool CNB::FillDescriptorSGList(CTXDescriptor &Descriptor, ULONG ParsedHeadersLength) const
{
return Descriptor.SetupHeaders(ParsedHeadersLength) &&
MapDataToVirtioSGL(Descriptor, ParsedHeadersLength + NET_BUFFER_DATA_OFFSET(m_NB));
}
bool CNB::MapDataToVirtioSGL(CTXDescriptor &Descriptor, ULONG Offset) const
{
for (ULONG i = 0; i < m_SGL->NumberOfElements; i++)
{
if (Offset < m_SGL->Elements[i].Length)
{
PHYSICAL_ADDRESS PA;
PA.QuadPart = m_SGL->Elements[i].Address.QuadPart + Offset;
if (!Descriptor.AddDataChunk(PA, m_SGL->Elements[i].Length - Offset))
{
return false;
}
Offset = 0;
}
else
{
Offset -= m_SGL->Elements[i].Length;
}
}
return true;
}
bool CNB::CopyHeaders(PVOID Destination, ULONG MaxSize, ULONG &HeadersLength, ULONG &L4HeaderOffset) const
{
HeadersLength = 0;
L4HeaderOffset = 0;
if (m_ParentNBL->IsLSO() || m_ParentNBL->IsTcpCSO())
{
L4HeaderOffset = m_ParentNBL->TCPHeaderOffset();
HeadersLength = L4HeaderOffset + sizeof(TCPHeader);
Copy(Destination, HeadersLength);
}
else if (m_ParentNBL->IsUdpCSO())
{
Copy(Destination, MaxSize);
L4HeaderOffset = QueryL4HeaderOffset(Destination, m_Context->Offload.ipHeaderOffset);
HeadersLength = L4HeaderOffset + sizeof(UDPHeader);
}
else if (m_ParentNBL->IsIPHdrCSO())
{
Copy(Destination, MaxSize);
HeadersLength = QueryL4HeaderOffset(Destination, m_Context->Offload.ipHeaderOffset);
L4HeaderOffset = HeadersLength;
}
else
{
HeadersLength = ETH_HEADER_SIZE;
Copy(Destination, HeadersLength);
}
return (HeadersLength <= MaxSize);
}
void CNB::BuildPriorityHeader(PETH_HEADER EthHeader, PVLAN_HEADER VlanHeader) const
{
VlanHeader->TCI = RtlUshortByteSwap(m_ParentNBL->TCI());
if (VlanHeader->TCI != 0)
{
VlanHeader->EthType = EthHeader->EthType;
EthHeader->EthType = RtlUshortByteSwap(PRIO_HEADER_ETH_TYPE);
}
}
void CNB::PrepareOffloads(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength, ULONG L4HeaderOffset) const
{
*VirtioHeader = {};
if (m_ParentNBL->IsLSO())
{
SetupLSO(VirtioHeader, IpHeader, EthPayloadLength);
}
else if (m_ParentNBL->IsTcpCSO() || m_ParentNBL->IsUdpCSO())
{
SetupCSO(VirtioHeader, L4HeaderOffset);
}
if (m_ParentNBL->IsIPHdrCSO())
{
DoIPHdrCSO(IpHeader, EthPayloadLength);
}
}
bool CNB::BindToDescriptor(CTXDescriptor &Descriptor)
{
if (m_SGL == nullptr)
{
return false;
}
Descriptor.SetNB(this);
auto &HeadersArea = Descriptor.HeadersAreaAccessor();
auto EthHeaders = HeadersArea.EthHeadersAreaVA();
ULONG HeadersLength;
ULONG L4HeaderOffset;
if (!CopyHeaders(EthHeaders, HeadersArea.MaxEthHeadersSize(), HeadersLength, L4HeaderOffset))
{
return false;
}
BuildPriorityHeader(HeadersArea.EthHeader(), HeadersArea.VlanHeader());
PrepareOffloads(HeadersArea.VirtioHeader(),
HeadersArea.IPHeaders(),
GetDataLength() - m_Context->Offload.ipHeaderOffset,
L4HeaderOffset);
return FillDescriptorSGList(Descriptor, HeadersLength);
}
bool CNB::Copy(PVOID Dst, ULONG Length) const
{
ULONG CurrOffset = NET_BUFFER_CURRENT_MDL_OFFSET(m_NB);
ULONG Copied = 0;
for (PMDL CurrMDL = NET_BUFFER_CURRENT_MDL(m_NB);
CurrMDL != nullptr && Copied < Length;
CurrMDL = CurrMDL->Next)
{
ULONG CurrLen;
PVOID CurrAddr;
#if NDIS_SUPPORT_NDIS620
NdisQueryMdl(CurrMDL, &CurrAddr, &CurrLen, LowPagePriority | MdlMappingNoExecute);
#else
NdisQueryMdl(CurrMDL, &CurrAddr, &CurrLen, LowPagePriority);
#endif
if (CurrAddr == nullptr)
{
break;
}
CurrLen = min(CurrLen - CurrOffset, Length - Copied);
NdisMoveMemory(RtlOffsetToPointer(Dst, Copied),
RtlOffsetToPointer(CurrAddr, CurrOffset),
CurrLen);
Copied += CurrLen;
CurrOffset = 0;
}
return (Copied == Length);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/good_1580_1 |
crossvul-cpp_data_bad_2411_1 | /*
Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "session_base.hpp"
#include "i_engine.hpp"
#include "err.hpp"
#include "pipe.hpp"
#include "likely.hpp"
#include "tcp_connecter.hpp"
#include "ipc_connecter.hpp"
#include "pgm_sender.hpp"
#include "pgm_receiver.hpp"
#include "address.hpp"
#include "ctx.hpp"
#include "req.hpp"
zmq::session_base_t *zmq::session_base_t::create (class io_thread_t *io_thread_,
bool connect_, class socket_base_t *socket_, const options_t &options_,
const address_t *addr_)
{
session_base_t *s = NULL;
switch (options_.type) {
case ZMQ_REQ:
s = new (std::nothrow) req_session_t (io_thread_, connect_,
socket_, options_, addr_);
break;
case ZMQ_DEALER:
case ZMQ_REP:
case ZMQ_ROUTER:
case ZMQ_PUB:
case ZMQ_XPUB:
case ZMQ_SUB:
case ZMQ_XSUB:
case ZMQ_PUSH:
case ZMQ_PULL:
case ZMQ_PAIR:
case ZMQ_STREAM:
s = new (std::nothrow) session_base_t (io_thread_, connect_,
socket_, options_, addr_);
break;
default:
errno = EINVAL;
return NULL;
}
alloc_assert (s);
return s;
}
zmq::session_base_t::session_base_t (class io_thread_t *io_thread_,
bool connect_, class socket_base_t *socket_, const options_t &options_,
const address_t *addr_) :
own_t (io_thread_, options_),
io_object_t (io_thread_),
connect (connect_),
pipe (NULL),
zap_pipe (NULL),
incomplete_in (false),
pending (false),
engine (NULL),
socket (socket_),
io_thread (io_thread_),
has_linger_timer (false),
addr (addr_)
{
}
zmq::session_base_t::~session_base_t ()
{
zmq_assert (!pipe);
zmq_assert (!zap_pipe);
// If there's still a pending linger timer, remove it.
if (has_linger_timer) {
cancel_timer (linger_timer_id);
has_linger_timer = false;
}
// Close the engine.
if (engine)
engine->terminate ();
delete addr;
}
void zmq::session_base_t::attach_pipe (pipe_t *pipe_)
{
zmq_assert (!is_terminating ());
zmq_assert (!pipe);
zmq_assert (pipe_);
pipe = pipe_;
pipe->set_event_sink (this);
}
int zmq::session_base_t::pull_msg (msg_t *msg_)
{
if (!pipe || !pipe->read (msg_)) {
errno = EAGAIN;
return -1;
}
incomplete_in = msg_->flags () & msg_t::more ? true : false;
return 0;
}
int zmq::session_base_t::push_msg (msg_t *msg_)
{
if (pipe && pipe->write (msg_)) {
int rc = msg_->init ();
errno_assert (rc == 0);
return 0;
}
errno = EAGAIN;
return -1;
}
int zmq::session_base_t::read_zap_msg (msg_t *msg_)
{
if (zap_pipe == NULL) {
errno = ENOTCONN;
return -1;
}
if (!zap_pipe->read (msg_)) {
errno = EAGAIN;
return -1;
}
return 0;
}
int zmq::session_base_t::write_zap_msg (msg_t *msg_)
{
if (zap_pipe == NULL) {
errno = ENOTCONN;
return -1;
}
const bool ok = zap_pipe->write (msg_);
zmq_assert (ok);
if ((msg_->flags () & msg_t::more) == 0)
zap_pipe->flush ();
const int rc = msg_->init ();
errno_assert (rc == 0);
return 0;
}
void zmq::session_base_t::reset ()
{
}
void zmq::session_base_t::flush ()
{
if (pipe)
pipe->flush ();
}
void zmq::session_base_t::clean_pipes ()
{
if (pipe) {
// Get rid of half-processed messages in the out pipe. Flush any
// unflushed messages upstream.
pipe->rollback ();
pipe->flush ();
// Remove any half-read message from the in pipe.
while (incomplete_in) {
msg_t msg;
int rc = msg.init ();
errno_assert (rc == 0);
rc = pull_msg (&msg);
errno_assert (rc == 0);
rc = msg.close ();
errno_assert (rc == 0);
}
}
}
void zmq::session_base_t::pipe_terminated (pipe_t *pipe_)
{
// Drop the reference to the deallocated pipe if required.
zmq_assert (pipe_ == pipe
|| pipe_ == zap_pipe
|| terminating_pipes.count (pipe_) == 1);
if (pipe_ == pipe)
// If this is our current pipe, remove it
pipe = NULL;
else
if (pipe_ == zap_pipe) {
zap_pipe = NULL;
}
else
// Remove the pipe from the detached pipes set
terminating_pipes.erase (pipe_);
if (!is_terminating () && options.raw_sock) {
if (engine) {
engine->terminate ();
engine = NULL;
}
terminate ();
}
// If we are waiting for pending messages to be sent, at this point
// we are sure that there will be no more messages and we can proceed
// with termination safely.
if (pending && !pipe && !zap_pipe && terminating_pipes.empty ())
proceed_with_term ();
}
void zmq::session_base_t::read_activated (pipe_t *pipe_)
{
// Skip activating if we're detaching this pipe
if (unlikely(pipe_ != pipe && pipe_ != zap_pipe)) {
zmq_assert (terminating_pipes.count (pipe_) == 1);
return;
}
if (unlikely (engine == NULL)) {
pipe->check_read ();
return;
}
if (likely (pipe_ == pipe))
engine->restart_output ();
else
engine->zap_msg_available ();
}
void zmq::session_base_t::write_activated (pipe_t *pipe_)
{
// Skip activating if we're detaching this pipe
if (pipe != pipe_) {
zmq_assert (terminating_pipes.count (pipe_) == 1);
return;
}
if (engine)
engine->restart_input ();
}
void zmq::session_base_t::hiccuped (pipe_t *)
{
// Hiccups are always sent from session to socket, not the other
// way round.
zmq_assert (false);
}
zmq::socket_base_t *zmq::session_base_t::get_socket ()
{
return socket;
}
void zmq::session_base_t::process_plug ()
{
if (connect)
start_connecting (false);
}
int zmq::session_base_t::zap_connect ()
{
zmq_assert (zap_pipe == NULL);
endpoint_t peer = find_endpoint ("inproc://zeromq.zap.01");
if (peer.socket == NULL) {
errno = ECONNREFUSED;
return -1;
}
if (peer.options.type != ZMQ_REP
&& peer.options.type != ZMQ_ROUTER) {
errno = ECONNREFUSED;
return -1;
}
// Create a bi-directional pipe that will connect
// session with zap socket.
object_t *parents [2] = {this, peer.socket};
pipe_t *new_pipes [2] = {NULL, NULL};
int hwms [2] = {0, 0};
bool conflates [2] = {false, false};
int rc = pipepair (parents, new_pipes, hwms, conflates);
errno_assert (rc == 0);
// Attach local end of the pipe to this socket object.
zap_pipe = new_pipes [0];
zap_pipe->set_nodelay ();
zap_pipe->set_event_sink (this);
send_bind (peer.socket, new_pipes [1], false);
// Send empty identity if required by the peer.
if (peer.options.recv_identity) {
msg_t id;
rc = id.init ();
errno_assert (rc == 0);
id.set_flags (msg_t::identity);
bool ok = zap_pipe->write (&id);
zmq_assert (ok);
zap_pipe->flush ();
}
return 0;
}
void zmq::session_base_t::process_attach (i_engine *engine_)
{
zmq_assert (engine_ != NULL);
// Create the pipe if it does not exist yet.
if (!pipe && !is_terminating ()) {
object_t *parents [2] = {this, socket};
pipe_t *pipes [2] = {NULL, NULL};
bool conflate = options.conflate &&
(options.type == ZMQ_DEALER ||
options.type == ZMQ_PULL ||
options.type == ZMQ_PUSH ||
options.type == ZMQ_PUB ||
options.type == ZMQ_SUB);
int hwms [2] = {conflate? -1 : options.rcvhwm,
conflate? -1 : options.sndhwm};
bool conflates [2] = {conflate, conflate};
int rc = pipepair (parents, pipes, hwms, conflates);
errno_assert (rc == 0);
// Plug the local end of the pipe.
pipes [0]->set_event_sink (this);
// Remember the local end of the pipe.
zmq_assert (!pipe);
pipe = pipes [0];
// Ask socket to plug into the remote end of the pipe.
send_bind (socket, pipes [1]);
}
// Plug in the engine.
zmq_assert (!engine);
engine = engine_;
engine->plug (io_thread, this);
}
void zmq::session_base_t::detach ()
{
// Engine is dead. Let's forget about it.
engine = NULL;
// Remove any half-done messages from the pipes.
clean_pipes ();
// Send the event to the derived class.
detached ();
// Just in case there's only a delimiter in the pipe.
if (pipe)
pipe->check_read ();
if (zap_pipe)
zap_pipe->check_read ();
}
void zmq::session_base_t::process_term (int linger_)
{
zmq_assert (!pending);
// If the termination of the pipe happens before the term command is
// delivered there's nothing much to do. We can proceed with the
// standard termination immediately.
if (!pipe && !zap_pipe) {
proceed_with_term ();
return;
}
pending = true;
if (pipe != NULL) {
// If there's finite linger value, delay the termination.
// If linger is infinite (negative) we don't even have to set
// the timer.
if (linger_ > 0) {
zmq_assert (!has_linger_timer);
add_timer (linger_, linger_timer_id);
has_linger_timer = true;
}
// Start pipe termination process. Delay the termination till all messages
// are processed in case the linger time is non-zero.
pipe->terminate (linger_ != 0);
// TODO: Should this go into pipe_t::terminate ?
// In case there's no engine and there's only delimiter in the
// pipe it wouldn't be ever read. Thus we check for it explicitly.
pipe->check_read ();
}
if (zap_pipe != NULL)
zap_pipe->terminate (false);
}
void zmq::session_base_t::proceed_with_term ()
{
// The pending phase has just ended.
pending = false;
// Continue with standard termination.
own_t::process_term (0);
}
void zmq::session_base_t::timer_event (int id_)
{
// Linger period expired. We can proceed with termination even though
// there are still pending messages to be sent.
zmq_assert (id_ == linger_timer_id);
has_linger_timer = false;
// Ask pipe to terminate even though there may be pending messages in it.
zmq_assert (pipe);
pipe->terminate (false);
}
void zmq::session_base_t::detached ()
{
// Transient session self-destructs after peer disconnects.
if (!connect) {
terminate ();
return;
}
// For delayed connect situations, terminate the pipe
// and reestablish later on
if (pipe && options.immediate == 1
&& addr->protocol != "pgm" && addr->protocol != "epgm") {
pipe->hiccup ();
pipe->terminate (false);
terminating_pipes.insert (pipe);
pipe = NULL;
}
reset ();
// Reconnect.
if (options.reconnect_ivl != -1)
start_connecting (true);
// For subscriber sockets we hiccup the inbound pipe, which will cause
// the socket object to resend all the subscriptions.
if (pipe && (options.type == ZMQ_SUB || options.type == ZMQ_XSUB))
pipe->hiccup ();
}
void zmq::session_base_t::start_connecting (bool wait_)
{
zmq_assert (connect);
// Choose I/O thread to run connecter in. Given that we are already
// running in an I/O thread, there must be at least one available.
io_thread_t *io_thread = choose_io_thread (options.affinity);
zmq_assert (io_thread);
// Create the connecter object.
if (addr->protocol == "tcp") {
tcp_connecter_t *connecter = new (std::nothrow) tcp_connecter_t (
io_thread, this, options, addr, wait_);
alloc_assert (connecter);
launch_child (connecter);
return;
}
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
if (addr->protocol == "ipc") {
ipc_connecter_t *connecter = new (std::nothrow) ipc_connecter_t (
io_thread, this, options, addr, wait_);
alloc_assert (connecter);
launch_child (connecter);
return;
}
#endif
#ifdef ZMQ_HAVE_OPENPGM
// Both PGM and EPGM transports are using the same infrastructure.
if (addr->protocol == "pgm" || addr->protocol == "epgm") {
zmq_assert (options.type == ZMQ_PUB || options.type == ZMQ_XPUB
|| options.type == ZMQ_SUB || options.type == ZMQ_XSUB);
// For EPGM transport with UDP encapsulation of PGM is used.
bool const udp_encapsulation = addr->protocol == "epgm";
// At this point we'll create message pipes to the session straight
// away. There's no point in delaying it as no concept of 'connect'
// exists with PGM anyway.
if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB) {
// PGM sender.
pgm_sender_t *pgm_sender = new (std::nothrow) pgm_sender_t (
io_thread, options);
alloc_assert (pgm_sender);
int rc = pgm_sender->init (udp_encapsulation, addr->address.c_str ());
errno_assert (rc == 0);
send_attach (this, pgm_sender);
}
else {
// PGM receiver.
pgm_receiver_t *pgm_receiver = new (std::nothrow) pgm_receiver_t (
io_thread, options);
alloc_assert (pgm_receiver);
int rc = pgm_receiver->init (udp_encapsulation, addr->address.c_str ());
errno_assert (rc == 0);
send_attach (this, pgm_receiver);
}
return;
}
#endif
zmq_assert (false);
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_2411_1 |
crossvul-cpp_data_bad_600_0 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/HTTP2Constants.h>
#include <proxygen/lib/http/codec/CodecUtil.h>
#include <proxygen/lib/utils/Logging.h>
#include <proxygen/lib/utils/Base64.h>
#include <folly/Conv.h>
#include <folly/Random.h>
#include <folly/ThreadLocal.h>
#include <folly/io/Cursor.h>
#include <folly/tracing/ScopedTraceSection.h>
#include <type_traits>
using namespace proxygen::compress;
using namespace folly::io;
using namespace folly;
using std::string;
namespace {
std::string base64url_encode(ByteRange range) {
return proxygen::Base64::urlEncode(range);
}
std::string base64url_decode(const std::string& str) {
return proxygen::Base64::urlDecode(str);
}
}
namespace proxygen {
HTTP2Codec::HTTP2Codec(TransportDirection direction)
: HTTPParallelCodec(direction),
headerCodec_(direction),
frameState_(direction == TransportDirection::DOWNSTREAM
? FrameState::UPSTREAM_CONNECTION_PREFACE
: FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
const auto maxHeaderListSize = egressSettings_.getSetting(
SettingsId::MAX_HEADER_LIST_SIZE);
if (maxHeaderListSize) {
headerCodec_.setMaxUncompressed(maxHeaderListSize->value);
}
VLOG(4) << "creating " << getTransportDirectionString(direction)
<< " HTTP/2 codec";
}
HTTP2Codec::~HTTP2Codec() {}
// HTTPCodec API
size_t HTTP2Codec::onIngress(const folly::IOBuf& buf) {
// TODO: ensure only 1 parse at a time on stack.
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - onIngress");
Cursor cursor(&buf);
size_t parsed = 0;
ErrorCode connError = ErrorCode::NO_ERROR;
for (auto bufLen = cursor.totalLength();
connError == ErrorCode::NO_ERROR;
bufLen = cursor.totalLength()) {
if (frameState_ == FrameState::UPSTREAM_CONNECTION_PREFACE) {
if (bufLen >= http2::kConnectionPreface.length()) {
auto test = cursor.readFixedString(http2::kConnectionPreface.length());
parsed += http2::kConnectionPreface.length();
if (test != http2::kConnectionPreface) {
goawayErrorMessage_ = "missing connection preface";
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
} else if (frameState_ == FrameState::FRAME_HEADER ||
frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
// Waiting to parse the common frame header
if (bufLen >= http2::kFrameHeaderSize) {
connError = parseFrameHeader(cursor, curHeader_);
parsed += http2::kFrameHeaderSize;
if (frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE &&
curHeader_.type != http2::FrameType::SETTINGS) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: got invalid connection preface frame type=",
getFrameTypeString(curHeader_.type), "(", curHeader_.type, ")",
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
if (curHeader_.length > maxRecvFrameSize()) {
VLOG(4) << "Excessively large frame len=" << curHeader_.length;
connError = ErrorCode::FRAME_SIZE_ERROR;
}
if (callback_) {
callback_->onFrameHeader(
curHeader_.stream,
curHeader_.flags,
curHeader_.length,
static_cast<uint8_t>(curHeader_.type));
}
frameState_ = (curHeader_.type == http2::FrameType::DATA) ?
FrameState::DATA_FRAME_DATA : FrameState::FRAME_DATA;
pendingDataFrameBytes_ = curHeader_.length;
pendingDataFramePaddingBytes_ = 0;
#ifndef NDEBUG
receivedFrameCount_++;
#endif
} else {
break;
}
} else if (frameState_ == FrameState::DATA_FRAME_DATA && bufLen > 0 &&
(bufLen < curHeader_.length ||
pendingDataFrameBytes_ < curHeader_.length)) {
// FrameState::DATA_FRAME_DATA with partial data only
size_t dataParsed = 0;
connError = parseDataFrameData(cursor, bufLen, dataParsed);
if (dataParsed == 0 && pendingDataFrameBytes_ > 0) {
// We received only the padding byte, we will wait for more
break;
} else {
parsed += dataParsed;
if (pendingDataFrameBytes_ == 0) {
frameState_ = FrameState::FRAME_HEADER;
}
}
} else { // FrameState::FRAME_DATA
// or FrameState::DATA_FRAME_DATA with all data available
// Already parsed the common frame header
const auto frameLen = curHeader_.length;
if (bufLen >= frameLen) {
connError = parseFrame(cursor);
parsed += curHeader_.length;
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
}
}
checkConnectionError(connError, &buf);
return parsed;
}
ErrorCode HTTP2Codec::parseFrame(folly::io::Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseFrame");
if (expectedContinuationStream_ != 0 &&
(curHeader_.type != http2::FrameType::CONTINUATION ||
expectedContinuationStream_ != curHeader_.stream)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: while expected CONTINUATION with stream=",
expectedContinuationStream_, ", received streamID=", curHeader_.stream,
" of type=", getFrameTypeString(curHeader_.type));
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (expectedContinuationStream_ == 0 &&
curHeader_.type == http2::FrameType::CONTINUATION) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: unexpected CONTINUATION received with streamID=",
curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (frameAffectsCompression(curHeader_.type) &&
curHeaderBlock_.chainLength() + curHeader_.length >
egressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, 0)) {
// this may be off by up to the padding length (max 255), but
// these numbers are already so generous, and we're comparing the
// max-uncompressed to the actual compressed size. Let's fail
// before buffering.
// TODO(t6513634): it would be nicer to stream-process this header
// block to keep the connection state consistent without consuming
// memory, and fail just the request per the HTTP/2 spec (section
// 10.3)
goawayErrorMessage_ = folly::to<string>(
"Failing connection due to excessively large headers");
LOG(ERROR) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
expectedContinuationStream_ =
(frameAffectsCompression(curHeader_.type) &&
!(curHeader_.flags & http2::END_HEADERS)) ? curHeader_.stream : 0;
switch (curHeader_.type) {
case http2::FrameType::DATA:
return parseAllData(cursor);
case http2::FrameType::HEADERS:
return parseHeaders(cursor);
case http2::FrameType::PRIORITY:
return parsePriority(cursor);
case http2::FrameType::RST_STREAM:
return parseRstStream(cursor);
case http2::FrameType::SETTINGS:
return parseSettings(cursor);
case http2::FrameType::PUSH_PROMISE:
return parsePushPromise(cursor);
case http2::FrameType::EX_HEADERS:
if (ingressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
return parseExHeaders(cursor);
} else {
VLOG(2) << "EX_HEADERS not enabled, ignoring the frame";
break;
}
case http2::FrameType::PING:
return parsePing(cursor);
case http2::FrameType::GOAWAY:
return parseGoaway(cursor);
case http2::FrameType::WINDOW_UPDATE:
return parseWindowUpdate(cursor);
case http2::FrameType::CONTINUATION:
return parseContinuation(cursor);
case http2::FrameType::ALTSVC:
// fall through, unimplemented
break;
case http2::FrameType::CERTIFICATE_REQUEST:
return parseCertificateRequest(cursor);
case http2::FrameType::CERTIFICATE:
return parseCertificate(cursor);
default:
// Implementations MUST ignore and discard any frame that has a
// type that is unknown
break;
}
// Landing here means unknown, unimplemented or ignored frame.
VLOG(2) << "Skipping frame (type=" << (uint8_t)curHeader_.type << ")";
cursor.skip(curHeader_.length);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::handleEndStream() {
if (curHeader_.type != http2::FrameType::HEADERS &&
curHeader_.type != http2::FrameType::EX_HEADERS &&
curHeader_.type != http2::FrameType::CONTINUATION &&
curHeader_.type != http2::FrameType::DATA) {
return ErrorCode::NO_ERROR;
}
// do we need to handle case where this stream has already aborted via
// another callback (onHeadersComplete/onBody)?
pendingEndStreamHandling_ |= (curHeader_.flags & http2::END_STREAM);
// with a websocket upgrade, we need to send message complete cb to
// mirror h1x codec's behavior. when the stream closes, we need to
// send another callback to clean up the stream's resources.
if (ingressWebsocketUpgrade_) {
ingressWebsocketUpgrade_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, true);
}
if (pendingEndStreamHandling_ && expectedContinuationStream_ == 0) {
pendingEndStreamHandling_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, false);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseAllData(Cursor& cursor) {
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing all frame DATA bytes for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto ret = http2::parseData(cursor, curHeader_, outData, padding);
RETURN_IF_ERROR(ret);
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return handleEndStream();
}
ErrorCode HTTP2Codec::parseDataFrameData(Cursor& cursor,
size_t bufLen,
size_t& parsed) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseDataFrameData");
if (bufLen == 0) {
VLOG(10) << "No data to parse";
return ErrorCode::NO_ERROR;
}
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing DATA frame data for stream=" << curHeader_.stream <<
" frame data length=" << curHeader_.length << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
// Parse the padding information only the first time
if (pendingDataFrameBytes_ == curHeader_.length &&
pendingDataFramePaddingBytes_ == 0) {
if (frameHasPadding(curHeader_) && bufLen == 1) {
// We need to wait for more bytes otherwise we won't be able to pass
// the correct padding to the first onBody call
return ErrorCode::NO_ERROR;
}
const auto ret = http2::parseDataBegin(cursor, curHeader_, parsed, padding);
RETURN_IF_ERROR(ret);
if (padding > 0) {
pendingDataFramePaddingBytes_ = padding - 1;
pendingDataFrameBytes_--;
bufLen--;
parsed++;
}
VLOG(10) << "out padding=" << padding << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
if (bufLen > 0) {
// Check if we have application data to parse
if (pendingDataFrameBytes_ > pendingDataFramePaddingBytes_) {
const size_t pendingAppData =
pendingDataFrameBytes_ - pendingDataFramePaddingBytes_;
const size_t toClone = std::min(pendingAppData, bufLen);
cursor.clone(outData, toClone);
bufLen -= toClone;
pendingDataFrameBytes_ -= toClone;
parsed += toClone;
VLOG(10) << "parsed some app data, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
// Check if we have padding bytes to parse
if (bufLen > 0 && pendingDataFramePaddingBytes_ > 0) {
size_t toSkip = 0;
auto ret = http2::parseDataEnd(cursor, bufLen,
pendingDataFramePaddingBytes_, toSkip);
RETURN_IF_ERROR(ret);
pendingDataFrameBytes_ -= toSkip;
pendingDataFramePaddingBytes_ -= toSkip;
parsed += toSkip;
VLOG(10) << "parsed some padding, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
}
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return (pendingDataFrameBytes_ > 0) ? ErrorCode::NO_ERROR : handleEndStream();
}
ErrorCode HTTP2Codec::parseHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseHeaders");
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing HEADERS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseHeaders(cursor, curHeader_, priority, headerBuf);
RETURN_IF_ERROR(err);
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, true /* trailersAllowed */));
}
err = parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
folly::none);
return err;
}
ErrorCode HTTP2Codec::parseExHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseExHeaders");
HTTPCodec::ExAttributes exAttributes;
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing ExHEADERS frame for stream=" << curHeader_.stream
<< " length=" << curHeader_.length;
auto err = http2::parseExHeaders(
cursor, curHeader_, exAttributes, priority, headerBuf);
RETURN_IF_ERROR(err);
if (isRequest(curHeader_.stream)) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, false /* trailersAllowed */));
}
return parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
exAttributes);
}
ErrorCode HTTP2Codec::parseContinuation(Cursor& cursor) {
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing CONTINUATION frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseContinuation(cursor, curHeader_, headerBuf);
RETURN_IF_ERROR(err);
err = parseHeadersImpl(cursor, std::move(headerBuf),
folly::none, folly::none, folly::none);
return err;
}
ErrorCode HTTP2Codec::parseHeadersImpl(
Cursor& /*cursor*/,
std::unique_ptr<IOBuf> headerBuf,
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes) {
curHeaderBlock_.append(std::move(headerBuf));
std::unique_ptr<HTTPMessage> msg;
if (curHeader_.flags & http2::END_HEADERS) {
auto errorCode =
parseHeadersDecodeFrames(priority, promisedStream, exAttributes, msg);
if (errorCode.hasValue()) {
return errorCode.value();
}
}
// if we're not parsing CONTINUATION, then it's start of new header block
if (curHeader_.type != http2::FrameType::CONTINUATION) {
headerBlockFrameType_ = curHeader_.type;
}
// Report back what we've parsed
if (callback_) {
auto concurError = parseHeadersCheckConcurrentStreams(priority);
if (concurError.hasValue()) {
return concurError.value();
}
uint32_t headersCompleteStream = curHeader_.stream;
bool trailers = parsingTrailers();
bool allHeaderFramesReceived =
(curHeader_.flags & http2::END_HEADERS) &&
(headerBlockFrameType_ == http2::FrameType::HEADERS);
if (allHeaderFramesReceived && !trailers) {
// Only deliver onMessageBegin once per stream.
// For responses with CONTINUATION, this will be delayed until
// the frame with the END_HEADERS flag set.
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageBegin,
"onMessageBegin",
curHeader_.stream,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::EX_HEADERS) {
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onExMessageBegin,
"onExMessageBegin",
curHeader_.stream,
exAttributes->controlStream,
exAttributes->unidirectional,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::PUSH_PROMISE) {
DCHECK(promisedStream);
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onPushMessageBegin,
"onPushMessageBegin", *promisedStream,
curHeader_.stream, msg.get())) {
return handleEndStream();
}
headersCompleteStream = *promisedStream;
}
if (curHeader_.flags & http2::END_HEADERS && msg) {
if (!(curHeader_.flags & http2::END_STREAM)) {
// If it there are DATA frames coming, consider it chunked
msg->setIsChunked(true);
}
if (trailers) {
VLOG(4) << "Trailers complete for streamId=" << headersCompleteStream
<< " direction=" << transportDirection_;
auto trailerHeaders =
std::make_unique<HTTPHeaders>(msg->extractHeaders());
msg.reset();
callback_->onTrailersComplete(headersCompleteStream,
std::move(trailerHeaders));
} else {
callback_->onHeadersComplete(headersCompleteStream, std::move(msg));
}
}
return handleEndStream();
}
return ErrorCode::NO_ERROR;
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersDecodeFrames(
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes,
std::unique_ptr<HTTPMessage>& msg) {
// decompress headers
Cursor headerCursor(curHeaderBlock_.front());
bool isReq = false;
if (promisedStream) {
isReq = true;
} else if (exAttributes) {
isReq = isRequest(curHeader_.stream);
} else {
isReq = transportDirection_ == TransportDirection::DOWNSTREAM;
}
// Validate circular dependencies.
if (priority && (curHeader_.stream == priority->streamDependency)) {
streamError(
folly::to<string>("Circular dependency for txn=", curHeader_.stream),
ErrorCode::PROTOCOL_ERROR,
curHeader_.type == http2::FrameType::HEADERS);
return ErrorCode::NO_ERROR;
}
decodeInfo_.init(isReq, parsingDownstreamTrailers_);
if (priority) {
decodeInfo_.msg->setHTTP2Priority(
std::make_tuple(priority->streamDependency,
priority->exclusive,
priority->weight));
}
headerCodec_.decodeStreaming(
headerCursor, curHeaderBlock_.chainLength(), this);
msg = std::move(decodeInfo_.msg);
// Saving this in case we need to log it on error
auto g = folly::makeGuard([this] { curHeaderBlock_.move(); });
// Check decoding error
if (decodeInfo_.decodeError != HPACK::DecodeError::NONE) {
static const std::string decodeErrorMessage =
"Failed decoding header block for stream=";
// Avoid logging header blocks that have failed decoding due to being
// excessively large.
if (decodeInfo_.decodeError != HPACK::DecodeError::HEADERS_TOO_LARGE) {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream
<< " header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
} else {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream;
}
if (msg) {
// print the partial message
msg->dumpMessage(3);
}
return ErrorCode::COMPRESSION_ERROR;
}
// Check parsing error
if (decodeInfo_.parsingError != "") {
LOG(ERROR) << "Failed parsing header list for stream=" << curHeader_.stream
<< ", error=" << decodeInfo_.parsingError << ", header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
HTTPException err(HTTPException::Direction::INGRESS,
folly::to<std::string>("HTTP2Codec stream error: ",
"stream=",
curHeader_.stream,
" status=",
400,
" error: ",
decodeInfo_.parsingError));
err.setHttpStatusCode(400);
callback_->onError(curHeader_.stream, err, true);
return ErrorCode::NO_ERROR;
}
return folly::Optional<ErrorCode>();
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersCheckConcurrentStreams(
const folly::Optional<http2::PriorityUpdate>& priority) {
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::EX_HEADERS) {
if (curHeader_.flags & http2::PRIORITY) {
DCHECK(priority);
// callback_->onPriority(priority.get());
}
// callback checks total number of streams is smaller than settings max
if (callback_->numIncomingStreams() >=
egressSettings_.getSetting(SettingsId::MAX_CONCURRENT_STREAMS,
std::numeric_limits<int32_t>::max())) {
streamError(folly::to<string>("Exceeded max_concurrent_streams"),
ErrorCode::REFUSED_STREAM, true);
return ErrorCode::NO_ERROR;
}
}
return folly::Optional<ErrorCode>();
}
void HTTP2Codec::onHeader(const folly::fbstring& name,
const folly::fbstring& value) {
if (decodeInfo_.onHeader(name, value)) {
if (name == "user-agent" && userAgent_.empty()) {
userAgent_ = value.toStdString();
}
} else {
VLOG(4) << "dir=" << uint32_t(transportDirection_) <<
decodeInfo_.parsingError << " codec=" << headerCodec_;
}
}
void HTTP2Codec::onHeadersComplete(HTTPHeaderSize decodedSize,
bool /*acknowledge*/) {
decodeInfo_.onHeadersComplete(decodedSize);
decodeInfo_.msg->setAdvancedProtocolString(http2::kProtocolString);
HTTPMessage* msg = decodeInfo_.msg.get();
HTTPRequestVerifier& verifier = decodeInfo_.verifier;
if ((transportDirection_ == TransportDirection::DOWNSTREAM) &&
verifier.hasUpgradeProtocol() &&
(*msg->getUpgradeProtocol() == headers::kWebsocketString) &&
msg->getMethod() == HTTPMethod::CONNECT) {
msg->setIngressWebsocketUpgrade();
ingressWebsocketUpgrade_ = true;
} else {
auto it = upgradedStreams_.find(curHeader_.stream);
if (it != upgradedStreams_.end()) {
upgradedStreams_.erase(curHeader_.stream);
// a websocket upgrade was sent on this stream.
if (msg->getStatusCode() != 200) {
decodeInfo_.parsingError =
folly::to<string>("Invalid response code to a websocket upgrade: ",
msg->getStatusCode());
return;
}
msg->setIngressWebsocketUpgrade();
}
}
}
void HTTP2Codec::onDecodeError(HPACK::DecodeError decodeError) {
decodeInfo_.decodeError = decodeError;
}
ErrorCode HTTP2Codec::parsePriority(Cursor& cursor) {
VLOG(4) << "parsing PRIORITY frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
http2::PriorityUpdate pri;
auto err = http2::parsePriority(cursor, curHeader_, pri);
RETURN_IF_ERROR(err);
if (curHeader_.stream == pri.streamDependency) {
streamError(folly::to<string>("Circular dependency for txn=",
curHeader_.stream),
ErrorCode::PROTOCOL_ERROR, false);
return ErrorCode::NO_ERROR;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onPriority, "onPriority",
curHeader_.stream,
std::make_tuple(pri.streamDependency,
pri.exclusive,
pri.weight));
return ErrorCode::NO_ERROR;
}
size_t HTTP2Codec::addPriorityNodes(
PriorityQueue& queue,
folly::IOBufQueue& writeBuf,
uint8_t maxLevel) {
HTTPCodec::StreamID parent = 0;
size_t bytes = 0;
while (maxLevel--) {
auto id = createStream();
virtualPriorityNodes_.push_back(id);
queue.addPriorityNode(id, parent);
bytes += generatePriority(writeBuf, id, std::make_tuple(parent, false, 0));
parent = id;
}
return bytes;
}
ErrorCode HTTP2Codec::parseRstStream(Cursor& cursor) {
// rst for stream in idle state - protocol error
VLOG(4) << "parsing RST_STREAM frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
upgradedStreams_.erase(curHeader_.stream);
ErrorCode statusCode = ErrorCode::NO_ERROR;
auto err = http2::parseRstStream(cursor, curHeader_, statusCode);
RETURN_IF_ERROR(err);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: RST_STREAM with code=", getErrorCodeString(statusCode),
" for streamID=", curHeader_.stream, " user-agent=", userAgent_);
VLOG(2) << goawayErrorMessage_;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onAbort, "onAbort",
curHeader_.stream, statusCode);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseSettings(Cursor& cursor) {
VLOG(4) << "parsing SETTINGS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
std::deque<SettingPair> settings;
auto err = http2::parseSettings(cursor, curHeader_, settings);
RETURN_IF_ERROR(err);
if (curHeader_.flags & http2::ACK) {
handleSettingsAck();
return ErrorCode::NO_ERROR;
}
return handleSettings(settings);
}
void HTTP2Codec::handleSettingsAck() {
if (pendingTableMaxSize_) {
headerCodec_.setDecoderHeaderTableMaxSize(*pendingTableMaxSize_);
pendingTableMaxSize_ = folly::none;
}
if (callback_) {
callback_->onSettingsAck();
}
}
ErrorCode HTTP2Codec::handleSettings(const std::deque<SettingPair>& settings) {
SettingsList settingsList;
for (auto& setting: settings) {
switch (setting.first) {
case SettingsId::HEADER_TABLE_SIZE:
{
uint32_t tableSize = setting.second;
if (setting.second > http2::kMaxHeaderTableSize) {
VLOG(2) << "Limiting table size from " << tableSize << " to " <<
http2::kMaxHeaderTableSize;
tableSize = http2::kMaxHeaderTableSize;
}
headerCodec_.setEncoderHeaderTableSize(tableSize);
}
break;
case SettingsId::ENABLE_PUSH:
if ((setting.second != 0 && setting.second != 1) ||
(setting.second == 1 &&
transportDirection_ == TransportDirection::UPSTREAM)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_PUSH invalid setting=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
break;
case SettingsId::INITIAL_WINDOW_SIZE:
if (setting.second > http2::kMaxWindowUpdateSize) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: INITIAL_WINDOW_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_FRAME_SIZE:
if (setting.second < http2::kMaxFramePayloadLengthMin ||
setting.second > http2::kMaxFramePayloadLength) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: MAX_FRAME_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
ingressSettings_.setSetting(SettingsId::MAX_FRAME_SIZE, setting.second);
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
break;
case SettingsId::ENABLE_EX_HEADERS:
{
auto ptr = egressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS);
if (ptr && ptr->value > 0) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " got ENABLE_EX_HEADERS=" << setting.second;
if (setting.second != 0 && setting.second != 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid ENABLE_EX_HEADERS=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
} else {
// egress ENABLE_EX_HEADERS is disabled, consider the ingress
// ENABLE_EX_HEADERS as unknown setting, and ignore it.
continue;
}
}
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.second > 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_CONNECT_PROTOCOL invalid number=",
setting.second, " for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
case SettingsId::SETTINGS_HTTP_CERT_AUTH:
break;
default:
continue; // ignore unknown setting
}
ingressSettings_.setSetting(setting.first, setting.second);
settingsList.push_back(*ingressSettings_.getSetting(setting.first));
}
if (callback_) {
callback_->onSettings(settingsList);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parsePushPromise(Cursor& cursor) {
// stream id must be idle - protocol error
// assoc-stream-id=closed/unknown - protocol error, unless rst_stream sent
/*
* What does "must handle" mean in the following context? I have to
* accept this as a valid pushed resource?
However, an endpoint that has sent RST_STREAM on the associated
stream MUST handle PUSH_PROMISE frames that might have been
created before the RST_STREAM frame is received and processed.
*/
if (transportDirection_ != TransportDirection::UPSTREAM) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on DOWNSTREAM codec");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (egressSettings_.getSetting(SettingsId::ENABLE_PUSH, -1) != 1) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on codec with push disabled");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
VLOG(4) << "parsing PUSH_PROMISE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t promisedStream;
std::unique_ptr<IOBuf> headerBlockFragment;
auto err = http2::parsePushPromise(cursor, curHeader_, promisedStream,
headerBlockFragment);
RETURN_IF_ERROR(err);
RETURN_IF_ERROR(checkNewStream(promisedStream, false /* trailersAllowed */));
err = parseHeadersImpl(cursor, std::move(headerBlockFragment), folly::none,
promisedStream, folly::none);
return err;
}
ErrorCode HTTP2Codec::parsePing(Cursor& cursor) {
VLOG(4) << "parsing PING frame length=" << curHeader_.length;
uint64_t opaqueData = 0;
auto err = http2::parsePing(cursor, curHeader_, opaqueData);
RETURN_IF_ERROR(err);
if (callback_) {
if (curHeader_.flags & http2::ACK) {
callback_->onPingReply(opaqueData);
} else {
callback_->onPingRequest(opaqueData);
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseGoaway(Cursor& cursor) {
VLOG(4) << "parsing GOAWAY frame length=" << curHeader_.length;
uint32_t lastGoodStream = 0;
ErrorCode statusCode = ErrorCode::NO_ERROR;
std::unique_ptr<IOBuf> debugData;
auto err = http2::parseGoaway(cursor, curHeader_, lastGoodStream, statusCode,
debugData);
if (statusCode != ErrorCode::NO_ERROR) {
VLOG(2) << "Goaway error statusCode=" << getErrorCodeString(statusCode)
<< " lastStream=" << lastGoodStream
<< " user-agent=" << userAgent_ << " debugData=" <<
((debugData) ? string((char*)debugData->data(), debugData->length()):
empty_string);
}
RETURN_IF_ERROR(err);
if (lastGoodStream < ingressGoawayAck_) {
ingressGoawayAck_ = lastGoodStream;
// Drain all streams <= lastGoodStream
// and abort streams > lastGoodStream
if (callback_) {
callback_->onGoaway(lastGoodStream, statusCode, std::move(debugData));
}
} else {
LOG(WARNING) << "Received multiple GOAWAY with increasing ack";
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseWindowUpdate(Cursor& cursor) {
VLOG(4) << "parsing WINDOW_UPDATE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t delta = 0;
auto err = http2::parseWindowUpdate(cursor, curHeader_, delta);
RETURN_IF_ERROR(err);
if (delta == 0) {
VLOG(4) << "Invalid 0 length delta for stream=" << curHeader_.stream;
if (curHeader_.stream == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid/0 length delta for streamID=",
curHeader_.stream);
return ErrorCode::PROTOCOL_ERROR;
} else {
// Parsing a zero delta window update should cause a protocol error
// and send a rst stream
goawayErrorMessage_ = folly::to<string>(
"parseWindowUpdate Invalid 0 length");
VLOG(4) << goawayErrorMessage_;
streamError(folly::to<std::string>("streamID=", curHeader_.stream,
" with HTTP2Codec stream error: ",
"window update delta=", delta),
ErrorCode::PROTOCOL_ERROR);
return ErrorCode::PROTOCOL_ERROR;
}
}
// if window exceeds 2^31-1, connection/stream error flow control error
// must be checked in session/txn
deliverCallbackIfAllowed(&HTTPCodec::Callback::onWindowUpdate,
"onWindowUpdate", curHeader_.stream, delta);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificateRequest(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE_REQUEST frame length=" << curHeader_.length;
uint16_t requestId = 0;
std::unique_ptr<IOBuf> authRequest;
auto err = http2::parseCertificateRequest(
cursor, curHeader_, requestId, authRequest);
RETURN_IF_ERROR(err);
if (callback_) {
callback_->onCertificateRequest(requestId, std::move(authRequest));
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificate(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE frame length=" << curHeader_.length;
uint16_t certId = 0;
std::unique_ptr<IOBuf> authData;
auto err = http2::parseCertificate(cursor, curHeader_, certId, authData);
RETURN_IF_ERROR(err);
if (curAuthenticatorBlock_.empty()) {
curCertId_ = certId;
} else if (certId != curCertId_) {
// Received CERTIFICATE frame with different Cert-ID.
return ErrorCode::PROTOCOL_ERROR;
}
curAuthenticatorBlock_.append(std::move(authData));
if (curAuthenticatorBlock_.chainLength() > http2::kMaxAuthenticatorBufSize) {
// Received excessively long authenticator.
return ErrorCode::PROTOCOL_ERROR;
}
if (!(curHeader_.flags & http2::TO_BE_CONTINUED)) {
auto authenticator = curAuthenticatorBlock_.move();
if (callback_) {
callback_->onCertificate(certId, std::move(authenticator));
} else {
curAuthenticatorBlock_.clear();
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {
if (streamId == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: received streamID=", streamId,
" as invalid new stream for lastStreamID_=", lastStreamID_);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);
if (parsingDownstreamTrailers_) {
VLOG(4) << "Parsing downstream trailers streamId=" << streamId;
}
if (sessionClosing_ != ClosingState::CLOSED) {
lastStreamID_ = streamId;
}
if (isInitiatedStream(streamId)) {
// this stream should be initiated by us, not by peer
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid new stream received with streamID=", streamId);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
} else {
return ErrorCode::NO_ERROR;
}
}
size_t HTTP2Codec::generateConnectionPreface(folly::IOBufQueue& writeBuf) {
if (transportDirection_ == TransportDirection::UPSTREAM) {
VLOG(4) << "generating connection preface";
writeBuf.append(http2::kConnectionPreface);
return http2::kConnectionPreface.length();
}
return 0;
}
bool HTTP2Codec::onIngressUpgradeMessage(const HTTPMessage& msg) {
if (!HTTPParallelCodec::onIngressUpgradeMessage(msg)) {
return false;
}
if (msg.getHeaders().getNumberOfValues(http2::kProtocolSettingsHeader) != 1) {
VLOG(4) << __func__ << " with no HTTP2-Settings";
return false;
}
const auto& settingsHeader = msg.getHeaders().getSingleOrEmpty(
http2::kProtocolSettingsHeader);
if (settingsHeader.empty()) {
return true;
}
auto decoded = base64url_decode(settingsHeader);
// Must be well formed Base64Url and not too large
if (decoded.empty() || decoded.length() > http2::kMaxFramePayloadLength) {
VLOG(4) << __func__ << " failed to decode HTTP2-Settings";
return false;
}
std::unique_ptr<IOBuf> decodedBuf = IOBuf::wrapBuffer(decoded.data(),
decoded.length());
IOBufQueue settingsQueue{IOBufQueue::cacheChainLength()};
settingsQueue.append(std::move(decodedBuf));
Cursor c(settingsQueue.front());
std::deque<SettingPair> settings;
// downcast is ok because of above length check
http2::FrameHeader frameHeader{
(uint32_t)settingsQueue.chainLength(), 0, http2::FrameType::SETTINGS, 0, 0};
auto err = http2::parseSettings(c, frameHeader, settings);
if (err != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " bad settings frame";
return false;
}
if (handleSettings(settings) != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " handleSettings failed";
return false;
}
return true;
}
void HTTP2Codec::generateHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generatePushPromise(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
StreamID assocStream,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
assocStream,
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generateExHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const HTTPCodec::ExAttributes& exAttributes,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
exAttributes,
eom,
size);
}
void HTTP2Codec::generateHeaderImpl(
folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const folly::Optional<StreamID>& assocStream,
const folly::Optional<HTTPCodec::ExAttributes>& exAttributes,
bool eom,
HTTPHeaderSize* size) {
if (assocStream) {
CHECK(!exAttributes);
VLOG(4) << "generating PUSH_PROMISE for stream=" << stream;
} else if (exAttributes) {
CHECK(!assocStream);
VLOG(4) << "generating ExHEADERS for stream=" << stream
<< " with control stream=" << exAttributes->controlStream
<< " unidirectional=" << exAttributes->unidirectional;
} else {
VLOG(4) << "generating HEADERS for stream=" << stream;
}
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing HEADERS/PROMISE for stream=" << stream <<
" ingressGoawayAck_=" << ingressGoawayAck_;
if (size) {
size->uncompressed = 0;
size->compressed = 0;
}
return;
}
if (msg.isRequest()) {
DCHECK(transportDirection_ == TransportDirection::UPSTREAM ||
assocStream || exAttributes);
if (msg.isEgressWebsocketUpgrade()) {
upgradedStreams_.insert(stream);
}
} else {
DCHECK(transportDirection_ == TransportDirection::DOWNSTREAM ||
exAttributes);
}
std::vector<std::string> temps;
auto allHeaders = CodecUtil::prepareMessageForCompression(msg, temps);
auto out = encodeHeaders(msg.getHeaders(), allHeaders, size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto res = msg.getHTTP2Priority();
auto remainingFrameSize = maxFrameSize;
if (res) {
pri = http2::PriorityUpdate{std::get<0>(*res), std::get<1>(*res),
std::get<2>(*res)};
DCHECK_GE(remainingFrameSize, http2::kFramePrioritySize)
<< "no enough space for priority? frameHeadroom=" << remainingFrameSize;
remainingFrameSize -= http2::kFramePrioritySize;
}
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
if (assocStream) {
DCHECK_EQ(transportDirection_, TransportDirection::DOWNSTREAM);
DCHECK(!eom);
generateHeaderCallbackWrapper(stream, http2::FrameType::PUSH_PROMISE,
http2::writePushPromise(writeBuf,
*assocStream,
stream,
std::move(chunk),
http2::kNoPadding,
endHeaders));
} else if (exAttributes) {
generateHeaderCallbackWrapper(
stream,
http2::FrameType::EX_HEADERS,
http2::writeExHeaders(writeBuf,
std::move(chunk),
stream,
*exAttributes,
pri,
http2::kNoPadding,
eom,
endHeaders));
} else {
generateHeaderCallbackWrapper(stream, http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
eom,
endHeaders));
}
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
}
void HTTP2Codec::generateContinuation(folly::IOBufQueue& writeBuf,
folly::IOBufQueue& queue,
StreamID stream,
size_t maxFrameSize) {
bool endHeaders = false;
while (!endHeaders) {
auto chunk = queue.split(std::min(maxFrameSize, queue.chainLength()));
endHeaders = (queue.chainLength() == 0);
VLOG(4) << "generating CONTINUATION for stream=" << stream;
generateHeaderCallbackWrapper(
stream,
http2::FrameType::CONTINUATION,
http2::writeContinuation(
writeBuf, stream, endHeaders, std::move(chunk)));
}
}
std::unique_ptr<folly::IOBuf> HTTP2Codec::encodeHeaders(
const HTTPHeaders& headers,
std::vector<compress::Header>& allHeaders,
HTTPHeaderSize* size) {
headerCodec_.setEncodeHeadroom(http2::kFrameHeaderSize +
http2::kFrameHeadersBaseMaxSize);
auto out = headerCodec_.encode(allHeaders);
if (size) {
*size = headerCodec_.getEncodedSize();
}
if (headerCodec_.getEncodedSize().uncompressed >
ingressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE,
std::numeric_limits<uint32_t>::max())) {
// The remote side told us they don't want headers this large...
// but this function has no mechanism to fail
string serializedHeaders;
headers.forEach(
[&serializedHeaders] (const string& name, const string& value) {
serializedHeaders = folly::to<string>(serializedHeaders, "\\n", name,
":", value);
});
LOG(ERROR) << "generating HEADERS frame larger than peer maximum nHeaders="
<< headers.size() << " all headers="
<< serializedHeaders;
}
return out;
}
size_t HTTP2Codec::generateHeaderCallbackWrapper(StreamID stream,
http2::FrameType type,
size_t length) {
if (callback_) {
callback_->onGenerateFrameHeader(stream,
static_cast<uint8_t>(type),
length);
}
return length;
}
size_t HTTP2Codec::generateBody(folly::IOBufQueue& writeBuf,
StreamID stream,
std::unique_ptr<folly::IOBuf> chain,
folly::Optional<uint8_t> padding,
bool eom) {
// todo: generate random padding for everything?
size_t written = 0;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing DATA for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(chain));
size_t maxFrameSize = maxSendFrameSize();
while (queue.chainLength() > maxFrameSize) {
auto chunk = queue.split(maxFrameSize);
written += generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
std::move(chunk),
stream,
padding,
false,
reuseIOBufHeadroomForData_));
}
return written + generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
queue.move(),
stream,
padding,
eom,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateChunkHeader(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/,
size_t /*length*/) {
// HTTP/2 has no chunk headers
return 0;
}
size_t HTTP2Codec::generateChunkTerminator(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/) {
// HTTP/2 has no chunk terminators
return 0;
}
size_t HTTP2Codec::generateTrailers(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPHeaders& trailers) {
std::vector<compress::Header> allHeaders;
CodecUtil::appendHeaders(trailers, allHeaders, HTTP_HEADER_NONE);
HTTPHeaderSize size;
auto out = encodeHeaders(trailers, allHeaders, &size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto remainingFrameSize = maxFrameSize;
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
generateHeaderCallbackWrapper(stream,
http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
true /*eom*/,
endHeaders));
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
return size.compressed;
}
size_t HTTP2Codec::generateEOM(folly::IOBufQueue& writeBuf,
StreamID stream) {
VLOG(4) << "sending EOM for stream=" << stream;
upgradedStreams_.erase(stream);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed EOM for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
nullptr,
stream,
http2::kNoPadding,
true,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateRstStream(folly::IOBufQueue& writeBuf,
StreamID stream,
ErrorCode statusCode) {
VLOG(4) << "sending RST_STREAM for stream=" << stream
<< " with code=" << getErrorCodeString(statusCode);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed RST_STREAM for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
// Suppress any EOM callback for the current frame.
if (stream == curHeader_.stream) {
curHeader_.flags &= ~http2::END_STREAM;
pendingEndStreamHandling_ = false;
ingressWebsocketUpgrade_ = false;
}
upgradedStreams_.erase(stream);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending RST_STREAM with code=" << getErrorCodeString(statusCode)
<< " for stream=" << stream << " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToReset(statusCode);
return generateHeaderCallbackWrapper(stream, http2::FrameType::RST_STREAM,
http2::writeRstStream(writeBuf, stream, code));
}
size_t HTTP2Codec::generateGoaway(folly::IOBufQueue& writeBuf,
StreamID lastStream,
ErrorCode statusCode,
std::unique_ptr<folly::IOBuf> debugData) {
DCHECK_LE(lastStream, egressGoawayAck_) << "Cannot increase last good stream";
egressGoawayAck_ = lastStream;
if (sessionClosing_ == ClosingState::CLOSED) {
VLOG(4) << "Not sending GOAWAY for closed session";
return 0;
}
switch (sessionClosing_) {
case ClosingState::OPEN:
case ClosingState::OPEN_WITH_GRACEFUL_DRAIN_ENABLED:
if (lastStream == std::numeric_limits<int32_t>::max() &&
statusCode == ErrorCode::NO_ERROR) {
sessionClosing_ = ClosingState::FIRST_GOAWAY_SENT;
} else {
// The user of this codec decided not to do the double goaway
// drain, or this is not a graceful shutdown
sessionClosing_ = ClosingState::CLOSED;
}
break;
case ClosingState::FIRST_GOAWAY_SENT:
sessionClosing_ = ClosingState::CLOSED;
break;
case ClosingState::CLOSING:
case ClosingState::CLOSED:
LOG(FATAL) << "unreachable";
}
VLOG(4) << "Sending GOAWAY with last acknowledged stream="
<< lastStream << " with code=" << getErrorCodeString(statusCode);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending GOAWAY with last acknowledged stream=" << lastStream
<< " with code=" << getErrorCodeString(statusCode)
<< " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToGoaway(statusCode);
return generateHeaderCallbackWrapper(
0,
http2::FrameType::GOAWAY,
http2::writeGoaway(writeBuf,
lastStream,
code,
std::move(debugData)));
}
size_t HTTP2Codec::generatePingRequest(folly::IOBufQueue& writeBuf) {
// should probably let the caller specify when integrating with session
// we know HTTPSession sets up events to track ping latency
uint64_t opaqueData = folly::Random::rand64();
VLOG(4) << "Generating ping request with opaqueData=" << opaqueData;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, opaqueData, false /* no ack */));
}
size_t HTTP2Codec::generatePingReply(folly::IOBufQueue& writeBuf,
uint64_t uniqueID) {
VLOG(4) << "Generating ping reply with opaqueData=" << uniqueID;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, uniqueID, true /* ack */));
}
size_t HTTP2Codec::generateSettings(folly::IOBufQueue& writeBuf) {
std::deque<SettingPair> settings;
for (auto& setting: egressSettings_.getAllSettings()) {
switch (setting.id) {
case SettingsId::HEADER_TABLE_SIZE:
if (pendingTableMaxSize_) {
LOG(ERROR) << "Can't have more than one settings in flight, skipping";
continue;
} else {
pendingTableMaxSize_ = setting.value;
}
break;
case SettingsId::ENABLE_PUSH:
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
// HTTP/2 spec says downstream must not send this flag
// HTTP2Codec uses it to determine if push features are enabled
continue;
} else {
CHECK(setting.value == 0 || setting.value == 1);
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
case SettingsId::INITIAL_WINDOW_SIZE:
case SettingsId::MAX_FRAME_SIZE:
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
headerCodec_.setMaxUncompressed(setting.value);
break;
case SettingsId::ENABLE_EX_HEADERS:
CHECK(setting.value == 0 || setting.value == 1);
if (setting.value == 0) {
continue; // just skip the experimental setting if disabled
} else {
VLOG(4) << "generating ENABLE_EX_HEADERS=" << setting.value;
}
break;
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.value == 0) {
continue;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
default:
LOG(ERROR) << "ignore unknown settingsId="
<< std::underlying_type<SettingsId>::type(setting.id)
<< " value=" << setting.value;
continue;
}
settings.push_back(SettingPair(setting.id, setting.value));
}
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating " << (unsigned)settings.size() << " settings";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettings(writeBuf, settings));
}
void HTTP2Codec::requestUpgrade(HTTPMessage& request) {
static folly::ThreadLocalPtr<HTTP2Codec> defaultCodec;
if (!defaultCodec.get()) {
defaultCodec.reset(new HTTP2Codec(TransportDirection::UPSTREAM));
}
auto& headers = request.getHeaders();
headers.set(HTTP_HEADER_UPGRADE, http2::kProtocolCleartextString);
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION, "Upgrade", false)) {
headers.add(HTTP_HEADER_CONNECTION, "Upgrade");
}
IOBufQueue writeBuf{IOBufQueue::cacheChainLength()};
defaultCodec->generateSettings(writeBuf);
// fake an ack since defaultCodec gets reused
defaultCodec->handleSettingsAck();
writeBuf.trimStart(http2::kFrameHeaderSize);
auto buf = writeBuf.move();
buf->coalesce();
headers.set(http2::kProtocolSettingsHeader,
base64url_encode(folly::ByteRange(buf->data(), buf->length())));
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(),
false)) {
headers.add(HTTP_HEADER_CONNECTION, http2::kProtocolSettingsHeader);
}
}
size_t HTTP2Codec::generateSettingsAck(folly::IOBufQueue& writeBuf) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating settings ack";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettingsAck(writeBuf));
}
size_t HTTP2Codec::generateWindowUpdate(folly::IOBufQueue& writeBuf,
StreamID stream,
uint32_t delta) {
VLOG(4) << "generating window update for stream=" << stream
<< ": Processed " << delta << " bytes";
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed WINDOW_UPDATE for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(stream, http2::FrameType::WINDOW_UPDATE,
http2::writeWindowUpdate(writeBuf, stream, delta));
}
size_t HTTP2Codec::generatePriority(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage::HTTPPriority& pri) {
VLOG(4) << "generating priority for stream=" << stream;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed PRIORITY for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::PRIORITY,
http2::writePriority(writeBuf, stream,
{std::get<0>(pri),
std::get<1>(pri),
std::get<2>(pri)}));
}
size_t HTTP2Codec::generateCertificateRequest(
folly::IOBufQueue& writeBuf,
uint16_t requestId,
std::unique_ptr<folly::IOBuf> certificateRequestData) {
VLOG(4) << "generating CERTIFICATE_REQUEST with Request-ID=" << requestId;
return http2::writeCertificateRequest(
writeBuf, requestId, std::move(certificateRequestData));
}
size_t HTTP2Codec::generateCertificate(folly::IOBufQueue& writeBuf,
uint16_t certId,
std::unique_ptr<folly::IOBuf> certData) {
size_t written = 0;
VLOG(4) << "sending CERTIFICATE with Cert-ID=" << certId << "for stream=0";
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(certData));
// The maximum size of an autenticator fragment, combined with the Cert-ID can
// not exceed the maximal allowable size of a sent frame.
size_t maxChunkSize = maxSendFrameSize() - sizeof(certId);
while (queue.chainLength() > maxChunkSize) {
auto chunk = queue.splitAtMost(maxChunkSize);
written +=
http2::writeCertificate(writeBuf, certId, std::move(chunk), true);
}
return written +
http2::writeCertificate(writeBuf, certId, queue.move(), false);
}
bool HTTP2Codec::checkConnectionError(ErrorCode err, const folly::IOBuf* buf) {
if (err != ErrorCode::NO_ERROR) {
LOG(ERROR) << "Connection error " << getErrorCodeString(err)
<< " with ingress=";
VLOG(3) << IOBufPrinter::printHexFolly(buf, true);
if (callback_) {
std::string errorDescription = goawayErrorMessage_.empty() ?
"Connection error" : goawayErrorMessage_;
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
errorDescription);
ex.setCodecStatusCode(err);
callback_->onError(0, ex, false);
}
return true;
}
return false;
}
void HTTP2Codec::streamError(const std::string& msg, ErrorCode code,
bool newTxn) {
HTTPException error(HTTPException::Direction::INGRESS_AND_EGRESS,
msg);
error.setCodecStatusCode(code);
if (callback_) {
callback_->onError(curHeader_.stream, error, newTxn);
}
}
HTTPCodec::StreamID
HTTP2Codec::mapPriorityToDependency(uint8_t priority) const {
// If the priority is out of the maximum index of virtual nodes array, we
// return the lowest level virtual node as a punishment of not setting
// priority correctly.
return virtualPriorityNodes_.empty()
? 0
: virtualPriorityNodes_[
std::min(priority, uint8_t(virtualPriorityNodes_.size() - 1))];
}
bool HTTP2Codec::parsingTrailers() const {
// HEADERS frame is used for request/response headers and trailers.
// Per spec, specific role of HEADERS frame is determined by it's postion
// within the stream. We don't keep full stream state in this codec,
// thus using heuristics to distinguish between headers/trailers.
// For DOWNSTREAM case, request headers HEADERS frame would be creating
// new stream, thus HEADERS on existing stream ID are considered trailers
// (see checkNewStream).
// For UPSTREAM case, response headers are required to have status code,
// thus if no status code we consider that trailers.
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::CONTINUATION) {
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
return parsingDownstreamTrailers_;
} else {
return !decodeInfo_.hasStatus();
}
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_600_0 |
crossvul-cpp_data_bad_3201_1 | /*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2014 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#include "abstractwebapplication.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QNetworkCookie>
#include <QTemporaryFile>
#include <QTimer>
#include "base/preferences.h"
#include "base/utils/fs.h"
#include "base/utils/random.h"
#include "websessiondata.h"
// UnbanTimer
class UnbanTimer: public QTimer
{
public:
UnbanTimer(const QHostAddress& peer_ip, QObject *parent)
: QTimer(parent), m_peerIp(peer_ip)
{
setSingleShot(true);
setInterval(BAN_TIME);
}
inline const QHostAddress& peerIp() const { return m_peerIp; }
private:
QHostAddress m_peerIp;
};
// WebSession
struct WebSession
{
const QString id;
uint timestamp;
WebSessionData data;
WebSession(const QString& id)
: id(id)
{
updateTimestamp();
}
void updateTimestamp()
{
timestamp = QDateTime::currentDateTime().toTime_t();
}
};
// AbstractWebApplication
AbstractWebApplication::AbstractWebApplication(QObject *parent)
: Http::ResponseBuilder(parent)
, session_(0)
{
QTimer *timer = new QTimer(this);
timer->setInterval(60000); // 1 min.
connect(timer, SIGNAL(timeout()), SLOT(removeInactiveSessions()));
}
AbstractWebApplication::~AbstractWebApplication()
{
// cleanup sessions data
qDeleteAll(sessions_);
}
Http::Response AbstractWebApplication::processRequest(const Http::Request &request, const Http::Environment &env)
{
session_ = 0;
request_ = request;
env_ = env;
clear(); // clear response
sessionInitialize();
if (!sessionActive() && !isAuthNeeded())
sessionStart();
if (isBanned()) {
status(403, "Forbidden");
print(QObject::tr("Your IP address has been banned after too many failed authentication attempts."), Http::CONTENT_TYPE_TXT);
}
else {
processRequest();
}
return response();
}
void AbstractWebApplication::UnbanTimerEvent()
{
UnbanTimer* ubantimer = static_cast<UnbanTimer*>(sender());
qDebug("Ban period has expired for %s", qPrintable(ubantimer->peerIp().toString()));
clientFailedAttempts_.remove(ubantimer->peerIp());
ubantimer->deleteLater();
}
void AbstractWebApplication::removeInactiveSessions()
{
const uint now = QDateTime::currentDateTime().toTime_t();
foreach (const QString &id, sessions_.keys()) {
if ((now - sessions_[id]->timestamp) > INACTIVE_TIME)
delete sessions_.take(id);
}
}
bool AbstractWebApplication::sessionInitialize()
{
static const QString SID_START = QLatin1String(C_SID) + QLatin1String("=");
if (session_ == 0)
{
QString cookie = request_.headers.value("cookie");
//qDebug() << Q_FUNC_INFO << "cookie: " << cookie;
QString sessionId;
int pos = cookie.indexOf(SID_START);
if (pos >= 0) {
pos += SID_START.length();
int end = cookie.indexOf(QRegExp("[,;]"), pos);
sessionId = cookie.mid(pos, end >= 0 ? end - pos : end);
}
// TODO: Additional session check
if (!sessionId.isNull()) {
if (sessions_.contains(sessionId)) {
session_ = sessions_[sessionId];
session_->updateTimestamp();
return true;
}
else {
qDebug() << Q_FUNC_INFO << "session does not exist!";
}
}
}
return false;
}
bool AbstractWebApplication::readFile(const QString& path, QByteArray &data, QString &type)
{
QString ext = "";
int index = path.lastIndexOf('.') + 1;
if (index > 0)
ext = path.mid(index);
// find translated file in cache
if (translatedFiles_.contains(path)) {
data = translatedFiles_[path];
}
else {
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
qDebug("File %s was not found!", qPrintable(path));
return false;
}
data = file.readAll();
file.close();
// Translate the file
if ((ext == "html") || ((ext == "js") && !path.endsWith("excanvas-compressed.js"))) {
QString dataStr = QString::fromUtf8(data.constData());
translateDocument(dataStr);
if (path.endsWith("about.html") || path.endsWith("index.html") || path.endsWith("client.js"))
dataStr.replace("${VERSION}", VERSION);
data = dataStr.toUtf8();
translatedFiles_[path] = data; // cashing translated file
}
}
type = CONTENT_TYPE_BY_EXT[ext];
return true;
}
WebSessionData *AbstractWebApplication::session()
{
Q_ASSERT(session_ != 0);
return &session_->data;
}
QString AbstractWebApplication::generateSid()
{
QString sid;
do {
const size_t size = 6;
quint32 tmp[size];
for (size_t i = 0; i < size; ++i)
tmp[i] = Utils::Random::rand();
sid = QByteArray::fromRawData(reinterpret_cast<const char *>(tmp), sizeof(quint32) * size).toBase64();
}
while (sessions_.contains(sid));
return sid;
}
void AbstractWebApplication::translateDocument(QString& data)
{
const QRegExp regex("QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR(\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\])?");
const QRegExp mnemonic("\\(?&([a-zA-Z]?\\))?");
const std::string contexts[] = {
"TransferListFiltersWidget", "TransferListWidget", "PropertiesWidget",
"HttpServer", "confirmDeletionDlg", "TrackerList", "TorrentFilesModel",
"options_imp", "Preferences", "TrackersAdditionDlg", "ScanFoldersModel",
"PropTabBar", "TorrentModel", "downloadFromURL", "MainWindow", "misc",
"StatusBar", "AboutDlg", "about", "PeerListWidget", "StatusFiltersWidget",
"CategoryFiltersList", "TransferListDelegate"
};
const size_t context_count = sizeof(contexts) / sizeof(contexts[0]);
int i = 0;
bool found = true;
const QString locale = Preferences::instance()->getLocale();
bool isTranslationNeeded = !locale.startsWith("en") || locale.startsWith("en_AU") || locale.startsWith("en_GB");
while(i < data.size() && found) {
i = regex.indexIn(data, i);
if (i >= 0) {
//qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data());
QByteArray word = regex.cap(1).toUtf8();
QString translation = word;
if (isTranslationNeeded) {
QString context = regex.cap(4);
if (context.length() > 0) {
#ifndef QBT_USES_QT5
translation = qApp->translate(context.toUtf8().constData(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1);
#else
translation = qApp->translate(context.toUtf8().constData(), word.constData(), 0, 1);
#endif
}
else {
size_t context_index = 0;
while ((context_index < context_count) && (translation == word)) {
#ifndef QBT_USES_QT5
translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1);
#else
translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, 1);
#endif
++context_index;
}
}
}
// Remove keyboard shortcuts
translation.replace(mnemonic, "");
// Use HTML code for quotes to prevent issues with JS
translation.replace("'", "'");
translation.replace("\"", """);
data.replace(i, regex.matchedLength(), translation);
i += translation.length();
}
else {
found = false; // no more translatable strings
}
}
}
bool AbstractWebApplication::isBanned() const
{
return clientFailedAttempts_.value(env_.clientAddress, 0) >= MAX_AUTH_FAILED_ATTEMPTS;
}
int AbstractWebApplication::failedAttempts() const
{
return clientFailedAttempts_.value(env_.clientAddress, 0);
}
void AbstractWebApplication::resetFailedAttempts()
{
clientFailedAttempts_.remove(env_.clientAddress);
}
void AbstractWebApplication::increaseFailedAttempts()
{
const int nb_fail = clientFailedAttempts_.value(env_.clientAddress, 0) + 1;
clientFailedAttempts_[env_.clientAddress] = nb_fail;
if (nb_fail == MAX_AUTH_FAILED_ATTEMPTS) {
// Max number of failed attempts reached
// Start ban period
UnbanTimer* ubantimer = new UnbanTimer(env_.clientAddress, this);
connect(ubantimer, SIGNAL(timeout()), SLOT(UnbanTimerEvent()));
ubantimer->start();
}
}
bool AbstractWebApplication::isAuthNeeded()
{
return (env_.clientAddress != QHostAddress::LocalHost
&& env_.clientAddress != QHostAddress::LocalHostIPv6
&& env_.clientAddress != QHostAddress("::ffff:127.0.0.1"))
|| Preferences::instance()->isWebUiLocalAuthEnabled();
}
void AbstractWebApplication::printFile(const QString& path)
{
QByteArray data;
QString type;
if (!readFile(path, data, type)) {
status(404, "Not Found");
return;
}
print(data, type);
}
bool AbstractWebApplication::sessionStart()
{
if (session_ == 0) {
session_ = new WebSession(generateSid());
sessions_[session_->id] = session_;
QNetworkCookie cookie(C_SID, session_->id.toUtf8());
cookie.setPath(QLatin1String("/"));
header(Http::HEADER_SET_COOKIE, cookie.toRawForm());
return true;
}
return false;
}
bool AbstractWebApplication::sessionEnd()
{
if ((session_ != 0) && (sessions_.contains(session_->id))) {
QNetworkCookie cookie(C_SID, session_->id.toUtf8());
cookie.setPath(QLatin1String("/"));
cookie.setExpirationDate(QDateTime::currentDateTime());
sessions_.remove(session_->id);
delete session_;
session_ = 0;
header(Http::HEADER_SET_COOKIE, cookie.toRawForm());
return true;
}
return false;
}
QString AbstractWebApplication::saveTmpFile(const QByteArray &data)
{
QTemporaryFile tmpfile(Utils::Fs::tempPath() + "XXXXXX.torrent");
tmpfile.setAutoRemove(false);
if (tmpfile.open()) {
tmpfile.write(data);
tmpfile.close();
return tmpfile.fileName();
}
qWarning() << "I/O Error: Could not create temporary file";
return QString();
}
QStringMap AbstractWebApplication::initializeContentTypeByExtMap()
{
QStringMap map;
map["htm"] = Http::CONTENT_TYPE_HTML;
map["html"] = Http::CONTENT_TYPE_HTML;
map["css"] = Http::CONTENT_TYPE_CSS;
map["gif"] = Http::CONTENT_TYPE_GIF;
map["png"] = Http::CONTENT_TYPE_PNG;
map["js"] = Http::CONTENT_TYPE_JS;
return map;
}
const QStringMap AbstractWebApplication::CONTENT_TYPE_BY_EXT = AbstractWebApplication::initializeContentTypeByExtMap();
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_3201_1 |
crossvul-cpp_data_bad_1376_4 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1376_4 |
crossvul-cpp_data_bad_592_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/server/upload.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/request-local.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/runtime/base/php-globals.h"
#include "hphp/runtime/ext/apc/ext_apc.h"
#include "hphp/util/logger.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/util/text-util.h"
#include "hphp/runtime/base/request-event-handler.h"
#include <folly/FileUtil.h>
using std::set;
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
static void destroy_uploaded_files();
struct Rfc1867Data final : RequestEventHandler {
std::set<std::string> rfc1867ProtectedVariables;
std::set<std::string> rfc1867UploadedFiles;
apc_rfc1867_data rfc1867ApcData;
int (*rfc1867Callback)(apc_rfc1867_data *rfc1867ApcData,
unsigned int event, void *event_data, void **extra);
void requestInit() override {
if (RuntimeOption::EnableUploadProgress) {
rfc1867Callback = apc_rfc1867_progress;
} else {
rfc1867Callback = nullptr;
}
}
void requestShutdown() override {
if (!rfc1867UploadedFiles.empty()) destroy_uploaded_files();
}
};
IMPLEMENT_STATIC_REQUEST_LOCAL(Rfc1867Data, s_rfc1867_data);
/*
* This product includes software developed by the Apache Group
* for use in the Apache HTTP server project (http://www.apache.org/).
*
*/
static void safe_php_register_variable(char *var, const Variant& val,
Array& track_vars_array,
bool override_protection);
#define FAILURE -1
/* The longest property name we use in an uploaded file array */
#define MAX_SIZE_OF_INDEX sizeof("[tmp_name]")
/* The longest anonymous name */
#define MAX_SIZE_ANONNAME 33
/* Errors */
#define UPLOAD_ERROR_OK 0 /* File upload successful */
#define UPLOAD_ERROR_A 1 /* Uploaded file exceeded upload_max_filesize */
#define UPLOAD_ERROR_B 2 /* Uploaded file exceeded MAX_FILE_SIZE */
#define UPLOAD_ERROR_C 3 /* Partially uploaded */
#define UPLOAD_ERROR_D 4 /* No file uploaded */
#define UPLOAD_ERROR_E 6 /* Missing /tmp or similar directory */
#define UPLOAD_ERROR_F 7 /* Failed to write file to disk */
#define UPLOAD_ERROR_X 8 /* File upload stopped by extension */
static void normalize_protected_variable(char *varname) {
char *s=varname, *index=nullptr, *indexend=nullptr, *p;
/* overjump leading space */
while (*s == ' ') {
s++;
}
/* and remove it */
if (s != varname) {
memmove(varname, s, strlen(s)+1);
}
for (p=varname; *p && *p != '['; p++) {
switch(*p) {
case ' ':
case '.':
*p='_';
break;
}
}
/* find index */
index = strchr(varname, '[');
if (index) {
index++;
s=index;
} else {
return;
}
/* done? */
while (index) {
while (*index == ' ' || *index == '\r' ||
*index == '\n' || *index=='\t') {
index++;
}
indexend = strchr(index, ']');
indexend = indexend ? indexend + 1 : index + strlen(index);
if (s != index) {
memmove(s, index, strlen(index)+1);
s += indexend-index;
} else {
s = indexend;
}
if (*s == '[') {
s++;
index = s;
} else {
index = nullptr;
}
}
*s++='\0';
}
static void add_protected_variable(char *varname) {
normalize_protected_variable(varname);
s_rfc1867_data->rfc1867ProtectedVariables.insert(varname);
}
static bool is_protected_variable(char *varname) {
normalize_protected_variable(varname);
auto iter = s_rfc1867_data->rfc1867ProtectedVariables.find(varname);
return iter != s_rfc1867_data->rfc1867ProtectedVariables.end();
}
static void safe_php_register_variable(char *var, const Variant& val,
Array& track_vars_array,
bool override_protection) {
if (override_protection || !is_protected_variable(var)) {
register_variable(track_vars_array, var, val);
}
}
bool is_uploaded_file(const std::string filename) {
std::set<std::string> &rfc1867UploadedFiles =
s_rfc1867_data->rfc1867UploadedFiles;
return rfc1867UploadedFiles.find(filename) != rfc1867UploadedFiles.end();
}
const std::set<std::string> &get_uploaded_files() {
return s_rfc1867_data->rfc1867UploadedFiles;
}
static void destroy_uploaded_files() {
std::set<std::string> &rfc1867UploadedFiles =
s_rfc1867_data->rfc1867UploadedFiles;
for (auto iter = rfc1867UploadedFiles.begin();
iter != rfc1867UploadedFiles.end(); iter++) {
unlink(iter->c_str());
}
rfc1867UploadedFiles.clear();
}
/*
* Following code is based on apache_multipart_buffer.c from
* libapreq-0.33 package.
*
*/
constexpr size_t FILLUNIT = 1024 * 5;
namespace {
struct multipart_buffer {
Transport *transport;
/* read buffer */
char *buffer;
char *buf_begin;
size_t bufsize;
int64_t bytes_in_buffer; // signed to catch underflow errors
/* boundary info */
char *boundary;
char *boundary_next;
int boundary_next_len;
/* post data */
const char *post_data;
uint64_t post_size;
uint64_t throw_size; // sum of all previously read chunks
char *cursor;
uint64_t read_post_bytes;
};
}
using header_list = std::list<std::pair<std::string, std::string>>;
static uint32_t read_post(multipart_buffer *self, char *buf,
uint32_t bytes_to_read) {
always_assert(bytes_to_read > 0);
always_assert(self->post_data);
always_assert(self->cursor >= self->post_data);
int64_t bytes_remaining = (self->post_size - self->throw_size) -
(self->cursor - self->post_data);
always_assert(bytes_remaining >= 0);
if (bytes_to_read <= bytes_remaining) {
memcpy(buf, self->cursor, bytes_to_read);
self->cursor += bytes_to_read;
return bytes_to_read;
}
uint32_t bytes_read = bytes_remaining;
memcpy(buf, self->cursor, bytes_remaining);
bytes_to_read -= bytes_remaining;
self->cursor += bytes_remaining;
always_assert(self->cursor == (char *)self->post_data +
(self->post_size - self->throw_size));
while (bytes_to_read > 0 && self->transport->hasMorePostData()) {
size_t extra_byte_read = 0;
const void *extra = self->transport->getMorePostData(extra_byte_read);
if (extra_byte_read == 0) break;
if (RuntimeOption::AlwaysPopulateRawPostData) {
// Possible overflow in buffer_append if post_size + extra_byte_read >=
// MAX INT
self->post_data = (const char *)buffer_append(
self->post_data, self->post_size, extra, extra_byte_read);
self->cursor = (char*)self->post_data + self->post_size;
} else {
self->post_data = (const char *)extra;
self->throw_size = self->post_size;
self->cursor = (char*)self->post_data;
}
self->post_size += extra_byte_read;
if (bytes_to_read <= extra_byte_read) {
memcpy(buf + bytes_read, self->cursor, bytes_to_read);
self->cursor += bytes_to_read;
return bytes_read + bytes_to_read;
}
memcpy(buf + bytes_read, self->cursor, extra_byte_read);
bytes_to_read -= extra_byte_read;
bytes_read += extra_byte_read;
self->cursor += extra_byte_read;
}
return bytes_read;
}
/*
fill up the buffer with client data.
returns number of bytes added to buffer.
*/
static uint32_t fill_buffer(multipart_buffer *self) {
uint32_t bytes_to_read, total_read = 0, actual_read = 0;
/* shift the existing data if necessary */
if (self->bytes_in_buffer > 0 && self->buf_begin != self->buffer) {
memmove(self->buffer, self->buf_begin, self->bytes_in_buffer);
}
self->buf_begin = self->buffer;
/* calculate the free space in the buffer */
bytes_to_read = self->bufsize - self->bytes_in_buffer;
always_assert(self->bufsize > 0);
always_assert(self->bytes_in_buffer >= 0);
/* read the required number of bytes */
while (bytes_to_read > 0) {
char *buf = self->buffer + self->bytes_in_buffer;
actual_read = read_post(self, buf, bytes_to_read);
/* update the buffer length */
if (actual_read > 0) {
always_assert(bytes_to_read >= actual_read);
self->bytes_in_buffer += actual_read;
self->read_post_bytes += actual_read;
total_read += actual_read;
bytes_to_read -= actual_read;
} else {
break;
}
}
return total_read;
}
/* eof if we are out of bytes, or if we hit the final boundary */
static int multipart_buffer_eof(multipart_buffer *self) {
if ( (self->bytes_in_buffer == 0 && fill_buffer(self) < 1) ) {
return 1;
} else {
return 0;
}
}
/* create new multipart_buffer structure */
static multipart_buffer *multipart_buffer_new(Transport *transport,
const char *data, size_t size,
std::string boundary) {
multipart_buffer *self =
(multipart_buffer *)calloc(1, sizeof(multipart_buffer));
self->transport = transport;
auto minsize = boundary.length() + 6;
if (minsize < FILLUNIT) minsize = FILLUNIT;
self->buffer = (char *) calloc(1, minsize + 1);
self->bufsize = minsize;
vspprintf(&self->boundary, 0, "--%s", boundary.c_str());
self->boundary_next_len =
vspprintf(&self->boundary_next, 0, "\n--%s", boundary.c_str());
self->buf_begin = self->buffer;
self->bytes_in_buffer = 0;
self->post_data = data;
self->cursor = (char*)self->post_data;
self->post_size = size;
self->throw_size = 0;
return self;
}
/*
gets the next CRLF terminated line from the input buffer.
if it doesn't find a CRLF, and the buffer isn't completely full, returns
NULL; otherwise, returns the beginning of the null-terminated line,
minus the CRLF.
note that we really just look for LF terminated lines. this works
around a bug in internet explorer for the macintosh which sends mime
boundaries that are only LF terminated when you use an image submit
button in a multipart/form-data form.
*/
static char *next_line(multipart_buffer *self) {
/* look for LF in the data */
char* line = self->buf_begin;
char* ptr = (char*)memchr(self->buf_begin, '\n', self->bytes_in_buffer);
if (ptr) { /* LF found */
/* terminate the string, remove CRLF */
if ((ptr - line) > 0 && *(ptr-1) == '\r') {
*(ptr-1) = 0;
} else {
*ptr = 0;
}
/* bump the pointer */
self->buf_begin = ptr + 1;
self->bytes_in_buffer -= (self->buf_begin - line);
} else { /* no LF found */
/* buffer isn't completely full, fail */
if (self->bytes_in_buffer < self->bufsize) {
return nullptr;
}
/* return entire buffer as a partial line */
line[self->bufsize] = 0;
self->buf_begin = ptr;
self->bytes_in_buffer = 0;
}
return line;
}
/* returns the next CRLF terminated line from the client */
static char *get_line(multipart_buffer *self) {
char* ptr = next_line(self);
if (!ptr) {
fill_buffer(self);
ptr = next_line(self);
}
return ptr;
}
/* finds a boundary */
static int find_boundary(multipart_buffer *self, char *boundary) {
char *line;
/* loop thru lines */
while( (line = get_line(self)) )
{
/* finished if we found the boundary */
if (!strcmp(line, boundary)) {
return 1;
}
}
/* didn't find the boundary */
return 0;
}
/* parse headers */
static int multipart_buffer_headers(multipart_buffer *self,
header_list &header) {
char *line;
std::string key;
std::string buf_value;
std::pair<std::string, std::string> entry;
/* didn't find boundary, abort */
if (!find_boundary(self, self->boundary)) {
return 0;
}
/* get lines of text, or CRLF_CRLF */
while( (line = get_line(self)) && strlen(line) > 0 )
{
/* add header to table */
char *value = nullptr;
/* space in the beginning means same header */
if (!isspace(line[0])) {
value = strchr(line, ':');
}
if (value) {
if (!buf_value.empty() && !key.empty() ) {
entry = std::make_pair(key, buf_value);
header.push_back(entry);
buf_value.erase();
key.erase();
}
*value = '\0';
do { value++; } while(isspace(*value));
key.assign(line);
buf_value.append(value);
} else if (!buf_value.empty() ) {
/* If no ':' on the line, add to previous line */
buf_value.append(line);
} else {
continue;
}
}
if (!buf_value.empty() && !key.empty()) {
entry = std::make_pair(key, buf_value);
header.push_back(entry);
}
return 1;
}
static char *php_mime_get_hdr_value(header_list &header, char *key) {
if (key == nullptr) return nullptr;
for (header_list::iterator iter = header.begin();
iter != header.end(); iter++) {
if (!strcasecmp(iter->first.c_str(), key)) {
return (char *)iter->second.c_str();
}
}
return nullptr;
}
static char *php_ap_getword(char **line, char stop) {
char *pos = *line, quote;
char *res;
while (*pos && *pos != stop) {
if ((quote = *pos) == '"' || quote == '\'') {
++pos;
while (*pos && *pos != quote) {
if (*pos == '\\' && pos[1] && pos[1] == quote) {
pos += 2;
} else {
++pos;
}
}
if (*pos) {
++pos;
}
} else ++pos;
}
if (*pos == '\0') {
res = strdup(*line);
*line += strlen(*line);
return res;
}
res = (char*)malloc(pos - *line + 1);
memcpy(res, *line, pos - *line);
res[pos - *line] = 0;
while (*pos == stop) {
++pos;
}
*line = pos;
return res;
}
static char *substring_conf(char *start, int len, char quote) {
char *result = (char *)malloc(len + 2);
char *resp = result;
int i;
for (i = 0; i < len; ++i) {
if (start[i] == '\\' &&
(start[i + 1] == '\\' || (quote && start[i + 1] == quote))) {
*resp++ = start[++i];
} else {
*resp++ = start[i];
}
}
*resp++ = '\0';
return result;
}
static char *php_ap_getword_conf(char **line) {
char *str = *line, *strend, *res, quote;
while (*str && isspace(*str)) {
++str;
}
if (!*str) {
*line = str;
return strdup("");
}
if ((quote = *str) == '"' || quote == '\'') {
strend = str + 1;
look_for_quote:
while (*strend && *strend != quote) {
if (*strend == '\\' && strend[1] && strend[1] == quote) {
strend += 2;
} else {
++strend;
}
}
if (*strend && *strend == quote) {
char p = *(strend + 1);
if (p != '\r' && p != '\n' && p != '\0') {
strend++;
goto look_for_quote;
}
}
res = substring_conf(str + 1, strend - str - 1, quote);
if (*strend == quote) {
++strend;
}
} else {
strend = str;
while (*strend && !isspace(*strend)) {
++strend;
}
res = substring_conf(str, strend - str, 0);
}
while (*strend && isspace(*strend)) {
++strend;
}
*line = strend;
return res;
}
/*
search for a string in a fixed-length byte string.
if partial is true, partial matches are allowed at the end of the buffer.
returns NULL if not found, or a pointer to the start of the first match.
*/
static char *php_ap_memstr(char *haystack, int haystacklen, char *needle,
int needlen, int partial) {
int len = haystacklen;
char *ptr = haystack;
/* iterate through first character matches */
while( (ptr = (char *)memchr(ptr, needle[0], len)) ) {
/* calculate length after match */
len = haystacklen - (ptr - (char *)haystack);
/* done if matches up to capacity of buffer */
if (memcmp(needle, ptr, needlen < len ? needlen : len) == 0 &&
(partial || len >= needlen)) {
break;
}
/* next character */
ptr++; len--;
}
return ptr;
}
/* read until a boundary condition */
static int multipart_buffer_read(multipart_buffer *self, char *buf,
int bytes, int *end) {
int len, max;
char *bound;
/* fill buffer if needed */
if (bytes > self->bytes_in_buffer) {
fill_buffer(self);
}
/* look for a potential boundary match, only read data up to that point */
if ((bound =
php_ap_memstr(self->buf_begin, self->bytes_in_buffer,
self->boundary_next, self->boundary_next_len, 1))) {
max = bound - self->buf_begin;
if (end &&
php_ap_memstr(self->buf_begin, self->bytes_in_buffer,
self->boundary_next, self->boundary_next_len, 0)) {
*end = 1;
}
} else {
max = self->bytes_in_buffer;
}
/* maximum number of bytes we are reading */
len = max < bytes-1 ? max : bytes-1;
/* if we read any data... */
if (len > 0) {
/* copy the data */
memcpy(buf, self->buf_begin, len);
buf[len] = 0;
if (bound && len > 0 && buf[len-1] == '\r') {
buf[--len] = 0;
}
/* update the buffer */
self->bytes_in_buffer -= len;
self->buf_begin += len;
}
return len;
}
/*
XXX: this is horrible memory-usage-wise, but we only expect
to do this on small pieces of form data.
*/
static char *multipart_buffer_read_body(multipart_buffer *self,
unsigned int *len) {
char buf[FILLUNIT], *out=nullptr;
int total_bytes=0, read_bytes=0;
while((read_bytes = multipart_buffer_read(self, buf, sizeof(buf), nullptr))) {
out = (char *)realloc(out, total_bytes + read_bytes + 1);
memcpy(out + total_bytes, buf, read_bytes);
total_bytes += read_bytes;
}
if (out) out[total_bytes] = '\0';
*len = total_bytes;
return out;
}
/*
* The combined READER/HANDLER
*
*/
void rfc1867PostHandler(Transport* transport,
Array& post,
Array& files,
size_t content_length,
const void*& data, size_t& size,
const std::string boundary) {
char *s=nullptr, *start_arr=nullptr;
std::string array_index, abuf;
char *lbuf=nullptr;
int total_bytes=0, cancel_upload=0, is_arr_upload=0, array_len=0;
int max_file_size=0, skip_upload=0, anonindex=0, is_anonymous;
std::set<std::string> &uploaded_files = s_rfc1867_data->rfc1867UploadedFiles;
multipart_buffer *mbuff;
int fd=-1;
void *event_extra_data = nullptr;
unsigned int llen = 0;
int upload_count = RuntimeOption::MaxFileUploads;
/* Initialize the buffer */
if (!(mbuff = multipart_buffer_new(transport,
(const char *)data, size, boundary))) {
Logger::Warning("Unable to initialize the input buffer");
return;
}
/* Initialize $_FILES[] */
s_rfc1867_data->rfc1867ProtectedVariables.clear();
uploaded_files.clear();
int (*php_rfc1867_callback)(apc_rfc1867_data *rfc1867ApcData,
unsigned int event, void *event_data,
void **extra) = s_rfc1867_data->rfc1867Callback;
if (php_rfc1867_callback != nullptr) {
multipart_event_start event_start;
event_start.content_length = content_length;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_START, &event_start,
&event_extra_data) == FAILURE) {
goto fileupload_done;
}
}
while (!multipart_buffer_eof(mbuff)) {
std::string temp_filename;
char buff[FILLUNIT];
char *cd=nullptr,*param=nullptr,*filename=nullptr, *tmp=nullptr;
size_t blen=0, wlen=0;
off_t offset;
header_list header;
if (!multipart_buffer_headers(mbuff, header)) {
goto fileupload_done;
}
if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) {
char *pair=nullptr;
int end=0;
while (isspace(*cd)) {
++cd;
}
while (*cd && (pair = php_ap_getword(&cd, ';')))
{
char *key=nullptr, *word = pair;
while (isspace(*cd)) {
++cd;
}
if (strchr(pair, '=')) {
key = php_ap_getword(&pair, '=');
if (!strcasecmp(key, "name")) {
if (param) {
free(param);
}
param = php_ap_getword_conf(&pair);
} else if (!strcasecmp(key, "filename")) {
if (filename) {
free(filename);
}
filename = php_ap_getword_conf(&pair);
}
}
if (key) free(key);
free(word);
}
/* Normal form variable, safe to read all data into memory */
if (!filename && param) {
unsigned int value_len;
char *value = multipart_buffer_read_body(mbuff, &value_len);
unsigned int new_val_len; /* Dummy variable */
if (!value) {
value = strdup("");
}
new_val_len = value_len;
if (php_rfc1867_callback != nullptr) {
multipart_event_formdata event_formdata;
size_t newlength = new_val_len;
event_formdata.post_bytes_processed = mbuff->read_post_bytes;
event_formdata.name = param;
event_formdata.value = &value;
event_formdata.length = new_val_len;
event_formdata.newlength = &newlength;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FORMDATA, &event_formdata,
&event_extra_data) == FAILURE) {
free(param);
free(value);
continue;
}
new_val_len = newlength;
}
String val(value, new_val_len, CopyString);
safe_php_register_variable(param, val, post, 0);
if (!strcasecmp(param, "MAX_FILE_SIZE")) {
max_file_size = atol(value);
}
free(param);
free(value);
continue;
}
/* If file_uploads=off, skip the file part */
if (!RuntimeOption::EnableFileUploads) {
skip_upload = 1;
} else if (upload_count <= 0) {
Logger::Warning(
"Maximum number of allowable file uploads has been exceeded"
);
skip_upload = 1;
}
/* Return with an error if the posted data is garbled */
if (!param && !filename) {
Logger::Warning("File Upload Mime headers garbled");
goto fileupload_done;
}
if (!param) {
is_anonymous = 1;
param = (char*)malloc(MAX_SIZE_ANONNAME);
snprintf(param, MAX_SIZE_ANONNAME, "%u", anonindex++);
} else {
is_anonymous = 0;
}
/* New Rule: never repair potential malicious user input */
if (!skip_upload) {
tmp = param;
long c = 0;
while (*tmp) {
if (*tmp == '[') {
c++;
} else if (*tmp == ']') {
c--;
if (tmp[1] && tmp[1] != '[') {
skip_upload = 1;
break;
}
}
if (c < 0) {
skip_upload = 1;
break;
}
tmp++;
}
}
total_bytes = cancel_upload = 0;
if (!skip_upload) {
/* Handle file */
char path[PATH_MAX];
// open a temporary file
snprintf(path, sizeof(path), "%s/XXXXXX",
RuntimeOption::UploadTmpDir.c_str());
fd = mkstemp(path);
upload_count--;
if (fd == -1) {
Logger::Warning("Unable to open temporary file");
Logger::Warning("File upload error - unable to create a "
"temporary file");
cancel_upload = UPLOAD_ERROR_E;
}
temp_filename = path;
}
if (!skip_upload && php_rfc1867_callback != nullptr) {
multipart_event_file_start event_file_start;
event_file_start.post_bytes_processed = mbuff->read_post_bytes;
event_file_start.name = param;
event_file_start.filename = &filename;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FILE_START,
&event_file_start,
&event_extra_data) == FAILURE) {
if (!temp_filename.empty()) {
if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */
close(fd);
unlink(temp_filename.c_str());
}
}
temp_filename="";
free(param);
free(filename);
continue;
}
}
if (skip_upload) {
free(param);
free(filename);
continue;
}
if (strlen(filename) == 0) {
Logger::Verbose("No file uploaded");
cancel_upload = UPLOAD_ERROR_D;
}
offset = 0;
end = 0;
while (!cancel_upload &&
(blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end)))
{
if (php_rfc1867_callback != nullptr) {
multipart_event_file_data event_file_data;
event_file_data.post_bytes_processed = mbuff->read_post_bytes;
event_file_data.offset = offset;
event_file_data.data = buff;
event_file_data.length = blen;
event_file_data.newlength = &blen;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FILE_DATA,
&event_file_data,
&event_extra_data) == FAILURE) {
cancel_upload = UPLOAD_ERROR_X;
continue;
}
}
if (VirtualHost::GetUploadMaxFileSize() > 0 &&
total_bytes > VirtualHost::GetUploadMaxFileSize()) {
Logger::Verbose("upload_max_filesize of %" PRId64 " bytes exceeded "
"- file [%s=%s] not saved",
VirtualHost::GetUploadMaxFileSize(),
param, filename);
cancel_upload = UPLOAD_ERROR_A;
} else if (max_file_size && (total_bytes > max_file_size)) {
Logger::Verbose("MAX_FILE_SIZE of %d bytes exceeded - "
"file [%s=%s] not saved",
max_file_size, param, filename);
cancel_upload = UPLOAD_ERROR_B;
} else if (blen > 0) {
wlen = folly::writeFull(fd, buff, blen);
if (wlen < blen) {
Logger::Verbose("Only %zd bytes were written, expected to "
"write %zd", wlen, blen);
cancel_upload = UPLOAD_ERROR_F;
} else {
total_bytes += wlen;
}
offset += wlen;
}
}
if (fd!=-1) { /* may not be initialized if file could not be created */
close(fd);
}
if (!cancel_upload && !end) {
Logger::Verbose("Missing mime boundary at the end of the data for "
"file %s", strlen(filename) > 0 ? filename : "");
cancel_upload = UPLOAD_ERROR_C;
}
if (strlen(filename) > 0 && total_bytes == 0 && !cancel_upload) {
Logger::Verbose("Uploaded file size 0 - file [%s=%s] not saved",
param, filename);
cancel_upload = 5;
}
if (php_rfc1867_callback != nullptr) {
multipart_event_file_end event_file_end;
event_file_end.post_bytes_processed = mbuff->read_post_bytes;
event_file_end.temp_filename = temp_filename.c_str();
event_file_end.cancel_upload = cancel_upload;
if (php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_FILE_END,
&event_file_end,
&event_extra_data) == FAILURE) {
cancel_upload = UPLOAD_ERROR_X;
}
}
if (cancel_upload && cancel_upload != UPLOAD_ERROR_C) {
if (!temp_filename.empty()) {
if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */
unlink(temp_filename.c_str());
}
}
temp_filename="";
} else {
s_rfc1867_data->rfc1867UploadedFiles.insert(temp_filename);
}
/* is_arr_upload is true when name of file upload field
* ends in [.*]
* start_arr is set to point to 1st [
*/
is_arr_upload = (start_arr = strchr(param,'[')) &&
(param[strlen(param)-1] == ']');
if (is_arr_upload) {
array_len = strlen(start_arr);
array_index = std::string(start_arr+1, array_len-2);
}
/* Add $foo_name */
if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) {
llen = strlen(param);
lbuf = (char *) realloc(lbuf, llen + MAX_SIZE_OF_INDEX + 1);
llen += MAX_SIZE_OF_INDEX + 1;
}
if (is_arr_upload) {
abuf = std::string(param, strlen(param)-array_len);
snprintf(lbuf, llen, "%s_name[%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s_name", param);
}
/* The \ check should technically be needed for win32 systems only
* where it is a valid path separator. However, IE in all it's wisdom
* always sends the full path of the file on the user's filesystem,
* which means that unless the user does basename() they get a bogus
* file name. Until IE's user base drops to nill or problem is fixed
* this code must remain enabled for all systems.
*/
s = strrchr(filename, '\\');
if ((tmp = strrchr(filename, '/')) > s) {
s = tmp;
}
Array globals = php_globals_as_array();
if (!is_anonymous) {
if (s) {
String val(s+1, strlen(s+1), CopyString);
safe_php_register_variable(lbuf, val, globals, 0);
} else {
String val(filename, strlen(filename), CopyString);
safe_php_register_variable(lbuf, val, globals, 0);
}
}
/* Add $foo[name] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[name][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[name]", param);
}
if (s) {
String val(s+1, strlen(s+1), CopyString);
safe_php_register_variable(lbuf, val, files, 0);
} else {
String val(filename, strlen(filename), CopyString);
safe_php_register_variable(lbuf, val, files, 0);
}
free(filename);
s = nullptr;
/* Possible Content-Type: */
if ((cancel_upload && cancel_upload != UPLOAD_ERROR_C) ||
!(cd = php_mime_get_hdr_value(header, "Content-Type"))) {
cd = "";
} else {
/* fix for Opera 6.01 */
s = strchr(cd, ';');
if (s != nullptr) {
*s = '\0';
}
}
/* Add $foo_type */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s_type[%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s_type", param);
}
if (!is_anonymous) {
String val(cd, strlen(cd), CopyString);
safe_php_register_variable(lbuf, val, globals, 0);
}
/* Add $foo[type] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[type][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[type]", param);
}
String val(cd, strlen(cd), CopyString);
safe_php_register_variable(lbuf, val, files, 0);
/* Restore Content-Type Header */
if (s != nullptr) {
*s = ';';
}
s = "";
/* Initialize variables */
add_protected_variable(param);
Variant tempFileName(temp_filename);
/* if param is of form xxx[.*] this will cut it to xxx */
if (!is_anonymous) {
safe_php_register_variable(param, tempFileName, globals, 1);
}
/* Add $foo[tmp_name] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[tmp_name][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[tmp_name]", param);
}
add_protected_variable(lbuf);
safe_php_register_variable(lbuf, tempFileName, files, 1);
Variant file_size, error_type;
error_type = cancel_upload;
/* Add $foo[error] */
if (cancel_upload) {
file_size = 0;
} else {
file_size = total_bytes;
}
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[error][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[error]", param);
}
safe_php_register_variable(lbuf, error_type, files, 0);
/* Add $foo_size */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s_size[%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s_size", param);
}
if (!is_anonymous) {
safe_php_register_variable(lbuf, file_size, globals, 0);
}
/* Add $foo[size] */
if (is_arr_upload) {
snprintf(lbuf, llen, "%s[size][%s]",
abuf.c_str(), array_index.c_str());
} else {
snprintf(lbuf, llen, "%s[size]", param);
}
safe_php_register_variable(lbuf, file_size, files, 0);
free(param);
}
}
fileupload_done:
data = mbuff->post_data;
size = mbuff->post_size;
if (php_rfc1867_callback != nullptr) {
multipart_event_end event_end;
event_end.post_bytes_processed = mbuff->read_post_bytes;
php_rfc1867_callback(&s_rfc1867_data->rfc1867ApcData,
MULTIPART_EVENT_END, &event_end, &event_extra_data);
}
if (lbuf) free(lbuf);
s_rfc1867_data->rfc1867ProtectedVariables.clear();
if (mbuff->boundary_next) free(mbuff->boundary_next);
if (mbuff->boundary) free(mbuff->boundary);
if (mbuff->buffer) free(mbuff->buffer);
if (mbuff) free(mbuff);
}
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_592_0 |
crossvul-cpp_data_bad_1580_3 | /**********************************************************************
* Copyright (c) 2008 Red Hat, Inc.
*
* File: sw-offload.c
*
* This file contains SW Implementation of checksum computation for IP,TCP,UDP
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
**********************************************************************/
#include "ndis56common.h"
// till IP header size is 8 bit
#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4)
// IPv6 Header RFC 2460 (n*8 bytes)
typedef struct _tagIPv6ExtHeader {
UCHAR ip6ext_next_header; // next header type
UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes
USHORT options; //
} IPv6ExtHeader;
// IP Pseudo Header RFC 768
typedef struct _tagIPv4PseudoHeader {
ULONG ipph_src; // Source address
ULONG ipph_dest; // Destination address
UCHAR ipph_zero; // 0
UCHAR ipph_protocol; // TCP/UDP
USHORT ipph_length; // TCP/UDP length
}tIPv4PseudoHeader;
// IPv6 Pseudo Header RFC 2460
typedef struct _tagIPv6PseudoHeader {
IPV6_ADDRESS ipph_src; // Source address
IPV6_ADDRESS ipph_dest; // Destination address
ULONG ipph_length; // TCP/UDP length
UCHAR z1; // 0
UCHAR z2; // 0
UCHAR z3; // 0
UCHAR ipph_protocol; // TCP/UDP
}tIPv6PseudoHeader;
// IP v6 extension header option
typedef struct _tagIP6_EXT_HDR_OPTION
{
UCHAR Type;
UCHAR Length;
} IP6_EXT_HDR_OPTION, *PIP6_EXT_HDR_OPTION;
#define IP6_EXT_HDR_OPTION_PAD1 (0)
#define IP6_EXT_HDR_OPTION_HOME_ADDR (201)
// IP v6 routing header
typedef struct _tagIP6_TYPE2_ROUTING_HEADER
{
UCHAR NextHdr;
UCHAR HdrLen;
UCHAR RoutingType;
UCHAR SegmentsLeft;
ULONG Reserved;
IPV6_ADDRESS Address;
} IP6_TYPE2_ROUTING_HEADER, *PIP6_TYPE2_ROUTING_HEADER;
#define PROTOCOL_TCP 6
#define PROTOCOL_UDP 17
#define IP_HEADER_LENGTH(pHeader) (((pHeader)->ip_verlen & 0x0F) << 2)
#define IP_HEADER_VERSION(pHeader) (((pHeader)->ip_verlen & 0xF0) >> 4)
#define IP_HEADER_IS_FRAGMENT(pHeader) (((pHeader)->ip_offset & ~0xC0) != 0)
#define IP6_HEADER_VERSION(pHeader) (((pHeader)->ip6_ver_tc & 0xF0) >> 4)
#define ETH_GET_VLAN_HDR(ethHdr) ((PVLAN_HEADER) RtlOffsetToPointer(ethHdr, ETH_PRIORITY_HEADER_OFFSET))
#define VLAN_GET_USER_PRIORITY(vlanHdr) ( (((PUCHAR)(vlanHdr))[2] & 0xE0) >> 5 )
#define VLAN_GET_VLAN_ID(vlanHdr) ( ((USHORT) (((PUCHAR)(vlanHdr))[2] & 0x0F) << 8) | ( ((PUCHAR)(vlanHdr))[3] ) )
#define ETH_PROTO_IP4 (0x0800)
#define ETH_PROTO_IP6 (0x86DD)
#define IP6_HDR_HOP_BY_HOP (0)
#define IP6_HDR_ROUTING (43)
#define IP6_HDR_FRAGMENT (44)
#define IP6_HDR_ESP (50)
#define IP6_HDR_AUTHENTICATION (51)
#define IP6_HDR_NONE (59)
#define IP6_HDR_DESTINATON (60)
#define IP6_HDR_MOBILITY (135)
#define IP6_EXT_HDR_GRANULARITY (8)
static UINT32 RawCheckSumCalculator(PVOID buffer, ULONG len)
{
UINT32 val = 0;
PUSHORT pus = (PUSHORT)buffer;
ULONG count = len >> 1;
while (count--) val += *pus++;
if (len & 1) val += (USHORT)*(PUCHAR)pus;
return val;
}
static __inline USHORT RawCheckSumFinalize(UINT32 val)
{
val = (((val >> 16) | (val << 16)) + val) >> 16;
return (USHORT)~val;
}
static __inline USHORT CheckSumCalculatorFlat(PVOID buffer, ULONG len)
{
return RawCheckSumFinalize(RawCheckSumCalculator(buffer, len));
}
static __inline USHORT CheckSumCalculator(tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG len)
{
tCompletePhysicalAddress *pCurrentPage = &pDataPages[0];
ULONG ulCurrPageOffset = 0;
UINT32 u32RawCSum = 0;
while(ulStartOffset > 0)
{
ulCurrPageOffset = min(pCurrentPage->size, ulStartOffset);
if(ulCurrPageOffset < ulStartOffset)
pCurrentPage++;
ulStartOffset -= ulCurrPageOffset;
}
while(len > 0)
{
PVOID pCurrentPageDataStart = RtlOffsetToPointer(pCurrentPage->Virtual, ulCurrPageOffset);
ULONG ulCurrentPageDataLength = min(len, pCurrentPage->size - ulCurrPageOffset);
u32RawCSum += RawCheckSumCalculator(pCurrentPageDataStart, ulCurrentPageDataLength);
pCurrentPage++;
ulCurrPageOffset = 0;
len -= ulCurrentPageDataLength;
}
return RawCheckSumFinalize(u32RawCSum);
}
/******************************************
IP header checksum calculator
*******************************************/
static __inline VOID CalculateIpChecksum(IPv4Header *pIpHeader)
{
pIpHeader->ip_xsum = 0;
pIpHeader->ip_xsum = CheckSumCalculatorFlat(pIpHeader, IP_HEADER_LENGTH(pIpHeader));
}
static __inline tTcpIpPacketParsingResult
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
static __inline tTcpIpPacketParsingResult
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
// may be full or not, but the datagram length is known
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
else
{
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
static __inline tTcpIpPacketParsingResult
QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
{
tTcpIpPacketParsingResult res;
res.value = 0;
if (len < 4)
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
if (len < sizeof(IPv4Header))
{
res.ipStatus = ppresNotIP;
return res;
}
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (res.ipStatus == ppresNotIP)
{
return res;
}
if (ipHeaderSize >= fullLength || len < fullLength)
{
DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n", __FUNCTION__,
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipCheckSum = ppresIPTooShort;
return res;
}
}
else if (ip_version == 6)
{
if (len < sizeof(IPv6Header))
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
if (len < fullLength)
{
res.ipStatus = ppresNotIP;
return res;
}
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
//existing extended headers
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
//any other protocol
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
// bit "more fragments" or fragment offset mean the packet is fragmented
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
static __inline USHORT GetXxpHeaderAndPayloadLen(IPHeader *pIpHeader, tTcpIpPacketParsingResult res)
{
if (res.ipStatus == ppresIPV4)
{
USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4);
USHORT len = swap_short(pIpHeader->v4.ip_length);
return len - headerLength;
}
if (res.ipStatus == ppresIPV6)
{
USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize;
}
return 0;
}
static __inline USHORT CalculateIpv4PseudoHeaderChecksum(IPv4Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv4PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src = pIpHeader->ip_src;
ipph.ipph_dest = pIpHeader->ip_dest;
ipph.ipph_zero = 0;
ipph.ipph_protocol = pIpHeader->ip_protocol;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen)
{
tIPv6PseudoHeader ipph;
USHORT checksum;
ipph.ipph_src[0] = pIpHeader->ip6_src_address[0];
ipph.ipph_src[1] = pIpHeader->ip6_src_address[1];
ipph.ipph_src[2] = pIpHeader->ip6_src_address[2];
ipph.ipph_src[3] = pIpHeader->ip6_src_address[3];
ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0];
ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1];
ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2];
ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3];
ipph.z1 = ipph.z2 = ipph.z3 = 0;
ipph.ipph_protocol = pIpHeader->ip6_next_header;
ipph.ipph_length = swap_short(headerAndPayloadLen);
checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
return ~checksum;
}
static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader,
tTcpIpPacketParsingResult res,
USHORT headerAndPayloadLen)
{
if (res.ipStatus == ppresIPV4)
return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen);
if (res.ipStatus == ppresIPV6)
return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen);
return 0;
}
static __inline BOOLEAN
CompareNetCheckSumOnEndSystem(USHORT computedChecksum, USHORT arrivedChecksum)
{
//According to RFC 1624 sec. 3
//Checksum verification mechanism should treat 0xFFFF
//checksum value from received packet as 0x0000
if(arrivedChecksum == 0xFFFF)
arrivedChecksum = 0;
return computedChecksum == arrivedChecksum;
}
/******************************************
Calculates IP header checksum calculator
it can be already calculated
the header must be complete!
*******************************************/
static __inline tTcpIpPacketParsingResult
VerifyIpChecksum(
IPv4Header *pIpHeader,
tTcpIpPacketParsingResult known,
BOOLEAN bFix)
{
tTcpIpPacketParsingResult res = known;
if (res.ipCheckSum != ppresIPTooShort)
{
USHORT saved = pIpHeader->ip_xsum;
CalculateIpChecksum(pIpHeader);
res.ipCheckSum = CompareNetCheckSumOnEndSystem(pIpHeader->ip_xsum, saved) ? ppresCSOK : ppresCSBad;
if (!bFix)
pIpHeader->ip_xsum = saved;
else
res.fixedIpCS = res.ipCheckSum == ppresCSBad;
}
return res;
}
/*********************************************
Calculates UDP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateUdpChecksumGivenPseudoCS(UDPHeader *pUdpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG udpLength)
{
pUdpHeader->udp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, udpLength);
}
/*********************************************
Calculates TCP checksum, assuming the checksum field
is initialized with pseudoheader checksum
**********************************************/
static __inline VOID CalculateTcpChecksumGivenPseudoCS(TCPHeader *pTcpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG tcpLength)
{
pTcpHeader->tcp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, tcpLength);
}
/************************************************
Checks (and fix if required) the TCP checksum
sets flags in result structure according to verification
TcpPseudoOK if valid pseudo CS was found
TcpOK if valid TCP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyTcpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pTcpHeader->tcp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (res.xxpCheckSum != ppresPCSOK || whatToFix)
{
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader)))
{
pTcpHeader->tcp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
//USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length);
pTcpHeader->tcp_xsum = phcs;
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pTcpHeader->tcp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else if (whatToFix)
{
res.xxpStatus = ppresXxpIncomplete;
}
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good TCP CS
// in such rare case we give a priority to TCP CS
CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pTcpHeader->tcp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pTcpHeader->tcp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
/************************************************
Checks (and fix if required) the UDP checksum
sets flags in result structure according to verification
UdpPseudoOK if valid pseudo CS was found
UdpOK if valid UDP checksum was found
************************************************/
static __inline tTcpIpPacketParsingResult
VerifyUdpChecksum(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
tTcpIpPacketParsingResult known,
ULONG whatToFix)
{
USHORT phcs;
tTcpIpPacketParsingResult res = known;
IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize);
USHORT saved = pUdpHeader->udp_xsum;
USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res);
if (ulDataLength >= res.ipHeaderSize)
{
phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen);
res.xxpCheckSum = CompareNetCheckSumOnEndSystem(phcs, saved) ? ppresPCSOK : ppresCSBad;
if (whatToFix & pcrFixPHChecksum)
{
if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader)))
{
pUdpHeader->udp_xsum = phcs;
res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK;
}
else
res.xxpStatus = ppresXxpIncomplete;
}
else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum))
{
if (res.xxpFull)
{
pUdpHeader->udp_xsum = phcs;
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
if (!(whatToFix & pcrFixXxpChecksum))
pUdpHeader->udp_xsum = saved;
else
res.fixedXxpCS =
res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK;
}
else
res.xxpCheckSum = ppresXxpIncomplete;
}
else if (res.xxpFull)
{
// we have correct PHCS and we do not need to fix anything
// there is a very small chance that it is also good UDP CS
// in such rare case we give a priority to UDP CS
CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen);
if (CompareNetCheckSumOnEndSystem(pUdpHeader->udp_xsum, saved))
res.xxpCheckSum = ppresCSOK;
pUdpHeader->udp_xsum = saved;
}
}
else
res.ipCheckSum = ppresIPTooShort;
return res;
}
static LPCSTR __inline GetPacketCase(tTcpIpPacketParsingResult res)
{
static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" };
if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ?
(res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") :
(res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6");
if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP";
if (res.xxpStatus == ppresXxpOther) return "IP";
return IPCaseName[res.ipStatus];
}
static LPCSTR __inline GetIPCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" };
return CSCaseName[res.ipCheckSum];
}
static LPCSTR __inline GetXxpCSCase(tTcpIpPacketParsingResult res)
{
static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" };
return CSCaseName[res.xxpCheckSum];
}
static __inline VOID PrintOutParsingResult(
tTcpIpPacketParsingResult res,
int level,
LPCSTR procname)
{
DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s\n", procname,
GetPacketCase(res),
GetIPCSCase(res),
res.fixedIpCS ? "(fixed)" : "",
GetXxpCSCase(res),
res.fixedXxpCS ? "(fixed)" : ""));
}
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
static __inline
VOID AnalyzeL3Proto(
USHORT L3Proto,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isIP4 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP4));
packetInfo->isIP6 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP6));
}
static
BOOLEAN AnalyzeL2Hdr(
PNET_PACKET_INFO packetInfo)
{
PETH_HEADER dataBuffer = (PETH_HEADER) packetInfo->headersBuffer;
if (packetInfo->dataLength < ETH_HEADER_SIZE)
return FALSE;
packetInfo->ethDestAddr = dataBuffer->DstAddr;
if (ETH_IS_BROADCAST(dataBuffer))
{
packetInfo->isBroadcast = TRUE;
}
else if (ETH_IS_MULTICAST(dataBuffer))
{
packetInfo->isMulticast = TRUE;
}
else
{
packetInfo->isUnicast = TRUE;
}
if(ETH_HAS_PRIO_HEADER(dataBuffer))
{
PVLAN_HEADER vlanHdr = ETH_GET_VLAN_HDR(dataBuffer);
if(packetInfo->dataLength < ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE)
return FALSE;
packetInfo->hasVlanHeader = TRUE;
packetInfo->Vlan.UserPriority = VLAN_GET_USER_PRIORITY(vlanHdr);
packetInfo->Vlan.VlanId = VLAN_GET_VLAN_ID(vlanHdr);
packetInfo->L2HdrLen = ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE;
AnalyzeL3Proto(vlanHdr->EthType, packetInfo);
}
else
{
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
AnalyzeL3Proto(dataBuffer->EthType, packetInfo);
}
packetInfo->L2PayloadLen = packetInfo->dataLength - packetInfo->L2HdrLen;
return TRUE;
}
static __inline
BOOLEAN SkipIP6ExtensionHeader(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr)
{
IPv6ExtHeader* ip6ExtHdr;
if (*ip6HdrLength + sizeof(*ip6ExtHdr) > dataLength)
return FALSE;
ip6ExtHdr = (IPv6ExtHeader *)RtlOffsetToPointer(ip6Hdr, *ip6HdrLength);
*nextHdr = ip6ExtHdr->ip6ext_next_header;
*ip6HdrLength += (ip6ExtHdr->ip6ext_hdr_len + 1) * IP6_EXT_HDR_GRANULARITY;
return TRUE;
}
static
BOOLEAN AnalyzeIP6RoutingExtension(
PIP6_TYPE2_ROUTING_HEADER routingHdr,
ULONG dataLength,
IPV6_ADDRESS **destAddr)
{
if(dataLength < sizeof(*routingHdr))
return FALSE;
if(routingHdr->RoutingType == 2)
{
if((dataLength != sizeof(*routingHdr)) || (routingHdr->SegmentsLeft != 1))
return FALSE;
*destAddr = &routingHdr->Address;
}
else *destAddr = NULL;
return TRUE;
}
static
BOOLEAN AnalyzeIP6DestinationExtension(
PVOID destHdr,
ULONG dataLength,
IPV6_ADDRESS **homeAddr)
{
while(dataLength != 0)
{
PIP6_EXT_HDR_OPTION optHdr = (PIP6_EXT_HDR_OPTION) destHdr;
ULONG optionLen;
switch(optHdr->Type)
{
case IP6_EXT_HDR_OPTION_HOME_ADDR:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
if(optHdr->Length != sizeof(IPV6_ADDRESS))
return FALSE;
*homeAddr = (IPV6_ADDRESS*) RtlOffsetToPointer(optHdr, sizeof(IP6_EXT_HDR_OPTION));
break;
case IP6_EXT_HDR_OPTION_PAD1:
optionLen = RTL_SIZEOF_THROUGH_FIELD(IP6_EXT_HDR_OPTION, Type);
break;
default:
if(dataLength < sizeof(IP6_EXT_HDR_OPTION))
return FALSE;
optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION);
break;
}
destHdr = RtlOffsetToPointer(destHdr, optionLen);
if(dataLength < optionLen)
return FALSE;
dataLength -= optionLen;
}
return TRUE;
}
static
BOOLEAN AnalyzeIP6Hdr(
IPv6Header *ip6Hdr,
ULONG dataLength,
PULONG ip6HdrLength,
PUCHAR nextHdr,
PULONG homeAddrOffset,
PULONG destAddrOffset)
{
*homeAddrOffset = 0;
*destAddrOffset = 0;
*ip6HdrLength = sizeof(*ip6Hdr);
if(dataLength < *ip6HdrLength)
return FALSE;
*nextHdr = ip6Hdr->ip6_next_header;
for(;;)
{
switch (*nextHdr)
{
default:
case IP6_HDR_NONE:
case PROTOCOL_TCP:
case PROTOCOL_UDP:
case IP6_HDR_FRAGMENT:
return TRUE;
case IP6_HDR_DESTINATON:
{
IPV6_ADDRESS *homeAddr = NULL;
ULONG destHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6DestinationExtension(RtlOffsetToPointer(ip6Hdr, destHdrOffset),
*ip6HdrLength - destHdrOffset, &homeAddr))
return FALSE;
*homeAddrOffset = homeAddr ? RtlPointerToOffset(ip6Hdr, homeAddr) : 0;
}
break;
case IP6_HDR_ROUTING:
{
IPV6_ADDRESS *destAddr = NULL;
ULONG routingHdrOffset = *ip6HdrLength;
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
if(!AnalyzeIP6RoutingExtension((PIP6_TYPE2_ROUTING_HEADER) RtlOffsetToPointer(ip6Hdr, routingHdrOffset),
*ip6HdrLength - routingHdrOffset, &destAddr))
return FALSE;
*destAddrOffset = destAddr ? RtlPointerToOffset(ip6Hdr, destAddr) : 0;
}
break;
case IP6_HDR_HOP_BY_HOP:
case IP6_HDR_ESP:
case IP6_HDR_AUTHENTICATION:
case IP6_HDR_MOBILITY:
if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr))
return FALSE;
break;
}
}
}
static __inline
VOID AnalyzeL4Proto(
UCHAR l4Protocol,
PNET_PACKET_INFO packetInfo)
{
packetInfo->isTCP = (l4Protocol == PROTOCOL_TCP);
packetInfo->isUDP = (l4Protocol == PROTOCOL_UDP);
}
static
BOOLEAN AnalyzeL3Hdr(
PNET_PACKET_INFO packetInfo)
{
if(packetInfo->isIP4)
{
IPv4Header *ip4Hdr = (IPv4Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(packetInfo->dataLength < packetInfo->L2HdrLen + sizeof(*ip4Hdr))
return FALSE;
packetInfo->L3HdrLen = IP_HEADER_LENGTH(ip4Hdr);
if ((packetInfo->L3HdrLen < sizeof(*ip4Hdr)) ||
(packetInfo->dataLength < packetInfo->L2HdrLen + packetInfo->L3HdrLen))
return FALSE;
if(IP_HEADER_VERSION(ip4Hdr) != 4)
return FALSE;
packetInfo->isFragment = IP_HEADER_IS_FRAGMENT(ip4Hdr);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(ip4Hdr->ip_protocol, packetInfo);
}
}
else if(packetInfo->isIP6)
{
ULONG homeAddrOffset, destAddrOffset;
UCHAR l4Proto;
IPv6Header *ip6Hdr = (IPv6Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen);
if(IP6_HEADER_VERSION(ip6Hdr) != 6)
return FALSE;
if(!AnalyzeIP6Hdr(ip6Hdr, packetInfo->L2PayloadLen,
&packetInfo->L3HdrLen, &l4Proto, &homeAddrOffset, &destAddrOffset))
return FALSE;
if (packetInfo->L3HdrLen > MAX_SUPPORTED_IPV6_HEADERS)
return FALSE;
packetInfo->ip6HomeAddrOffset = (homeAddrOffset) ? packetInfo->L2HdrLen + homeAddrOffset : 0;
packetInfo->ip6DestAddrOffset = (destAddrOffset) ? packetInfo->L2HdrLen + destAddrOffset : 0;
packetInfo->isFragment = (l4Proto == IP6_HDR_FRAGMENT);
if(!packetInfo->isFragment)
{
AnalyzeL4Proto(l4Proto, packetInfo);
}
}
return TRUE;
}
BOOLEAN ParaNdis_AnalyzeReceivedPacket(
PVOID headersBuffer,
ULONG dataLength,
PNET_PACKET_INFO packetInfo)
{
NdisZeroMemory(packetInfo, sizeof(*packetInfo));
packetInfo->headersBuffer = headersBuffer;
packetInfo->dataLength = dataLength;
if(!AnalyzeL2Hdr(packetInfo))
return FALSE;
if (!AnalyzeL3Hdr(packetInfo))
return FALSE;
return TRUE;
}
ULONG ParaNdis_StripVlanHeaderMoveHead(PNET_PACKET_INFO packetInfo)
{
PUINT32 pData = (PUINT32) packetInfo->headersBuffer;
ASSERT(packetInfo->hasVlanHeader);
ASSERT(packetInfo->L2HdrLen == ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE);
pData[3] = pData[2];
pData[2] = pData[1];
pData[1] = pData[0];
packetInfo->headersBuffer = RtlOffsetToPointer(packetInfo->headersBuffer, ETH_PRIORITY_HEADER_SIZE);
packetInfo->dataLength -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->L2HdrLen = ETH_HEADER_SIZE;
packetInfo->ethDestAddr = (PUCHAR) RtlOffsetToPointer(packetInfo->ethDestAddr, ETH_PRIORITY_HEADER_SIZE);
packetInfo->ip6DestAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
packetInfo->ip6HomeAddrOffset -= ETH_PRIORITY_HEADER_SIZE;
return ETH_PRIORITY_HEADER_SIZE;
};
VOID ParaNdis_PadPacketToMinimalLength(PNET_PACKET_INFO packetInfo)
{
// Ethernet standard declares minimal possible packet size
// Packets smaller than that must be padded before transfer
// Ethernet HW pads packets on transmit, however in our case
// some packets do not travel over Ethernet but being routed
// guest-to-guest by virtual switch.
// In this case padding is not performed and we may
// receive packet smaller than minimal allowed size. This is not
// a problem for real life scenarios however WHQL/HCK contains
// tests that check padding of received packets.
// To make these tests happy we have to pad small packets on receive
//NOTE: This function assumes that VLAN header has been already stripped out
if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE)
{
RtlZeroMemory(
RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength),
ETH_MIN_PACKET_SIZE - packetInfo->dataLength);
packetInfo->dataLength = ETH_MIN_PACKET_SIZE;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/cpp/bad_1580_3 |
crossvul-cpp_data_good_5845_10 | /*
RFCOMM implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/*
* RFCOMM sockets.
*/
#include <linux/export.h>
#include <linux/debugfs.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/l2cap.h>
#include <net/bluetooth/rfcomm.h>
static const struct proto_ops rfcomm_sock_ops;
static struct bt_sock_list rfcomm_sk_list = {
.lock = __RW_LOCK_UNLOCKED(rfcomm_sk_list.lock)
};
static void rfcomm_sock_close(struct sock *sk);
static void rfcomm_sock_kill(struct sock *sk);
/* ---- DLC callbacks ----
*
* called under rfcomm_dlc_lock()
*/
static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb)
{
struct sock *sk = d->owner;
if (!sk)
return;
atomic_add(skb->len, &sk->sk_rmem_alloc);
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk, skb->len);
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
rfcomm_dlc_throttle(d);
}
static void rfcomm_sk_state_change(struct rfcomm_dlc *d, int err)
{
struct sock *sk = d->owner, *parent;
unsigned long flags;
if (!sk)
return;
BT_DBG("dlc %p state %ld err %d", d, d->state, err);
local_irq_save(flags);
bh_lock_sock(sk);
if (err)
sk->sk_err = err;
sk->sk_state = d->state;
parent = bt_sk(sk)->parent;
if (parent) {
if (d->state == BT_CLOSED) {
sock_set_flag(sk, SOCK_ZAPPED);
bt_accept_unlink(sk);
}
parent->sk_data_ready(parent, 0);
} else {
if (d->state == BT_CONNECTED)
rfcomm_session_getaddr(d->session,
&rfcomm_pi(sk)->src, NULL);
sk->sk_state_change(sk);
}
bh_unlock_sock(sk);
local_irq_restore(flags);
if (parent && sock_flag(sk, SOCK_ZAPPED)) {
/* We have to drop DLC lock here, otherwise
* rfcomm_sock_destruct() will dead lock. */
rfcomm_dlc_unlock(d);
rfcomm_sock_kill(sk);
rfcomm_dlc_lock(d);
}
}
/* ---- Socket functions ---- */
static struct sock *__rfcomm_get_sock_by_addr(u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL;
sk_for_each(sk, &rfcomm_sk_list.head) {
if (rfcomm_pi(sk)->channel == channel &&
!bacmp(&rfcomm_pi(sk)->src, src))
break;
}
return sk ? sk : NULL;
}
/* Find socket with channel and source bdaddr.
* Returns closest match.
*/
static struct sock *rfcomm_get_sock_by_channel(int state, u8 channel, bdaddr_t *src)
{
struct sock *sk = NULL, *sk1 = NULL;
read_lock(&rfcomm_sk_list.lock);
sk_for_each(sk, &rfcomm_sk_list.head) {
if (state && sk->sk_state != state)
continue;
if (rfcomm_pi(sk)->channel == channel) {
/* Exact match. */
if (!bacmp(&rfcomm_pi(sk)->src, src))
break;
/* Closest match */
if (!bacmp(&rfcomm_pi(sk)->src, BDADDR_ANY))
sk1 = sk;
}
}
read_unlock(&rfcomm_sk_list.lock);
return sk ? sk : sk1;
}
static void rfcomm_sock_destruct(struct sock *sk)
{
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
BT_DBG("sk %p dlc %p", sk, d);
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
rfcomm_dlc_lock(d);
rfcomm_pi(sk)->dlc = NULL;
/* Detach DLC if it's owned by this socket */
if (d->owner == sk)
d->owner = NULL;
rfcomm_dlc_unlock(d);
rfcomm_dlc_put(d);
}
static void rfcomm_sock_cleanup_listen(struct sock *parent)
{
struct sock *sk;
BT_DBG("parent %p", parent);
/* Close not yet accepted dlcs */
while ((sk = bt_accept_dequeue(parent, NULL))) {
rfcomm_sock_close(sk);
rfcomm_sock_kill(sk);
}
parent->sk_state = BT_CLOSED;
sock_set_flag(parent, SOCK_ZAPPED);
}
/* Kill socket (only if zapped and orphan)
* Must be called on unlocked socket.
*/
static void rfcomm_sock_kill(struct sock *sk)
{
if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket)
return;
BT_DBG("sk %p state %d refcnt %d", sk, sk->sk_state, atomic_read(&sk->sk_refcnt));
/* Kill poor orphan */
bt_sock_unlink(&rfcomm_sk_list, sk);
sock_set_flag(sk, SOCK_DEAD);
sock_put(sk);
}
static void __rfcomm_sock_close(struct sock *sk)
{
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket);
switch (sk->sk_state) {
case BT_LISTEN:
rfcomm_sock_cleanup_listen(sk);
break;
case BT_CONNECT:
case BT_CONNECT2:
case BT_CONFIG:
case BT_CONNECTED:
rfcomm_dlc_close(d, 0);
default:
sock_set_flag(sk, SOCK_ZAPPED);
break;
}
}
/* Close socket.
* Must be called on unlocked socket.
*/
static void rfcomm_sock_close(struct sock *sk)
{
lock_sock(sk);
__rfcomm_sock_close(sk);
release_sock(sk);
}
static void rfcomm_sock_init(struct sock *sk, struct sock *parent)
{
struct rfcomm_pinfo *pi = rfcomm_pi(sk);
BT_DBG("sk %p", sk);
if (parent) {
sk->sk_type = parent->sk_type;
pi->dlc->defer_setup = test_bit(BT_SK_DEFER_SETUP,
&bt_sk(parent)->flags);
pi->sec_level = rfcomm_pi(parent)->sec_level;
pi->role_switch = rfcomm_pi(parent)->role_switch;
security_sk_clone(parent, sk);
} else {
pi->dlc->defer_setup = 0;
pi->sec_level = BT_SECURITY_LOW;
pi->role_switch = 0;
}
pi->dlc->sec_level = pi->sec_level;
pi->dlc->role_switch = pi->role_switch;
}
static struct proto rfcomm_proto = {
.name = "RFCOMM",
.owner = THIS_MODULE,
.obj_size = sizeof(struct rfcomm_pinfo)
};
static struct sock *rfcomm_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio)
{
struct rfcomm_dlc *d;
struct sock *sk;
sk = sk_alloc(net, PF_BLUETOOTH, prio, &rfcomm_proto);
if (!sk)
return NULL;
sock_init_data(sock, sk);
INIT_LIST_HEAD(&bt_sk(sk)->accept_q);
d = rfcomm_dlc_alloc(prio);
if (!d) {
sk_free(sk);
return NULL;
}
d->data_ready = rfcomm_sk_data_ready;
d->state_change = rfcomm_sk_state_change;
rfcomm_pi(sk)->dlc = d;
d->owner = sk;
sk->sk_destruct = rfcomm_sock_destruct;
sk->sk_sndtimeo = RFCOMM_CONN_TIMEOUT;
sk->sk_sndbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10;
sk->sk_rcvbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = proto;
sk->sk_state = BT_OPEN;
bt_sock_link(&rfcomm_sk_list, sk);
BT_DBG("sk %p", sk);
return sk;
}
static int rfcomm_sock_create(struct net *net, struct socket *sock,
int protocol, int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_STREAM && sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sock->ops = &rfcomm_sock_ops;
sk = rfcomm_sock_alloc(net, sock, protocol, GFP_ATOMIC);
if (!sk)
return -ENOMEM;
rfcomm_sock_init(sk, NULL);
return 0;
}
static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa->rc_channel && __rfcomm_get_sock_by_addr(sa->rc_channel, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = sa->rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int err = 0;
BT_DBG("sk %p", sk);
if (alen < sizeof(struct sockaddr_rc) ||
addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
sk->sk_state = BT_CONNECT;
bacpy(&rfcomm_pi(sk)->dst, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = sa->rc_channel;
d->sec_level = rfcomm_pi(sk)->sec_level;
d->role_switch = rfcomm_pi(sk)->role_switch;
err = rfcomm_dlc_open(d, &rfcomm_pi(sk)->src, &sa->rc_bdaddr,
sa->rc_channel);
if (!err)
err = bt_sock_wait_state(sk, BT_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
if (!rfcomm_pi(sk)->channel) {
bdaddr_t *src = &rfcomm_pi(sk)->src;
u8 channel;
err = -EINVAL;
write_lock(&rfcomm_sk_list.lock);
for (channel = 1; channel < 31; channel++)
if (!__rfcomm_get_sock_by_addr(channel, src)) {
rfcomm_pi(sk)->channel = channel;
err = 0;
break;
}
write_unlock(&rfcomm_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *nsk;
long timeo;
int err = 0;
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
BT_DBG("sk %p timeo %ld", sk, timeo);
/* Wait for an incoming connection. (wake-one). */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_state != BT_LISTEN) {
err = -EBADFD;
break;
}
nsk = bt_accept_dequeue(sk, newsock);
if (nsk)
break;
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (err)
goto done;
newsock->state = SS_CONNECTED;
BT_DBG("new socket %p", nsk);
done:
release_sock(sk);
return err;
}
static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
BT_DBG("sock %p, sk %p", sock, sk);
memset(sa, 0, sizeof(*sa));
sa->rc_family = AF_BLUETOOTH;
sa->rc_channel = rfcomm_pi(sk)->channel;
if (peer)
bacpy(&sa->rc_bdaddr, &rfcomm_pi(sk)->dst);
else
bacpy(&sa->rc_bdaddr, &rfcomm_pi(sk)->src);
*len = sizeof(struct sockaddr_rc);
return 0;
}
static int rfcomm_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
struct sk_buff *skb;
int sent;
if (test_bit(RFCOMM_DEFER_SETUP, &d->flags))
return -ENOTCONN;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (sk->sk_shutdown & SEND_SHUTDOWN)
return -EPIPE;
BT_DBG("sock %p, sk %p", sock, sk);
lock_sock(sk);
sent = bt_sock_wait_ready(sk, msg->msg_flags);
if (sent)
goto done;
while (len) {
size_t size = min_t(size_t, len, d->mtu);
int err;
skb = sock_alloc_send_skb(sk, size + RFCOMM_SKB_RESERVE,
msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb) {
if (sent == 0)
sent = err;
break;
}
skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE);
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
if (sent == 0)
sent = err;
break;
}
skb->priority = sk->sk_priority;
err = rfcomm_dlc_send(d, skb);
if (err < 0) {
kfree_skb(skb);
if (sent == 0)
sent = err;
break;
}
sent += size;
len -= size;
}
done:
release_sock(sk);
return sent;
}
static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
}
static int rfcomm_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int err = 0;
u32 opt;
BT_DBG("sk %p", sk);
lock_sock(sk);
switch (optname) {
case RFCOMM_LM:
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt & RFCOMM_LM_AUTH)
rfcomm_pi(sk)->sec_level = BT_SECURITY_LOW;
if (opt & RFCOMM_LM_ENCRYPT)
rfcomm_pi(sk)->sec_level = BT_SECURITY_MEDIUM;
if (opt & RFCOMM_LM_SECURE)
rfcomm_pi(sk)->sec_level = BT_SECURITY_HIGH;
rfcomm_pi(sk)->role_switch = (opt & RFCOMM_LM_MASTER);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int err = 0;
size_t len;
u32 opt;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_setsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = BT_SECURITY_LOW;
len = min_t(unsigned int, sizeof(sec), optlen);
if (copy_from_user((char *) &sec, optval, len)) {
err = -EFAULT;
break;
}
if (sec.level > BT_SECURITY_HIGH) {
err = -EINVAL;
break;
}
rfcomm_pi(sk)->sec_level = sec.level;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt)
set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
else
clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct rfcomm_conninfo cinfo;
struct l2cap_conn *conn = l2cap_pi(sk)->chan->conn;
int len, err = 0;
u32 opt;
BT_DBG("sk %p", sk);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case RFCOMM_LM:
switch (rfcomm_pi(sk)->sec_level) {
case BT_SECURITY_LOW:
opt = RFCOMM_LM_AUTH;
break;
case BT_SECURITY_MEDIUM:
opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT;
break;
case BT_SECURITY_HIGH:
opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT |
RFCOMM_LM_SECURE;
break;
default:
opt = 0;
break;
}
if (rfcomm_pi(sk)->role_switch)
opt |= RFCOMM_LM_MASTER;
if (put_user(opt, (u32 __user *) optval))
err = -EFAULT;
break;
case RFCOMM_CONNINFO:
if (sk->sk_state != BT_CONNECTED &&
!rfcomm_pi(sk)->dlc->defer_setup) {
err = -ENOTCONN;
break;
}
memset(&cinfo, 0, sizeof(cinfo));
cinfo.hci_handle = conn->hcon->handle;
memcpy(cinfo.dev_class, conn->hcon->dev_class, 3);
len = min_t(unsigned int, len, sizeof(cinfo));
if (copy_to_user(optval, (char *) &cinfo, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int len, err = 0;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = rfcomm_pi(sk)->sec_level;
sec.key_size = 0;
len = min_t(unsigned int, len, sizeof(sec));
if (copy_to_user(optval, (char *) &sec, len))
err = -EFAULT;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),
(u32 __user *) optval))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int rfcomm_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk __maybe_unused = sock->sk;
int err;
BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg);
err = bt_sock_ioctl(sock, cmd, arg);
if (err == -ENOIOCTLCMD) {
#ifdef CONFIG_BT_RFCOMM_TTY
lock_sock(sk);
err = rfcomm_dev_ioctl(sk, cmd, (void __user *) arg);
release_sock(sk);
#else
err = -EOPNOTSUPP;
#endif
}
return err;
}
static int rfcomm_sock_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
lock_sock(sk);
if (!sk->sk_shutdown) {
sk->sk_shutdown = SHUTDOWN_MASK;
__rfcomm_sock_close(sk);
if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime)
err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime);
}
release_sock(sk);
return err;
}
static int rfcomm_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
int err;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
err = rfcomm_sock_shutdown(sock, 2);
sock_orphan(sk);
rfcomm_sock_kill(sk);
return err;
}
/* ---- RFCOMM core layer callbacks ----
*
* called under rfcomm_lock()
*/
int rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d)
{
struct sock *sk, *parent;
bdaddr_t src, dst;
int result = 0;
BT_DBG("session %p channel %d", s, channel);
rfcomm_session_getaddr(s, &src, &dst);
/* Check if we have socket listening on channel */
parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src);
if (!parent)
return 0;
bh_lock_sock(parent);
/* Check for backlog size */
if (sk_acceptq_is_full(parent)) {
BT_DBG("backlog full %d", parent->sk_ack_backlog);
goto done;
}
sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC);
if (!sk)
goto done;
bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM);
rfcomm_sock_init(sk, parent);
bacpy(&rfcomm_pi(sk)->src, &src);
bacpy(&rfcomm_pi(sk)->dst, &dst);
rfcomm_pi(sk)->channel = channel;
sk->sk_state = BT_CONFIG;
bt_accept_enqueue(parent, sk);
/* Accept connection and return socket DLC */
*d = rfcomm_pi(sk)->dlc;
result = 1;
done:
bh_unlock_sock(parent);
if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags))
parent->sk_state_change(parent);
return result;
}
static int rfcomm_sock_debugfs_show(struct seq_file *f, void *p)
{
struct sock *sk;
read_lock(&rfcomm_sk_list.lock);
sk_for_each(sk, &rfcomm_sk_list.head) {
seq_printf(f, "%pMR %pMR %d %d\n",
&rfcomm_pi(sk)->src, &rfcomm_pi(sk)->dst,
sk->sk_state, rfcomm_pi(sk)->channel);
}
read_unlock(&rfcomm_sk_list.lock);
return 0;
}
static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, rfcomm_sock_debugfs_show, inode->i_private);
}
static const struct file_operations rfcomm_sock_debugfs_fops = {
.open = rfcomm_sock_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *rfcomm_sock_debugfs;
static const struct proto_ops rfcomm_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = rfcomm_sock_release,
.bind = rfcomm_sock_bind,
.connect = rfcomm_sock_connect,
.listen = rfcomm_sock_listen,
.accept = rfcomm_sock_accept,
.getname = rfcomm_sock_getname,
.sendmsg = rfcomm_sock_sendmsg,
.recvmsg = rfcomm_sock_recvmsg,
.shutdown = rfcomm_sock_shutdown,
.setsockopt = rfcomm_sock_setsockopt,
.getsockopt = rfcomm_sock_getsockopt,
.ioctl = rfcomm_sock_ioctl,
.poll = bt_sock_poll,
.socketpair = sock_no_socketpair,
.mmap = sock_no_mmap
};
static const struct net_proto_family rfcomm_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = rfcomm_sock_create
};
int __init rfcomm_init_sockets(void)
{
int err;
err = proto_register(&rfcomm_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_RFCOMM, &rfcomm_sock_family_ops);
if (err < 0) {
BT_ERR("RFCOMM socket layer registration failed");
goto error;
}
err = bt_procfs_init(&init_net, "rfcomm", &rfcomm_sk_list, NULL);
if (err < 0) {
BT_ERR("Failed to create RFCOMM proc file");
bt_sock_unregister(BTPROTO_RFCOMM);
goto error;
}
BT_INFO("RFCOMM socket layer initialized");
if (IS_ERR_OR_NULL(bt_debugfs))
return 0;
rfcomm_sock_debugfs = debugfs_create_file("rfcomm", 0444,
bt_debugfs, NULL,
&rfcomm_sock_debugfs_fops);
return 0;
error:
proto_unregister(&rfcomm_proto);
return err;
}
void __exit rfcomm_cleanup_sockets(void)
{
bt_procfs_cleanup(&init_net, "rfcomm");
debugfs_remove(rfcomm_sock_debugfs);
bt_sock_unregister(BTPROTO_RFCOMM);
proto_unregister(&rfcomm_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_10 |
crossvul-cpp_data_good_4728_0 | /*
* linux/kernel/fork.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* 'fork.c' contains the help-routines for the 'fork' system call
* (see also entry.S and others).
* Fork is rather simple, once you get the hang of it, but the memory
* management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
*/
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/unistd.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/personality.h>
#include <linux/mempolicy.h>
#include <linux/sem.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/iocontext.h>
#include <linux/key.h>
#include <linux/binfmts.h>
#include <linux/mman.h>
#include <linux/mmu_notifier.h>
#include <linux/fs.h>
#include <linux/nsproxy.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/cgroup.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
#include <linux/swap.h>
#include <linux/syscalls.h>
#include <linux/jiffies.h>
#include <linux/tracehook.h>
#include <linux/futex.h>
#include <linux/compat.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/rcupdate.h>
#include <linux/ptrace.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/memcontrol.h>
#include <linux/ftrace.h>
#include <linux/profile.h>
#include <linux/rmap.h>
#include <linux/ksm.h>
#include <linux/acct.h>
#include <linux/tsacct_kern.h>
#include <linux/cn_proc.h>
#include <linux/freezer.h>
#include <linux/delayacct.h>
#include <linux/taskstats_kern.h>
#include <linux/random.h>
#include <linux/tty.h>
#include <linux/proc_fs.h>
#include <linux/blkdev.h>
#include <linux/fs_struct.h>
#include <linux/magic.h>
#include <linux/perf_event.h>
#include <linux/posix-timers.h>
#include <linux/user-return-notifier.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <trace/events/sched.h>
/*
* Protected counters by write_lock_irq(&tasklist_lock)
*/
unsigned long total_forks; /* Handle normal Linux uptimes. */
int nr_threads; /* The idle threads do not count.. */
int max_threads; /* tunable limit on nr_threads */
DEFINE_PER_CPU(unsigned long, process_counts) = 0;
__cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
#ifdef CONFIG_PROVE_RCU
int lockdep_tasklist_lock_is_held(void)
{
return lockdep_is_held(&tasklist_lock);
}
EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
#endif /* #ifdef CONFIG_PROVE_RCU */
int nr_processes(void)
{
int cpu;
int total = 0;
for_each_possible_cpu(cpu)
total += per_cpu(process_counts, cpu);
return total;
}
#ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
# define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL)
# define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk))
static struct kmem_cache *task_struct_cachep;
#endif
#ifndef __HAVE_ARCH_THREAD_INFO_ALLOCATOR
static inline struct thread_info *alloc_thread_info(struct task_struct *tsk)
{
#ifdef CONFIG_DEBUG_STACK_USAGE
gfp_t mask = GFP_KERNEL | __GFP_ZERO;
#else
gfp_t mask = GFP_KERNEL;
#endif
return (struct thread_info *)__get_free_pages(mask, THREAD_SIZE_ORDER);
}
static inline void free_thread_info(struct thread_info *ti)
{
free_pages((unsigned long)ti, THREAD_SIZE_ORDER);
}
#endif
/* SLAB cache for signal_struct structures (tsk->signal) */
static struct kmem_cache *signal_cachep;
/* SLAB cache for sighand_struct structures (tsk->sighand) */
struct kmem_cache *sighand_cachep;
/* SLAB cache for files_struct structures (tsk->files) */
struct kmem_cache *files_cachep;
/* SLAB cache for fs_struct structures (tsk->fs) */
struct kmem_cache *fs_cachep;
/* SLAB cache for vm_area_struct structures */
struct kmem_cache *vm_area_cachep;
/* SLAB cache for mm_struct structures (tsk->mm) */
static struct kmem_cache *mm_cachep;
static void account_kernel_stack(struct thread_info *ti, int account)
{
struct zone *zone = page_zone(virt_to_page(ti));
mod_zone_page_state(zone, NR_KERNEL_STACK, account);
}
void free_task(struct task_struct *tsk)
{
prop_local_destroy_single(&tsk->dirties);
account_kernel_stack(tsk->stack, -1);
free_thread_info(tsk->stack);
rt_mutex_debug_task_free(tsk);
ftrace_graph_exit_task(tsk);
free_task_struct(tsk);
}
EXPORT_SYMBOL(free_task);
static inline void free_signal_struct(struct signal_struct *sig)
{
taskstats_tgid_free(sig);
kmem_cache_free(signal_cachep, sig);
}
static inline void put_signal_struct(struct signal_struct *sig)
{
if (atomic_dec_and_test(&sig->sigcnt))
free_signal_struct(sig);
}
void __put_task_struct(struct task_struct *tsk)
{
WARN_ON(!tsk->exit_state);
WARN_ON(atomic_read(&tsk->usage));
WARN_ON(tsk == current);
exit_creds(tsk);
delayacct_tsk_free(tsk);
put_signal_struct(tsk->signal);
if (!profile_handoff_task(tsk))
free_task(tsk);
}
/*
* macro override instead of weak attribute alias, to workaround
* gcc 4.1.0 and 4.1.1 bugs with weak attribute and empty functions.
*/
#ifndef arch_task_cache_init
#define arch_task_cache_init()
#endif
void __init fork_init(unsigned long mempages)
{
#ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
#ifndef ARCH_MIN_TASKALIGN
#define ARCH_MIN_TASKALIGN L1_CACHE_BYTES
#endif
/* create a slab on which task_structs can be allocated */
task_struct_cachep =
kmem_cache_create("task_struct", sizeof(struct task_struct),
ARCH_MIN_TASKALIGN, SLAB_PANIC | SLAB_NOTRACK, NULL);
#endif
/* do the arch specific task caches init */
arch_task_cache_init();
/*
* The default maximum number of threads is set to a safe
* value: the thread structures can take up at most half
* of memory.
*/
max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
/*
* we need to allow at least 20 threads to boot a system
*/
if(max_threads < 20)
max_threads = 20;
init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
init_task.signal->rlim[RLIMIT_SIGPENDING] =
init_task.signal->rlim[RLIMIT_NPROC];
}
int __attribute__((weak)) arch_dup_task_struct(struct task_struct *dst,
struct task_struct *src)
{
*dst = *src;
return 0;
}
static struct task_struct *dup_task_struct(struct task_struct *orig)
{
struct task_struct *tsk;
struct thread_info *ti;
unsigned long *stackend;
int err;
prepare_to_copy(orig);
tsk = alloc_task_struct();
if (!tsk)
return NULL;
ti = alloc_thread_info(tsk);
if (!ti) {
free_task_struct(tsk);
return NULL;
}
err = arch_dup_task_struct(tsk, orig);
if (err)
goto out;
tsk->stack = ti;
err = prop_local_init_single(&tsk->dirties);
if (err)
goto out;
setup_thread_stack(tsk, orig);
clear_user_return_notifier(tsk);
stackend = end_of_stack(tsk);
*stackend = STACK_END_MAGIC; /* for overflow detection */
#ifdef CONFIG_CC_STACKPROTECTOR
tsk->stack_canary = get_random_int();
#endif
/* One for us, one for whoever does the "release_task()" (usually parent) */
atomic_set(&tsk->usage,2);
atomic_set(&tsk->fs_excl, 0);
#ifdef CONFIG_BLK_DEV_IO_TRACE
tsk->btrace_seq = 0;
#endif
tsk->splice_pipe = NULL;
account_kernel_stack(ti, 1);
return tsk;
out:
free_thread_info(ti);
free_task_struct(tsk);
return NULL;
}
#ifdef CONFIG_MMU
static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
{
struct vm_area_struct *mpnt, *tmp, **pprev;
struct rb_node **rb_link, *rb_parent;
int retval;
unsigned long charge;
struct mempolicy *pol;
down_write(&oldmm->mmap_sem);
flush_cache_dup_mm(oldmm);
/*
* Not linked in yet - no deadlock potential:
*/
down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
mm->locked_vm = 0;
mm->mmap = NULL;
mm->mmap_cache = NULL;
mm->free_area_cache = oldmm->mmap_base;
mm->cached_hole_size = ~0UL;
mm->map_count = 0;
cpumask_clear(mm_cpumask(mm));
mm->mm_rb = RB_ROOT;
rb_link = &mm->mm_rb.rb_node;
rb_parent = NULL;
pprev = &mm->mmap;
retval = ksm_fork(mm, oldmm);
if (retval)
goto out;
for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
struct file *file;
if (mpnt->vm_flags & VM_DONTCOPY) {
long pages = vma_pages(mpnt);
mm->total_vm -= pages;
vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
-pages);
continue;
}
charge = 0;
if (mpnt->vm_flags & VM_ACCOUNT) {
unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
if (security_vm_enough_memory(len))
goto fail_nomem;
charge = len;
}
tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
if (!tmp)
goto fail_nomem;
*tmp = *mpnt;
INIT_LIST_HEAD(&tmp->anon_vma_chain);
pol = mpol_dup(vma_policy(mpnt));
retval = PTR_ERR(pol);
if (IS_ERR(pol))
goto fail_nomem_policy;
vma_set_policy(tmp, pol);
if (anon_vma_fork(tmp, mpnt))
goto fail_nomem_anon_vma_fork;
tmp->vm_flags &= ~VM_LOCKED;
tmp->vm_mm = mm;
tmp->vm_next = NULL;
file = tmp->vm_file;
if (file) {
struct inode *inode = file->f_path.dentry->d_inode;
struct address_space *mapping = file->f_mapping;
get_file(file);
if (tmp->vm_flags & VM_DENYWRITE)
atomic_dec(&inode->i_writecount);
spin_lock(&mapping->i_mmap_lock);
if (tmp->vm_flags & VM_SHARED)
mapping->i_mmap_writable++;
tmp->vm_truncate_count = mpnt->vm_truncate_count;
flush_dcache_mmap_lock(mapping);
/* insert tmp into the share list, just after mpnt */
vma_prio_tree_add(tmp, mpnt);
flush_dcache_mmap_unlock(mapping);
spin_unlock(&mapping->i_mmap_lock);
}
/*
* Clear hugetlb-related page reserves for children. This only
* affects MAP_PRIVATE mappings. Faults generated by the child
* are not guaranteed to succeed, even if read-only
*/
if (is_vm_hugetlb_page(tmp))
reset_vma_resv_huge_pages(tmp);
/*
* Link in the new vma and copy the page table entries.
*/
*pprev = tmp;
pprev = &tmp->vm_next;
__vma_link_rb(mm, tmp, rb_link, rb_parent);
rb_link = &tmp->vm_rb.rb_right;
rb_parent = &tmp->vm_rb;
mm->map_count++;
retval = copy_page_range(mm, oldmm, mpnt);
if (tmp->vm_ops && tmp->vm_ops->open)
tmp->vm_ops->open(tmp);
if (retval)
goto out;
}
/* a new mm has just been created */
arch_dup_mmap(oldmm, mm);
retval = 0;
out:
up_write(&mm->mmap_sem);
flush_tlb_mm(oldmm);
up_write(&oldmm->mmap_sem);
return retval;
fail_nomem_anon_vma_fork:
mpol_put(pol);
fail_nomem_policy:
kmem_cache_free(vm_area_cachep, tmp);
fail_nomem:
retval = -ENOMEM;
vm_unacct_memory(charge);
goto out;
}
static inline int mm_alloc_pgd(struct mm_struct * mm)
{
mm->pgd = pgd_alloc(mm);
if (unlikely(!mm->pgd))
return -ENOMEM;
return 0;
}
static inline void mm_free_pgd(struct mm_struct * mm)
{
pgd_free(mm, mm->pgd);
}
#else
#define dup_mmap(mm, oldmm) (0)
#define mm_alloc_pgd(mm) (0)
#define mm_free_pgd(mm)
#endif /* CONFIG_MMU */
__cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
#define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
#define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
static int __init coredump_filter_setup(char *s)
{
default_dump_filter =
(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
MMF_DUMP_FILTER_MASK;
return 1;
}
__setup("coredump_filter=", coredump_filter_setup);
#include <linux/init_task.h>
static void mm_init_aio(struct mm_struct *mm)
{
#ifdef CONFIG_AIO
spin_lock_init(&mm->ioctx_lock);
INIT_HLIST_HEAD(&mm->ioctx_list);
#endif
}
static struct mm_struct * mm_init(struct mm_struct * mm, struct task_struct *p)
{
atomic_set(&mm->mm_users, 1);
atomic_set(&mm->mm_count, 1);
init_rwsem(&mm->mmap_sem);
INIT_LIST_HEAD(&mm->mmlist);
mm->flags = (current->mm) ?
(current->mm->flags & MMF_INIT_MASK) : default_dump_filter;
mm->core_state = NULL;
mm->nr_ptes = 0;
memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
spin_lock_init(&mm->page_table_lock);
mm->free_area_cache = TASK_UNMAPPED_BASE;
mm->cached_hole_size = ~0UL;
mm_init_aio(mm);
mm_init_owner(mm, p);
if (likely(!mm_alloc_pgd(mm))) {
mm->def_flags = 0;
mmu_notifier_mm_init(mm);
return mm;
}
free_mm(mm);
return NULL;
}
/*
* Allocate and initialize an mm_struct.
*/
struct mm_struct * mm_alloc(void)
{
struct mm_struct * mm;
mm = allocate_mm();
if (mm) {
memset(mm, 0, sizeof(*mm));
mm = mm_init(mm, current);
}
return mm;
}
/*
* Called when the last reference to the mm
* is dropped: either by a lazy thread or by
* mmput. Free the page directory and the mm.
*/
void __mmdrop(struct mm_struct *mm)
{
BUG_ON(mm == &init_mm);
mm_free_pgd(mm);
destroy_context(mm);
mmu_notifier_mm_destroy(mm);
free_mm(mm);
}
EXPORT_SYMBOL_GPL(__mmdrop);
/*
* Decrement the use count and release all resources for an mm.
*/
void mmput(struct mm_struct *mm)
{
might_sleep();
if (atomic_dec_and_test(&mm->mm_users)) {
exit_aio(mm);
ksm_exit(mm);
exit_mmap(mm);
set_mm_exe_file(mm, NULL);
if (!list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
list_del(&mm->mmlist);
spin_unlock(&mmlist_lock);
}
put_swap_token(mm);
if (mm->binfmt)
module_put(mm->binfmt->module);
mmdrop(mm);
}
}
EXPORT_SYMBOL_GPL(mmput);
/**
* get_task_mm - acquire a reference to the task's mm
*
* Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
* this kernel workthread has transiently adopted a user mm with use_mm,
* to do its AIO) is not set and if so returns a reference to it, after
* bumping up the use count. User must release the mm via mmput()
* after use. Typically used by /proc and ptrace.
*/
struct mm_struct *get_task_mm(struct task_struct *task)
{
struct mm_struct *mm;
task_lock(task);
mm = task->mm;
if (mm) {
if (task->flags & PF_KTHREAD)
mm = NULL;
else
atomic_inc(&mm->mm_users);
}
task_unlock(task);
return mm;
}
EXPORT_SYMBOL_GPL(get_task_mm);
/* Please note the differences between mmput and mm_release.
* mmput is called whenever we stop holding onto a mm_struct,
* error success whatever.
*
* mm_release is called after a mm_struct has been removed
* from the current process.
*
* This difference is important for error handling, when we
* only half set up a mm_struct for a new process and need to restore
* the old one. Because we mmput the new mm_struct before
* restoring the old one. . .
* Eric Biederman 10 January 1998
*/
void mm_release(struct task_struct *tsk, struct mm_struct *mm)
{
struct completion *vfork_done = tsk->vfork_done;
/* Get rid of any futexes when releasing the mm */
#ifdef CONFIG_FUTEX
if (unlikely(tsk->robust_list)) {
exit_robust_list(tsk);
tsk->robust_list = NULL;
}
#ifdef CONFIG_COMPAT
if (unlikely(tsk->compat_robust_list)) {
compat_exit_robust_list(tsk);
tsk->compat_robust_list = NULL;
}
#endif
if (unlikely(!list_empty(&tsk->pi_state_list)))
exit_pi_state_list(tsk);
#endif
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
/* notify parent sleeping on vfork() */
if (vfork_done) {
tsk->vfork_done = NULL;
complete(vfork_done);
}
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
* trouble otherwise. Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid) {
if (!(tsk->flags & PF_SIGNALED) &&
atomic_read(&mm->mm_users) > 1) {
/*
* We don't check the error code - if userspace has
* not set up a proper pointer then tough luck.
*/
put_user(0, tsk->clear_child_tid);
sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
1, NULL, NULL, 0);
}
tsk->clear_child_tid = NULL;
}
}
/*
* Allocate a new mm structure and copy contents from the
* mm structure of the passed in task structure.
*/
struct mm_struct *dup_mm(struct task_struct *tsk)
{
struct mm_struct *mm, *oldmm = current->mm;
int err;
if (!oldmm)
return NULL;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
if (!mm_init(mm, tsk))
goto fail_nomem;
if (init_new_context(tsk, mm))
goto fail_nocontext;
dup_mm_exe_file(oldmm, mm);
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
mm->hiwater_rss = get_mm_rss(mm);
mm->hiwater_vm = mm->total_vm;
if (mm->binfmt && !try_module_get(mm->binfmt->module))
goto free_pt;
return mm;
free_pt:
/* don't put binfmt in mmput, we haven't got module yet */
mm->binfmt = NULL;
mmput(mm);
fail_nomem:
return NULL;
fail_nocontext:
/*
* If init_new_context() failed, we cannot use mmput() to free the mm
* because it calls destroy_context()
*/
mm_free_pgd(mm);
free_mm(mm);
return NULL;
}
static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
{
struct mm_struct * mm, *oldmm;
int retval;
tsk->min_flt = tsk->maj_flt = 0;
tsk->nvcsw = tsk->nivcsw = 0;
#ifdef CONFIG_DETECT_HUNG_TASK
tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
#endif
tsk->mm = NULL;
tsk->active_mm = NULL;
/*
* Are we cloning a kernel thread?
*
* We need to steal a active VM for that..
*/
oldmm = current->mm;
if (!oldmm)
return 0;
if (clone_flags & CLONE_VM) {
atomic_inc(&oldmm->mm_users);
mm = oldmm;
goto good_mm;
}
retval = -ENOMEM;
mm = dup_mm(tsk);
if (!mm)
goto fail_nomem;
good_mm:
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
tsk->mm = mm;
tsk->active_mm = mm;
return 0;
fail_nomem:
return retval;
}
static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
{
struct fs_struct *fs = current->fs;
if (clone_flags & CLONE_FS) {
/* tsk->fs is already what we want */
write_lock(&fs->lock);
if (fs->in_exec) {
write_unlock(&fs->lock);
return -EAGAIN;
}
fs->users++;
write_unlock(&fs->lock);
return 0;
}
tsk->fs = copy_fs_struct(fs);
if (!tsk->fs)
return -ENOMEM;
return 0;
}
static int copy_files(unsigned long clone_flags, struct task_struct * tsk)
{
struct files_struct *oldf, *newf;
int error = 0;
/*
* A background process may not have any files ...
*/
oldf = current->files;
if (!oldf)
goto out;
if (clone_flags & CLONE_FILES) {
atomic_inc(&oldf->count);
goto out;
}
newf = dup_fd(oldf, &error);
if (!newf)
goto out;
tsk->files = newf;
error = 0;
out:
return error;
}
static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
{
#ifdef CONFIG_BLOCK
struct io_context *ioc = current->io_context;
if (!ioc)
return 0;
/*
* Share io context with parent, if CLONE_IO is set
*/
if (clone_flags & CLONE_IO) {
tsk->io_context = ioc_task_link(ioc);
if (unlikely(!tsk->io_context))
return -ENOMEM;
} else if (ioprio_valid(ioc->ioprio)) {
tsk->io_context = alloc_io_context(GFP_KERNEL, -1);
if (unlikely(!tsk->io_context))
return -ENOMEM;
tsk->io_context->ioprio = ioc->ioprio;
}
#endif
return 0;
}
static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
{
struct sighand_struct *sig;
if (clone_flags & CLONE_SIGHAND) {
atomic_inc(¤t->sighand->count);
return 0;
}
sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
rcu_assign_pointer(tsk->sighand, sig);
if (!sig)
return -ENOMEM;
atomic_set(&sig->count, 1);
memcpy(sig->action, current->sighand->action, sizeof(sig->action));
return 0;
}
void __cleanup_sighand(struct sighand_struct *sighand)
{
if (atomic_dec_and_test(&sighand->count))
kmem_cache_free(sighand_cachep, sighand);
}
/*
* Initialize POSIX timer handling for a thread group.
*/
static void posix_cpu_timers_init_group(struct signal_struct *sig)
{
unsigned long cpu_limit;
/* Thread group counters. */
thread_group_cputime_init(sig);
cpu_limit = ACCESS_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
if (cpu_limit != RLIM_INFINITY) {
sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
sig->cputimer.running = 1;
}
/* The timer lists. */
INIT_LIST_HEAD(&sig->cpu_timers[0]);
INIT_LIST_HEAD(&sig->cpu_timers[1]);
INIT_LIST_HEAD(&sig->cpu_timers[2]);
}
static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
{
struct signal_struct *sig;
if (clone_flags & CLONE_THREAD)
return 0;
sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
tsk->signal = sig;
if (!sig)
return -ENOMEM;
sig->nr_threads = 1;
atomic_set(&sig->live, 1);
atomic_set(&sig->sigcnt, 1);
init_waitqueue_head(&sig->wait_chldexit);
if (clone_flags & CLONE_NEWPID)
sig->flags |= SIGNAL_UNKILLABLE;
sig->curr_target = tsk;
init_sigpending(&sig->shared_pending);
INIT_LIST_HEAD(&sig->posix_timers);
hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
sig->real_timer.function = it_real_fn;
task_lock(current->group_leader);
memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
task_unlock(current->group_leader);
posix_cpu_timers_init_group(sig);
tty_audit_fork(sig);
sig->oom_adj = current->signal->oom_adj;
return 0;
}
static void copy_flags(unsigned long clone_flags, struct task_struct *p)
{
unsigned long new_flags = p->flags;
new_flags &= ~PF_SUPERPRIV;
new_flags |= PF_FORKNOEXEC;
new_flags |= PF_STARTING;
p->flags = new_flags;
clear_freeze_flag(p);
}
SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
{
current->clear_child_tid = tidptr;
return task_pid_vnr(current);
}
static void rt_mutex_init_task(struct task_struct *p)
{
raw_spin_lock_init(&p->pi_lock);
#ifdef CONFIG_RT_MUTEXES
plist_head_init_raw(&p->pi_waiters, &p->pi_lock);
p->pi_blocked_on = NULL;
#endif
}
#ifdef CONFIG_MM_OWNER
void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
{
mm->owner = p;
}
#endif /* CONFIG_MM_OWNER */
/*
* Initialize POSIX timer handling for a single task.
*/
static void posix_cpu_timers_init(struct task_struct *tsk)
{
tsk->cputime_expires.prof_exp = cputime_zero;
tsk->cputime_expires.virt_exp = cputime_zero;
tsk->cputime_expires.sched_exp = 0;
INIT_LIST_HEAD(&tsk->cpu_timers[0]);
INIT_LIST_HEAD(&tsk->cpu_timers[1]);
INIT_LIST_HEAD(&tsk->cpu_timers[2]);
}
/*
* This creates a new process as a copy of the old one,
* but does not actually start it yet.
*
* It copies the registers, and all the appropriate
* parts of the process environment (as per the clone
* flags). The actual kick-off is left to the caller.
*/
static struct task_struct *copy_process(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *child_tidptr,
struct pid *pid,
int trace)
{
int retval;
struct task_struct *p;
int cgroup_callbacks_done = 0;
if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
return ERR_PTR(-EINVAL);
/*
* Thread groups must share signals as well, and detached threads
* can only be started up within the thread group.
*/
if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
return ERR_PTR(-EINVAL);
/*
* Shared signal handlers imply shared VM. By way of the above,
* thread groups also imply shared VM. Blocking this case allows
* for various simplifications in other code.
*/
if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
return ERR_PTR(-EINVAL);
/*
* Siblings of global init remain as zombies on exit since they are
* not reaped by their parent (swapper). To solve this and to avoid
* multi-rooted process trees, prevent global and container-inits
* from creating siblings.
*/
if ((clone_flags & CLONE_PARENT) &&
current->signal->flags & SIGNAL_UNKILLABLE)
return ERR_PTR(-EINVAL);
retval = security_task_create(clone_flags);
if (retval)
goto fork_out;
retval = -ENOMEM;
p = dup_task_struct(current);
if (!p)
goto fork_out;
ftrace_graph_init_task(p);
rt_mutex_init_task(p);
#ifdef CONFIG_PROVE_LOCKING
DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
retval = -EAGAIN;
if (atomic_read(&p->real_cred->user->processes) >=
task_rlimit(p, RLIMIT_NPROC)) {
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
p->real_cred->user != INIT_USER)
goto bad_fork_free;
}
retval = copy_creds(p, clone_flags);
if (retval < 0)
goto bad_fork_free;
/*
* If multiple threads are within copy_process(), then this check
* triggers too late. This doesn't hurt, the check is only there
* to stop root fork bombs.
*/
retval = -EAGAIN;
if (nr_threads >= max_threads)
goto bad_fork_cleanup_count;
if (!try_module_get(task_thread_info(p)->exec_domain->module))
goto bad_fork_cleanup_count;
p->did_exec = 0;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
copy_flags(clone_flags, p);
INIT_LIST_HEAD(&p->children);
INIT_LIST_HEAD(&p->sibling);
rcu_copy_process(p);
p->vfork_done = NULL;
spin_lock_init(&p->alloc_lock);
init_sigpending(&p->pending);
p->utime = cputime_zero;
p->stime = cputime_zero;
p->gtime = cputime_zero;
p->utimescaled = cputime_zero;
p->stimescaled = cputime_zero;
#ifndef CONFIG_VIRT_CPU_ACCOUNTING
p->prev_utime = cputime_zero;
p->prev_stime = cputime_zero;
#endif
#if defined(SPLIT_RSS_COUNTING)
memset(&p->rss_stat, 0, sizeof(p->rss_stat));
#endif
p->default_timer_slack_ns = current->timer_slack_ns;
task_io_accounting_init(&p->ioac);
acct_clear_integrals(p);
posix_cpu_timers_init(p);
p->lock_depth = -1; /* -1 = no lock */
do_posix_clock_monotonic_gettime(&p->start_time);
p->real_start_time = p->start_time;
monotonic_to_bootbased(&p->real_start_time);
p->io_context = NULL;
p->audit_context = NULL;
cgroup_fork(p);
#ifdef CONFIG_NUMA
p->mempolicy = mpol_dup(p->mempolicy);
if (IS_ERR(p->mempolicy)) {
retval = PTR_ERR(p->mempolicy);
p->mempolicy = NULL;
goto bad_fork_cleanup_cgroup;
}
mpol_fix_fork_child_flag(p);
#endif
#ifdef CONFIG_CPUSETS
p->cpuset_mem_spread_rotor = node_random(p->mems_allowed);
p->cpuset_slab_spread_rotor = node_random(p->mems_allowed);
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
p->irq_events = 0;
#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
p->hardirqs_enabled = 1;
#else
p->hardirqs_enabled = 0;
#endif
p->hardirq_enable_ip = 0;
p->hardirq_enable_event = 0;
p->hardirq_disable_ip = _THIS_IP_;
p->hardirq_disable_event = 0;
p->softirqs_enabled = 1;
p->softirq_enable_ip = _THIS_IP_;
p->softirq_enable_event = 0;
p->softirq_disable_ip = 0;
p->softirq_disable_event = 0;
p->hardirq_context = 0;
p->softirq_context = 0;
#endif
#ifdef CONFIG_LOCKDEP
p->lockdep_depth = 0; /* no locks held yet */
p->curr_chain_key = 0;
p->lockdep_recursion = 0;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
p->blocked_on = NULL; /* not blocked yet */
#endif
#ifdef CONFIG_CGROUP_MEM_RES_CTLR
p->memcg_batch.do_batch = 0;
p->memcg_batch.memcg = NULL;
#endif
/* Perform scheduler related setup. Assign this task to a CPU. */
sched_fork(p, clone_flags);
retval = perf_event_init_task(p);
if (retval)
goto bad_fork_cleanup_policy;
if ((retval = audit_alloc(p)))
goto bad_fork_cleanup_policy;
/* copy all the process information */
if ((retval = copy_semundo(clone_flags, p)))
goto bad_fork_cleanup_audit;
if ((retval = copy_files(clone_flags, p)))
goto bad_fork_cleanup_semundo;
if ((retval = copy_fs(clone_flags, p)))
goto bad_fork_cleanup_files;
if ((retval = copy_sighand(clone_flags, p)))
goto bad_fork_cleanup_fs;
if ((retval = copy_signal(clone_flags, p)))
goto bad_fork_cleanup_sighand;
if ((retval = copy_mm(clone_flags, p)))
goto bad_fork_cleanup_signal;
if ((retval = copy_namespaces(clone_flags, p)))
goto bad_fork_cleanup_mm;
if ((retval = copy_io(clone_flags, p)))
goto bad_fork_cleanup_namespaces;
retval = copy_thread(clone_flags, stack_start, stack_size, p, regs);
if (retval)
goto bad_fork_cleanup_io;
if (pid != &init_struct_pid) {
retval = -ENOMEM;
pid = alloc_pid(p->nsproxy->pid_ns);
if (!pid)
goto bad_fork_cleanup_io;
if (clone_flags & CLONE_NEWPID) {
retval = pid_ns_prepare_proc(p->nsproxy->pid_ns);
if (retval < 0)
goto bad_fork_free_pid;
}
}
p->pid = pid_nr(pid);
p->tgid = p->pid;
if (clone_flags & CLONE_THREAD)
p->tgid = current->tgid;
if (current->nsproxy != p->nsproxy) {
retval = ns_cgroup_clone(p, pid);
if (retval)
goto bad_fork_free_pid;
}
p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
/*
* Clear TID on mm_release()?
*/
p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
#ifdef CONFIG_FUTEX
p->robust_list = NULL;
#ifdef CONFIG_COMPAT
p->compat_robust_list = NULL;
#endif
INIT_LIST_HEAD(&p->pi_state_list);
p->pi_state_cache = NULL;
#endif
/*
* sigaltstack should be cleared when sharing the same VM
*/
if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
p->sas_ss_sp = p->sas_ss_size = 0;
/*
* Syscall tracing and stepping should be turned off in the
* child regardless of CLONE_PTRACE.
*/
user_disable_single_step(p);
clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
#ifdef TIF_SYSCALL_EMU
clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
#endif
clear_all_latency_tracing(p);
/* ok, now we should be set up.. */
p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
p->pdeath_signal = 0;
p->exit_state = 0;
/*
* Ok, make it visible to the rest of the system.
* We dont wake it up yet.
*/
p->group_leader = p;
INIT_LIST_HEAD(&p->thread_group);
/* Now that the task is set up, run cgroup callbacks if
* necessary. We need to run them before the task is visible
* on the tasklist. */
cgroup_fork_callbacks(p);
cgroup_callbacks_done = 1;
/* Need tasklist lock for parent etc handling! */
write_lock_irq(&tasklist_lock);
/* CLONE_PARENT re-uses the old parent */
if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
p->real_parent = current->real_parent;
p->parent_exec_id = current->parent_exec_id;
} else {
p->real_parent = current;
p->parent_exec_id = current->self_exec_id;
}
spin_lock(¤t->sighand->siglock);
/*
* Process group and session signals need to be delivered to just the
* parent before the fork or both the parent and the child after the
* fork. Restart if a signal comes in before we add the new process to
* it's process group.
* A fatal signal pending means that current will exit, so the new
* thread can't slip out of an OOM kill (or normal SIGKILL).
*/
recalc_sigpending();
if (signal_pending(current)) {
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
retval = -ERESTARTNOINTR;
goto bad_fork_free_pid;
}
if (clone_flags & CLONE_THREAD) {
current->signal->nr_threads++;
atomic_inc(¤t->signal->live);
atomic_inc(¤t->signal->sigcnt);
p->group_leader = current->group_leader;
list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);
}
if (likely(p->pid)) {
tracehook_finish_clone(p, clone_flags, trace);
if (thread_group_leader(p)) {
if (clone_flags & CLONE_NEWPID)
p->nsproxy->pid_ns->child_reaper = p;
p->signal->leader_pid = pid;
p->signal->tty = tty_kref_get(current->signal->tty);
attach_pid(p, PIDTYPE_PGID, task_pgrp(current));
attach_pid(p, PIDTYPE_SID, task_session(current));
list_add_tail(&p->sibling, &p->real_parent->children);
list_add_tail_rcu(&p->tasks, &init_task.tasks);
__get_cpu_var(process_counts)++;
}
attach_pid(p, PIDTYPE_PID, pid);
nr_threads++;
}
total_forks++;
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
proc_fork_connector(p);
cgroup_post_fork(p);
perf_event_fork(p);
return p;
bad_fork_free_pid:
if (pid != &init_struct_pid)
free_pid(pid);
bad_fork_cleanup_io:
if (p->io_context)
exit_io_context(p);
bad_fork_cleanup_namespaces:
exit_task_namespaces(p);
bad_fork_cleanup_mm:
if (p->mm)
mmput(p->mm);
bad_fork_cleanup_signal:
if (!(clone_flags & CLONE_THREAD))
free_signal_struct(p->signal);
bad_fork_cleanup_sighand:
__cleanup_sighand(p->sighand);
bad_fork_cleanup_fs:
exit_fs(p); /* blocking */
bad_fork_cleanup_files:
exit_files(p); /* blocking */
bad_fork_cleanup_semundo:
exit_sem(p);
bad_fork_cleanup_audit:
audit_free(p);
bad_fork_cleanup_policy:
perf_event_free_task(p);
#ifdef CONFIG_NUMA
mpol_put(p->mempolicy);
bad_fork_cleanup_cgroup:
#endif
cgroup_exit(p, cgroup_callbacks_done);
delayacct_tsk_free(p);
module_put(task_thread_info(p)->exec_domain->module);
bad_fork_cleanup_count:
atomic_dec(&p->cred->user->processes);
exit_creds(p);
bad_fork_free:
free_task(p);
fork_out:
return ERR_PTR(retval);
}
noinline struct pt_regs * __cpuinit __attribute__((weak)) idle_regs(struct pt_regs *regs)
{
memset(regs, 0, sizeof(struct pt_regs));
return regs;
}
static inline void init_idle_pids(struct pid_link *links)
{
enum pid_type type;
for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
INIT_HLIST_NODE(&links[type].node); /* not really needed */
links[type].pid = &init_struct_pid;
}
}
struct task_struct * __cpuinit fork_idle(int cpu)
{
struct task_struct *task;
struct pt_regs regs;
task = copy_process(CLONE_VM, 0, idle_regs(®s), 0, NULL,
&init_struct_pid, 0);
if (!IS_ERR(task)) {
init_idle_pids(task->pids);
init_idle(task, cpu);
}
return task;
}
/*
* Ok, this is the main fork-routine.
*
* It copies the process, and if successful kick-starts
* it and waits for it to finish using the VM if required.
*/
long do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *parent_tidptr,
int __user *child_tidptr)
{
struct task_struct *p;
int trace = 0;
long nr;
/*
* Do some preliminary argument and permissions checking before we
* actually start allocating stuff
*/
if (clone_flags & CLONE_NEWUSER) {
if (clone_flags & CLONE_THREAD)
return -EINVAL;
/* hopefully this check will go away when userns support is
* complete
*/
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SETUID) ||
!capable(CAP_SETGID))
return -EPERM;
}
/*
* We hope to recycle these flags after 2.6.26
*/
if (unlikely(clone_flags & CLONE_STOPPED)) {
static int __read_mostly count = 100;
if (count > 0 && printk_ratelimit()) {
char comm[TASK_COMM_LEN];
count--;
printk(KERN_INFO "fork(): process `%s' used deprecated "
"clone flags 0x%lx\n",
get_task_comm(comm, current),
clone_flags & CLONE_STOPPED);
}
}
/*
* When called from kernel_thread, don't do user tracing stuff.
*/
if (likely(user_mode(regs)))
trace = tracehook_prepare_clone(clone_flags);
p = copy_process(clone_flags, stack_start, regs, stack_size,
child_tidptr, NULL, trace);
/*
* Do this prior waking up the new thread - the thread pointer
* might get invalid after that point, if the thread exits quickly.
*/
if (!IS_ERR(p)) {
struct completion vfork;
trace_sched_process_fork(current, p);
nr = task_pid_vnr(p);
if (clone_flags & CLONE_PARENT_SETTID)
put_user(nr, parent_tidptr);
if (clone_flags & CLONE_VFORK) {
p->vfork_done = &vfork;
init_completion(&vfork);
}
audit_finish_fork(p);
tracehook_report_clone(regs, clone_flags, nr, p);
/*
* We set PF_STARTING at creation in case tracing wants to
* use this to distinguish a fully live task from one that
* hasn't gotten to tracehook_report_clone() yet. Now we
* clear it and set the child going.
*/
p->flags &= ~PF_STARTING;
if (unlikely(clone_flags & CLONE_STOPPED)) {
/*
* We'll start up with an immediate SIGSTOP.
*/
sigaddset(&p->pending.signal, SIGSTOP);
set_tsk_thread_flag(p, TIF_SIGPENDING);
__set_task_state(p, TASK_STOPPED);
} else {
wake_up_new_task(p, clone_flags);
}
tracehook_report_clone_complete(trace, regs,
clone_flags, nr, p);
if (clone_flags & CLONE_VFORK) {
freezer_do_not_count();
wait_for_completion(&vfork);
freezer_count();
tracehook_report_vfork_done(p, nr);
}
} else {
nr = PTR_ERR(p);
}
return nr;
}
#ifndef ARCH_MIN_MMSTRUCT_ALIGN
#define ARCH_MIN_MMSTRUCT_ALIGN 0
#endif
static void sighand_ctor(void *data)
{
struct sighand_struct *sighand = data;
spin_lock_init(&sighand->siglock);
init_waitqueue_head(&sighand->signalfd_wqh);
}
void __init proc_caches_init(void)
{
sighand_cachep = kmem_cache_create("sighand_cache",
sizeof(struct sighand_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
SLAB_NOTRACK, sighand_ctor);
signal_cachep = kmem_cache_create("signal_cache",
sizeof(struct signal_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
files_cachep = kmem_cache_create("files_cache",
sizeof(struct files_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
fs_cachep = kmem_cache_create("fs_cache",
sizeof(struct fs_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
mm_cachep = kmem_cache_create("mm_struct",
sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC);
mmap_init();
}
/*
* Check constraints on flags passed to the unshare system call and
* force unsharing of additional process context as appropriate.
*/
static void check_unshare_flags(unsigned long *flags_ptr)
{
/*
* If unsharing a thread from a thread group, must also
* unshare vm.
*/
if (*flags_ptr & CLONE_THREAD)
*flags_ptr |= CLONE_VM;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (*flags_ptr & CLONE_VM)
*flags_ptr |= CLONE_SIGHAND;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (*flags_ptr & CLONE_NEWNS)
*flags_ptr |= CLONE_FS;
}
/*
* Unsharing of tasks created with CLONE_THREAD is not supported yet
*/
static int unshare_thread(unsigned long unshare_flags)
{
if (unshare_flags & CLONE_THREAD)
return -EINVAL;
return 0;
}
/*
* Unshare the filesystem structure if it is being shared
*/
static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
{
struct fs_struct *fs = current->fs;
if (!(unshare_flags & CLONE_FS) || !fs)
return 0;
/* don't need lock here; in the worst case we'll do useless copy */
if (fs->users == 1)
return 0;
*new_fsp = copy_fs_struct(fs);
if (!*new_fsp)
return -ENOMEM;
return 0;
}
/*
* Unsharing of sighand is not supported yet
*/
static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp)
{
struct sighand_struct *sigh = current->sighand;
if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1)
return -EINVAL;
else
return 0;
}
/*
* Unshare vm if it is being shared
*/
static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp)
{
struct mm_struct *mm = current->mm;
if ((unshare_flags & CLONE_VM) &&
(mm && atomic_read(&mm->mm_users) > 1)) {
return -EINVAL;
}
return 0;
}
/*
* Unshare file descriptor table if it is being shared
*/
static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
{
struct files_struct *fd = current->files;
int error = 0;
if ((unshare_flags & CLONE_FILES) &&
(fd && atomic_read(&fd->count) > 1)) {
*new_fdp = dup_fd(fd, &error);
if (!*new_fdp)
return error;
}
return 0;
}
/*
* unshare allows a process to 'unshare' part of the process
* context which was originally shared using clone. copy_*
* functions used by do_fork() cannot be used here directly
* because they modify an inactive task_struct that is being
* constructed. Here we are modifying the current, active,
* task_struct.
*/
SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
{
int err = 0;
struct fs_struct *fs, *new_fs = NULL;
struct sighand_struct *new_sigh = NULL;
struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL;
struct files_struct *fd, *new_fd = NULL;
struct nsproxy *new_nsproxy = NULL;
int do_sysvsem = 0;
check_unshare_flags(&unshare_flags);
/* Return -EINVAL for all unsupported flags */
err = -EINVAL;
if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET))
goto bad_unshare_out;
/*
* CLONE_NEWIPC must also detach from the undolist: after switching
* to a new ipc namespace, the semaphore arrays from the old
* namespace are unreachable.
*/
if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
do_sysvsem = 1;
if ((err = unshare_thread(unshare_flags)))
goto bad_unshare_out;
if ((err = unshare_fs(unshare_flags, &new_fs)))
goto bad_unshare_cleanup_thread;
if ((err = unshare_sighand(unshare_flags, &new_sigh)))
goto bad_unshare_cleanup_fs;
if ((err = unshare_vm(unshare_flags, &new_mm)))
goto bad_unshare_cleanup_sigh;
if ((err = unshare_fd(unshare_flags, &new_fd)))
goto bad_unshare_cleanup_vm;
if ((err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
new_fs)))
goto bad_unshare_cleanup_fd;
if (new_fs || new_mm || new_fd || do_sysvsem || new_nsproxy) {
if (do_sysvsem) {
/*
* CLONE_SYSVSEM is equivalent to sys_exit().
*/
exit_sem(current);
}
if (new_nsproxy) {
switch_task_namespaces(current, new_nsproxy);
new_nsproxy = NULL;
}
task_lock(current);
if (new_fs) {
fs = current->fs;
write_lock(&fs->lock);
current->fs = new_fs;
if (--fs->users)
new_fs = NULL;
else
new_fs = fs;
write_unlock(&fs->lock);
}
if (new_mm) {
mm = current->mm;
active_mm = current->active_mm;
current->mm = new_mm;
current->active_mm = new_mm;
activate_mm(active_mm, new_mm);
new_mm = mm;
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
}
if (new_nsproxy)
put_nsproxy(new_nsproxy);
bad_unshare_cleanup_fd:
if (new_fd)
put_files_struct(new_fd);
bad_unshare_cleanup_vm:
if (new_mm)
mmput(new_mm);
bad_unshare_cleanup_sigh:
if (new_sigh)
if (atomic_dec_and_test(&new_sigh->count))
kmem_cache_free(sighand_cachep, new_sigh);
bad_unshare_cleanup_fs:
if (new_fs)
free_fs_struct(new_fs);
bad_unshare_cleanup_thread:
bad_unshare_out:
return err;
}
/*
* Helper to unshare the files of the current task.
* We don't want to expose copy_files internals to
* the exec layer of the kernel.
*/
int unshare_files(struct files_struct **displaced)
{
struct task_struct *task = current;
struct files_struct *copy = NULL;
int error;
error = unshare_fd(CLONE_FILES, ©);
if (error || !copy) {
*displaced = NULL;
return error;
}
*displaced = task->files;
task_lock(task);
task->files = copy;
task_unlock(task);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4728_0 |
crossvul-cpp_data_bad_2109_0 | /*
* DCCP connection tracking protocol helper
*
* Copyright (c) 2005, 2006, 2008 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sysctl.h>
#include <linux/spinlock.h>
#include <linux/skbuff.h>
#include <linux/dccp.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <linux/netfilter/nfnetlink_conntrack.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_ecache.h>
#include <net/netfilter/nf_log.h>
/* Timeouts are based on values from RFC4340:
*
* - REQUEST:
*
* 8.1.2. Client Request
*
* A client MAY give up on its DCCP-Requests after some time
* (3 minutes, for example).
*
* - RESPOND:
*
* 8.1.3. Server Response
*
* It MAY also leave the RESPOND state for CLOSED after a timeout of
* not less than 4MSL (8 minutes);
*
* - PARTOPEN:
*
* 8.1.5. Handshake Completion
*
* If the client remains in PARTOPEN for more than 4MSL (8 minutes),
* it SHOULD reset the connection with Reset Code 2, "Aborted".
*
* - OPEN:
*
* The DCCP timestamp overflows after 11.9 hours. If the connection
* stays idle this long the sequence number won't be recognized
* as valid anymore.
*
* - CLOSEREQ/CLOSING:
*
* 8.3. Termination
*
* The retransmission timer should initially be set to go off in two
* round-trip times and should back off to not less than once every
* 64 seconds ...
*
* - TIMEWAIT:
*
* 4.3. States
*
* A server or client socket remains in this state for 2MSL (4 minutes)
* after the connection has been town down, ...
*/
#define DCCP_MSL (2 * 60 * HZ)
static const char * const dccp_state_names[] = {
[CT_DCCP_NONE] = "NONE",
[CT_DCCP_REQUEST] = "REQUEST",
[CT_DCCP_RESPOND] = "RESPOND",
[CT_DCCP_PARTOPEN] = "PARTOPEN",
[CT_DCCP_OPEN] = "OPEN",
[CT_DCCP_CLOSEREQ] = "CLOSEREQ",
[CT_DCCP_CLOSING] = "CLOSING",
[CT_DCCP_TIMEWAIT] = "TIMEWAIT",
[CT_DCCP_IGNORE] = "IGNORE",
[CT_DCCP_INVALID] = "INVALID",
};
#define sNO CT_DCCP_NONE
#define sRQ CT_DCCP_REQUEST
#define sRS CT_DCCP_RESPOND
#define sPO CT_DCCP_PARTOPEN
#define sOP CT_DCCP_OPEN
#define sCR CT_DCCP_CLOSEREQ
#define sCG CT_DCCP_CLOSING
#define sTW CT_DCCP_TIMEWAIT
#define sIG CT_DCCP_IGNORE
#define sIV CT_DCCP_INVALID
/*
* DCCP state transition table
*
* The assumption is the same as for TCP tracking:
*
* We are the man in the middle. All the packets go through us but might
* get lost in transit to the destination. It is assumed that the destination
* can't receive segments we haven't seen.
*
* The following states exist:
*
* NONE: Initial state, expecting Request
* REQUEST: Request seen, waiting for Response from server
* RESPOND: Response from server seen, waiting for Ack from client
* PARTOPEN: Ack after Response seen, waiting for packet other than Response,
* Reset or Sync from server
* OPEN: Packet other than Response, Reset or Sync seen
* CLOSEREQ: CloseReq from server seen, expecting Close from client
* CLOSING: Close seen, expecting Reset
* TIMEWAIT: Reset seen
* IGNORE: Not determinable whether packet is valid
*
* Some states exist only on one side of the connection: REQUEST, RESPOND,
* PARTOPEN, CLOSEREQ. For the other side these states are equivalent to
* the one it was in before.
*
* Packets are marked as ignored (sIG) if we don't know if they're valid
* (for example a reincarnation of a connection we didn't notice is dead
* already) and the server may send back a connection closing Reset or a
* Response. They're also used for Sync/SyncAck packets, which we don't
* care about.
*/
static const u_int8_t
dccp_state_table[CT_DCCP_ROLE_MAX + 1][DCCP_PKT_SYNCACK + 1][CT_DCCP_MAX + 1] = {
[CT_DCCP_ROLE_CLIENT] = {
[DCCP_PKT_REQUEST] = {
/*
* sNO -> sRQ Regular Request
* sRQ -> sRQ Retransmitted Request or reincarnation
* sRS -> sRS Retransmitted Request (apparently Response
* got lost after we saw it) or reincarnation
* sPO -> sIG Ignore, conntrack might be out of sync
* sOP -> sIG Ignore, conntrack might be out of sync
* sCR -> sIG Ignore, conntrack might be out of sync
* sCG -> sIG Ignore, conntrack might be out of sync
* sTW -> sRQ Reincarnation
*
* sNO, sRQ, sRS, sPO. sOP, sCR, sCG, sTW, */
sRQ, sRQ, sRS, sIG, sIG, sIG, sIG, sRQ,
},
[DCCP_PKT_RESPONSE] = {
/*
* sNO -> sIV Invalid
* sRQ -> sIG Ignore, might be response to ignored Request
* sRS -> sIG Ignore, might be response to ignored Request
* sPO -> sIG Ignore, might be response to ignored Request
* sOP -> sIG Ignore, might be response to ignored Request
* sCR -> sIG Ignore, might be response to ignored Request
* sCG -> sIG Ignore, might be response to ignored Request
* sTW -> sIV Invalid, reincarnation in reverse direction
* goes through sRQ
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIV,
},
[DCCP_PKT_ACK] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sPO Ack for Response, move to PARTOPEN (8.1.5.)
* sPO -> sPO Retransmitted Ack for Response, remain in PARTOPEN
* sOP -> sOP Regular ACK, remain in OPEN
* sCR -> sCR Ack in CLOSEREQ MAY be processed (8.3.)
* sCG -> sCG Ack in CLOSING MAY be processed (8.3.)
* sTW -> sIV
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sPO, sPO, sOP, sCR, sCG, sIV
},
[DCCP_PKT_DATA] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sIV MUST use DataAck in PARTOPEN state (8.1.5.)
* sOP -> sOP Regular Data packet
* sCR -> sCR Data in CLOSEREQ MAY be processed (8.3.)
* sCG -> sCG Data in CLOSING MAY be processed (8.3.)
* sTW -> sIV
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sIV, sOP, sCR, sCG, sIV,
},
[DCCP_PKT_DATAACK] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sPO Ack for Response, move to PARTOPEN (8.1.5.)
* sPO -> sPO Remain in PARTOPEN state
* sOP -> sOP Regular DataAck packet in OPEN state
* sCR -> sCR DataAck in CLOSEREQ MAY be processed (8.3.)
* sCG -> sCG DataAck in CLOSING MAY be processed (8.3.)
* sTW -> sIV
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sPO, sPO, sOP, sCR, sCG, sIV
},
[DCCP_PKT_CLOSEREQ] = {
/*
* CLOSEREQ may only be sent by the server.
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV
},
[DCCP_PKT_CLOSE] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sCG Client-initiated close
* sOP -> sCG Client-initiated close
* sCR -> sCG Close in response to CloseReq (8.3.)
* sCG -> sCG Retransmit
* sTW -> sIV Late retransmit, already in TIME_WAIT
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sCG, sCG, sCG, sIV, sIV
},
[DCCP_PKT_RESET] = {
/*
* sNO -> sIV No connection
* sRQ -> sTW Sync received or timeout, SHOULD send Reset (8.1.1.)
* sRS -> sTW Response received without Request
* sPO -> sTW Timeout, SHOULD send Reset (8.1.5.)
* sOP -> sTW Connection reset
* sCR -> sTW Connection reset
* sCG -> sTW Connection reset
* sTW -> sIG Ignore (don't refresh timer)
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sTW, sTW, sTW, sTW, sTW, sTW, sIG
},
[DCCP_PKT_SYNC] = {
/*
* We currently ignore Sync packets
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIG, sIG, sIG, sIG, sIG, sIG, sIG, sIG,
},
[DCCP_PKT_SYNCACK] = {
/*
* We currently ignore SyncAck packets
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIG, sIG, sIG, sIG, sIG, sIG, sIG, sIG,
},
},
[CT_DCCP_ROLE_SERVER] = {
[DCCP_PKT_REQUEST] = {
/*
* sNO -> sIV Invalid
* sRQ -> sIG Ignore, conntrack might be out of sync
* sRS -> sIG Ignore, conntrack might be out of sync
* sPO -> sIG Ignore, conntrack might be out of sync
* sOP -> sIG Ignore, conntrack might be out of sync
* sCR -> sIG Ignore, conntrack might be out of sync
* sCG -> sIG Ignore, conntrack might be out of sync
* sTW -> sRQ Reincarnation, must reverse roles
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIG, sIG, sIG, sIG, sIG, sIG, sRQ
},
[DCCP_PKT_RESPONSE] = {
/*
* sNO -> sIV Response without Request
* sRQ -> sRS Response to clients Request
* sRS -> sRS Retransmitted Response (8.1.3. SHOULD NOT)
* sPO -> sIG Response to an ignored Request or late retransmit
* sOP -> sIG Ignore, might be response to ignored Request
* sCR -> sIG Ignore, might be response to ignored Request
* sCG -> sIG Ignore, might be response to ignored Request
* sTW -> sIV Invalid, Request from client in sTW moves to sRQ
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sRS, sRS, sIG, sIG, sIG, sIG, sIV
},
[DCCP_PKT_ACK] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sOP Enter OPEN state (8.1.5.)
* sOP -> sOP Regular Ack in OPEN state
* sCR -> sIV Waiting for Close from client
* sCG -> sCG Ack in CLOSING MAY be processed (8.3.)
* sTW -> sIV
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sOP, sOP, sIV, sCG, sIV
},
[DCCP_PKT_DATA] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sOP Enter OPEN state (8.1.5.)
* sOP -> sOP Regular Data packet in OPEN state
* sCR -> sIV Waiting for Close from client
* sCG -> sCG Data in CLOSING MAY be processed (8.3.)
* sTW -> sIV
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sOP, sOP, sIV, sCG, sIV
},
[DCCP_PKT_DATAACK] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sOP Enter OPEN state (8.1.5.)
* sOP -> sOP Regular DataAck in OPEN state
* sCR -> sIV Waiting for Close from client
* sCG -> sCG Data in CLOSING MAY be processed (8.3.)
* sTW -> sIV
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sOP, sOP, sIV, sCG, sIV
},
[DCCP_PKT_CLOSEREQ] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sOP -> sCR Move directly to CLOSEREQ (8.1.5.)
* sOP -> sCR CloseReq in OPEN state
* sCR -> sCR Retransmit
* sCG -> sCR Simultaneous close, client sends another Close
* sTW -> sIV Already closed
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sCR, sCR, sCR, sCR, sIV
},
[DCCP_PKT_CLOSE] = {
/*
* sNO -> sIV No connection
* sRQ -> sIV No connection
* sRS -> sIV No connection
* sPO -> sOP -> sCG Move direcly to CLOSING
* sOP -> sCG Move to CLOSING
* sCR -> sIV Close after CloseReq is invalid
* sCG -> sCG Retransmit
* sTW -> sIV Already closed
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIV, sIV, sIV, sCG, sCG, sIV, sCG, sIV
},
[DCCP_PKT_RESET] = {
/*
* sNO -> sIV No connection
* sRQ -> sTW Reset in response to Request
* sRS -> sTW Timeout, SHOULD send Reset (8.1.3.)
* sPO -> sTW Timeout, SHOULD send Reset (8.1.3.)
* sOP -> sTW
* sCR -> sTW
* sCG -> sTW
* sTW -> sIG Ignore (don't refresh timer)
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW, sTW */
sIV, sTW, sTW, sTW, sTW, sTW, sTW, sTW, sIG
},
[DCCP_PKT_SYNC] = {
/*
* We currently ignore Sync packets
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIG, sIG, sIG, sIG, sIG, sIG, sIG, sIG,
},
[DCCP_PKT_SYNCACK] = {
/*
* We currently ignore SyncAck packets
*
* sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */
sIG, sIG, sIG, sIG, sIG, sIG, sIG, sIG,
},
},
};
/* this module per-net specifics */
static int dccp_net_id __read_mostly;
struct dccp_net {
struct nf_proto_net pn;
int dccp_loose;
unsigned int dccp_timeout[CT_DCCP_MAX + 1];
};
static inline struct dccp_net *dccp_pernet(struct net *net)
{
return net_generic(net, dccp_net_id);
}
static bool dccp_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff,
struct nf_conntrack_tuple *tuple)
{
struct dccp_hdr _hdr, *dh;
dh = skb_header_pointer(skb, dataoff, sizeof(_hdr), &_hdr);
if (dh == NULL)
return false;
tuple->src.u.dccp.port = dh->dccph_sport;
tuple->dst.u.dccp.port = dh->dccph_dport;
return true;
}
static bool dccp_invert_tuple(struct nf_conntrack_tuple *inv,
const struct nf_conntrack_tuple *tuple)
{
inv->src.u.dccp.port = tuple->dst.u.dccp.port;
inv->dst.u.dccp.port = tuple->src.u.dccp.port;
return true;
}
static bool dccp_new(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
struct dccp_net *dn;
struct dccp_hdr _dh, *dh;
const char *msg;
u_int8_t state;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
BUG_ON(dh == NULL);
state = dccp_state_table[CT_DCCP_ROLE_CLIENT][dh->dccph_type][CT_DCCP_NONE];
switch (state) {
default:
dn = dccp_pernet(net);
if (dn->dccp_loose == 0) {
msg = "nf_ct_dccp: not picking up existing connection ";
goto out_invalid;
}
case CT_DCCP_REQUEST:
break;
case CT_DCCP_INVALID:
msg = "nf_ct_dccp: invalid state transition ";
goto out_invalid;
}
ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.state = CT_DCCP_NONE;
ct->proto.dccp.last_pkt = DCCP_PKT_REQUEST;
ct->proto.dccp.last_dir = IP_CT_DIR_ORIGINAL;
ct->proto.dccp.handshake_seq = 0;
return true;
out_invalid:
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, nf_ct_l3num(ct), 0, skb, NULL, NULL,
NULL, "%s", msg);
return false;
}
static u64 dccp_ack_seq(const struct dccp_hdr *dh)
{
const struct dccp_hdr_ack_bits *dhack;
dhack = (void *)dh + __dccp_basic_hdr_len(dh);
return ((u64)ntohs(dhack->dccph_ack_nr_high) << 32) +
ntohl(dhack->dccph_ack_nr_low);
}
static unsigned int *dccp_get_timeouts(struct net *net)
{
return dccp_pernet(net)->dccp_timeout;
}
static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, enum ip_conntrack_info ctinfo,
u_int8_t pf, unsigned int hooknum,
unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
struct dccp_hdr _dh, *dh;
u_int8_t type, old_state, new_state;
enum ct_dccp_roles role;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
BUG_ON(dh == NULL);
type = dh->dccph_type;
if (type == DCCP_PKT_RESET &&
!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
/* Tear down connection immediately if only reply is a RESET */
nf_ct_kill_acct(ct, ctinfo, skb);
return NF_ACCEPT;
}
spin_lock_bh(&ct->lock);
role = ct->proto.dccp.role[dir];
old_state = ct->proto.dccp.state;
new_state = dccp_state_table[role][type][old_state];
switch (new_state) {
case CT_DCCP_REQUEST:
if (old_state == CT_DCCP_TIMEWAIT &&
role == CT_DCCP_ROLE_SERVER) {
/* Reincarnation in the reverse direction: reopen and
* reverse client/server roles. */
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER;
}
break;
case CT_DCCP_RESPOND:
if (old_state == CT_DCCP_REQUEST)
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
break;
case CT_DCCP_PARTOPEN:
if (old_state == CT_DCCP_RESPOND &&
type == DCCP_PKT_ACK &&
dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq)
set_bit(IPS_ASSURED_BIT, &ct->status);
break;
case CT_DCCP_IGNORE:
/*
* Connection tracking might be out of sync, so we ignore
* packets that might establish a new connection and resync
* if the server responds with a valid Response.
*/
if (ct->proto.dccp.last_dir == !dir &&
ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST &&
type == DCCP_PKT_RESPONSE) {
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
new_state = CT_DCCP_RESPOND;
break;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid packet ignored ");
return NF_ACCEPT;
case CT_DCCP_INVALID:
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid state transition ");
return -NF_ACCEPT;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
ct->proto.dccp.state = new_state;
spin_unlock_bh(&ct->lock);
if (new_state != old_state)
nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]);
return NF_ACCEPT;
}
static int dccp_error(struct net *net, struct nf_conn *tmpl,
struct sk_buff *skb, unsigned int dataoff,
enum ip_conntrack_info *ctinfo,
u_int8_t pf, unsigned int hooknum)
{
struct dccp_hdr _dh, *dh;
unsigned int dccp_len = skb->len - dataoff;
unsigned int cscov;
const char *msg;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
if (dh == NULL) {
msg = "nf_ct_dccp: short packet ";
goto out_invalid;
}
if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) ||
dh->dccph_doff * 4 > dccp_len) {
msg = "nf_ct_dccp: truncated/malformed packet ";
goto out_invalid;
}
cscov = dccp_len;
if (dh->dccph_cscov) {
cscov = (dh->dccph_cscov - 1) * 4;
if (cscov > dccp_len) {
msg = "nf_ct_dccp: bad checksum coverage ";
goto out_invalid;
}
}
if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP,
pf)) {
msg = "nf_ct_dccp: bad checksum ";
goto out_invalid;
}
if (dh->dccph_type >= DCCP_PKT_INVALID) {
msg = "nf_ct_dccp: reserved packet type ";
goto out_invalid;
}
return NF_ACCEPT;
out_invalid:
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg);
return -NF_ACCEPT;
}
static int dccp_print_tuple(struct seq_file *s,
const struct nf_conntrack_tuple *tuple)
{
return seq_printf(s, "sport=%hu dport=%hu ",
ntohs(tuple->src.u.dccp.port),
ntohs(tuple->dst.u.dccp.port));
}
static int dccp_print_conntrack(struct seq_file *s, struct nf_conn *ct)
{
return seq_printf(s, "%s ", dccp_state_names[ct->proto.dccp.state]);
}
#if IS_ENABLED(CONFIG_NF_CT_NETLINK)
static int dccp_to_nlattr(struct sk_buff *skb, struct nlattr *nla,
struct nf_conn *ct)
{
struct nlattr *nest_parms;
spin_lock_bh(&ct->lock);
nest_parms = nla_nest_start(skb, CTA_PROTOINFO_DCCP | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (nla_put_u8(skb, CTA_PROTOINFO_DCCP_STATE, ct->proto.dccp.state) ||
nla_put_u8(skb, CTA_PROTOINFO_DCCP_ROLE,
ct->proto.dccp.role[IP_CT_DIR_ORIGINAL]) ||
nla_put_be64(skb, CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ,
cpu_to_be64(ct->proto.dccp.handshake_seq)))
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
spin_unlock_bh(&ct->lock);
return 0;
nla_put_failure:
spin_unlock_bh(&ct->lock);
return -1;
}
static const struct nla_policy dccp_nla_policy[CTA_PROTOINFO_DCCP_MAX + 1] = {
[CTA_PROTOINFO_DCCP_STATE] = { .type = NLA_U8 },
[CTA_PROTOINFO_DCCP_ROLE] = { .type = NLA_U8 },
[CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ] = { .type = NLA_U64 },
};
static int nlattr_to_dccp(struct nlattr *cda[], struct nf_conn *ct)
{
struct nlattr *attr = cda[CTA_PROTOINFO_DCCP];
struct nlattr *tb[CTA_PROTOINFO_DCCP_MAX + 1];
int err;
if (!attr)
return 0;
err = nla_parse_nested(tb, CTA_PROTOINFO_DCCP_MAX, attr,
dccp_nla_policy);
if (err < 0)
return err;
if (!tb[CTA_PROTOINFO_DCCP_STATE] ||
!tb[CTA_PROTOINFO_DCCP_ROLE] ||
nla_get_u8(tb[CTA_PROTOINFO_DCCP_ROLE]) > CT_DCCP_ROLE_MAX ||
nla_get_u8(tb[CTA_PROTOINFO_DCCP_STATE]) >= CT_DCCP_IGNORE) {
return -EINVAL;
}
spin_lock_bh(&ct->lock);
ct->proto.dccp.state = nla_get_u8(tb[CTA_PROTOINFO_DCCP_STATE]);
if (nla_get_u8(tb[CTA_PROTOINFO_DCCP_ROLE]) == CT_DCCP_ROLE_CLIENT) {
ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_SERVER;
} else {
ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_CLIENT;
}
if (tb[CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ]) {
ct->proto.dccp.handshake_seq =
be64_to_cpu(nla_get_be64(tb[CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ]));
}
spin_unlock_bh(&ct->lock);
return 0;
}
static int dccp_nlattr_size(void)
{
return nla_total_size(0) /* CTA_PROTOINFO_DCCP */
+ nla_policy_len(dccp_nla_policy, CTA_PROTOINFO_DCCP_MAX + 1);
}
#endif
#if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT)
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nfnetlink_cttimeout.h>
static int dccp_timeout_nlattr_to_obj(struct nlattr *tb[],
struct net *net, void *data)
{
struct dccp_net *dn = dccp_pernet(net);
unsigned int *timeouts = data;
int i;
/* set default DCCP timeouts. */
for (i=0; i<CT_DCCP_MAX; i++)
timeouts[i] = dn->dccp_timeout[i];
/* there's a 1:1 mapping between attributes and protocol states. */
for (i=CTA_TIMEOUT_DCCP_UNSPEC+1; i<CTA_TIMEOUT_DCCP_MAX+1; i++) {
if (tb[i]) {
timeouts[i] = ntohl(nla_get_be32(tb[i])) * HZ;
}
}
return 0;
}
static int
dccp_timeout_obj_to_nlattr(struct sk_buff *skb, const void *data)
{
const unsigned int *timeouts = data;
int i;
for (i=CTA_TIMEOUT_DCCP_UNSPEC+1; i<CTA_TIMEOUT_DCCP_MAX+1; i++) {
if (nla_put_be32(skb, i, htonl(timeouts[i] / HZ)))
goto nla_put_failure;
}
return 0;
nla_put_failure:
return -ENOSPC;
}
static const struct nla_policy
dccp_timeout_nla_policy[CTA_TIMEOUT_DCCP_MAX+1] = {
[CTA_TIMEOUT_DCCP_REQUEST] = { .type = NLA_U32 },
[CTA_TIMEOUT_DCCP_RESPOND] = { .type = NLA_U32 },
[CTA_TIMEOUT_DCCP_PARTOPEN] = { .type = NLA_U32 },
[CTA_TIMEOUT_DCCP_OPEN] = { .type = NLA_U32 },
[CTA_TIMEOUT_DCCP_CLOSEREQ] = { .type = NLA_U32 },
[CTA_TIMEOUT_DCCP_CLOSING] = { .type = NLA_U32 },
[CTA_TIMEOUT_DCCP_TIMEWAIT] = { .type = NLA_U32 },
};
#endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */
#ifdef CONFIG_SYSCTL
/* template, data assigned later */
static struct ctl_table dccp_sysctl_table[] = {
{
.procname = "nf_conntrack_dccp_timeout_request",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_timeout_respond",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_timeout_partopen",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_timeout_open",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_timeout_closereq",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_timeout_closing",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_timeout_timewait",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_dccp_loose",
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
#endif /* CONFIG_SYSCTL */
static int dccp_kmemdup_sysctl_table(struct net *net, struct nf_proto_net *pn,
struct dccp_net *dn)
{
#ifdef CONFIG_SYSCTL
if (pn->ctl_table)
return 0;
pn->ctl_table = kmemdup(dccp_sysctl_table,
sizeof(dccp_sysctl_table),
GFP_KERNEL);
if (!pn->ctl_table)
return -ENOMEM;
pn->ctl_table[0].data = &dn->dccp_timeout[CT_DCCP_REQUEST];
pn->ctl_table[1].data = &dn->dccp_timeout[CT_DCCP_RESPOND];
pn->ctl_table[2].data = &dn->dccp_timeout[CT_DCCP_PARTOPEN];
pn->ctl_table[3].data = &dn->dccp_timeout[CT_DCCP_OPEN];
pn->ctl_table[4].data = &dn->dccp_timeout[CT_DCCP_CLOSEREQ];
pn->ctl_table[5].data = &dn->dccp_timeout[CT_DCCP_CLOSING];
pn->ctl_table[6].data = &dn->dccp_timeout[CT_DCCP_TIMEWAIT];
pn->ctl_table[7].data = &dn->dccp_loose;
/* Don't export sysctls to unprivileged users */
if (net->user_ns != &init_user_ns)
pn->ctl_table[0].procname = NULL;
#endif
return 0;
}
static int dccp_init_net(struct net *net, u_int16_t proto)
{
struct dccp_net *dn = dccp_pernet(net);
struct nf_proto_net *pn = &dn->pn;
if (!pn->users) {
/* default values */
dn->dccp_loose = 1;
dn->dccp_timeout[CT_DCCP_REQUEST] = 2 * DCCP_MSL;
dn->dccp_timeout[CT_DCCP_RESPOND] = 4 * DCCP_MSL;
dn->dccp_timeout[CT_DCCP_PARTOPEN] = 4 * DCCP_MSL;
dn->dccp_timeout[CT_DCCP_OPEN] = 12 * 3600 * HZ;
dn->dccp_timeout[CT_DCCP_CLOSEREQ] = 64 * HZ;
dn->dccp_timeout[CT_DCCP_CLOSING] = 64 * HZ;
dn->dccp_timeout[CT_DCCP_TIMEWAIT] = 2 * DCCP_MSL;
}
return dccp_kmemdup_sysctl_table(net, pn, dn);
}
static struct nf_conntrack_l4proto dccp_proto4 __read_mostly = {
.l3proto = AF_INET,
.l4proto = IPPROTO_DCCP,
.name = "dccp",
.pkt_to_tuple = dccp_pkt_to_tuple,
.invert_tuple = dccp_invert_tuple,
.new = dccp_new,
.packet = dccp_packet,
.get_timeouts = dccp_get_timeouts,
.error = dccp_error,
.print_tuple = dccp_print_tuple,
.print_conntrack = dccp_print_conntrack,
#if IS_ENABLED(CONFIG_NF_CT_NETLINK)
.to_nlattr = dccp_to_nlattr,
.nlattr_size = dccp_nlattr_size,
.from_nlattr = nlattr_to_dccp,
.tuple_to_nlattr = nf_ct_port_tuple_to_nlattr,
.nlattr_tuple_size = nf_ct_port_nlattr_tuple_size,
.nlattr_to_tuple = nf_ct_port_nlattr_to_tuple,
.nla_policy = nf_ct_port_nla_policy,
#endif
#if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT)
.ctnl_timeout = {
.nlattr_to_obj = dccp_timeout_nlattr_to_obj,
.obj_to_nlattr = dccp_timeout_obj_to_nlattr,
.nlattr_max = CTA_TIMEOUT_DCCP_MAX,
.obj_size = sizeof(unsigned int) * CT_DCCP_MAX,
.nla_policy = dccp_timeout_nla_policy,
},
#endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */
.net_id = &dccp_net_id,
.init_net = dccp_init_net,
};
static struct nf_conntrack_l4proto dccp_proto6 __read_mostly = {
.l3proto = AF_INET6,
.l4proto = IPPROTO_DCCP,
.name = "dccp",
.pkt_to_tuple = dccp_pkt_to_tuple,
.invert_tuple = dccp_invert_tuple,
.new = dccp_new,
.packet = dccp_packet,
.get_timeouts = dccp_get_timeouts,
.error = dccp_error,
.print_tuple = dccp_print_tuple,
.print_conntrack = dccp_print_conntrack,
#if IS_ENABLED(CONFIG_NF_CT_NETLINK)
.to_nlattr = dccp_to_nlattr,
.nlattr_size = dccp_nlattr_size,
.from_nlattr = nlattr_to_dccp,
.tuple_to_nlattr = nf_ct_port_tuple_to_nlattr,
.nlattr_tuple_size = nf_ct_port_nlattr_tuple_size,
.nlattr_to_tuple = nf_ct_port_nlattr_to_tuple,
.nla_policy = nf_ct_port_nla_policy,
#endif
#if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT)
.ctnl_timeout = {
.nlattr_to_obj = dccp_timeout_nlattr_to_obj,
.obj_to_nlattr = dccp_timeout_obj_to_nlattr,
.nlattr_max = CTA_TIMEOUT_DCCP_MAX,
.obj_size = sizeof(unsigned int) * CT_DCCP_MAX,
.nla_policy = dccp_timeout_nla_policy,
},
#endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */
.net_id = &dccp_net_id,
.init_net = dccp_init_net,
};
static __net_init int dccp_net_init(struct net *net)
{
int ret = 0;
ret = nf_ct_l4proto_pernet_register(net, &dccp_proto4);
if (ret < 0) {
pr_err("nf_conntrack_dccp4: pernet registration failed.\n");
goto out;
}
ret = nf_ct_l4proto_pernet_register(net, &dccp_proto6);
if (ret < 0) {
pr_err("nf_conntrack_dccp6: pernet registration failed.\n");
goto cleanup_dccp4;
}
return 0;
cleanup_dccp4:
nf_ct_l4proto_pernet_unregister(net, &dccp_proto4);
out:
return ret;
}
static __net_exit void dccp_net_exit(struct net *net)
{
nf_ct_l4proto_pernet_unregister(net, &dccp_proto6);
nf_ct_l4proto_pernet_unregister(net, &dccp_proto4);
}
static struct pernet_operations dccp_net_ops = {
.init = dccp_net_init,
.exit = dccp_net_exit,
.id = &dccp_net_id,
.size = sizeof(struct dccp_net),
};
static int __init nf_conntrack_proto_dccp_init(void)
{
int ret;
ret = register_pernet_subsys(&dccp_net_ops);
if (ret < 0)
goto out_pernet;
ret = nf_ct_l4proto_register(&dccp_proto4);
if (ret < 0)
goto out_dccp4;
ret = nf_ct_l4proto_register(&dccp_proto6);
if (ret < 0)
goto out_dccp6;
return 0;
out_dccp6:
nf_ct_l4proto_unregister(&dccp_proto4);
out_dccp4:
unregister_pernet_subsys(&dccp_net_ops);
out_pernet:
return ret;
}
static void __exit nf_conntrack_proto_dccp_fini(void)
{
nf_ct_l4proto_unregister(&dccp_proto6);
nf_ct_l4proto_unregister(&dccp_proto4);
unregister_pernet_subsys(&dccp_net_ops);
}
module_init(nf_conntrack_proto_dccp_init);
module_exit(nf_conntrack_proto_dccp_fini);
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_DESCRIPTION("DCCP connection tracking protocol helper");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2109_0 |
crossvul-cpp_data_good_5039_4 | /*
* Copyright (c) 2009-2014 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "jansson.h"
#include "jansson_private.h"
#include "strbuffer.h"
#include "utf.h"
#define STREAM_STATE_OK 0
#define STREAM_STATE_EOF -1
#define STREAM_STATE_ERROR -2
#define TOKEN_INVALID -1
#define TOKEN_EOF 0
#define TOKEN_STRING 256
#define TOKEN_INTEGER 257
#define TOKEN_REAL 258
#define TOKEN_TRUE 259
#define TOKEN_FALSE 260
#define TOKEN_NULL 261
/* Locale independent versions of isxxx() functions */
#define l_isupper(c) ('A' <= (c) && (c) <= 'Z')
#define l_islower(c) ('a' <= (c) && (c) <= 'z')
#define l_isalpha(c) (l_isupper(c) || l_islower(c))
#define l_isdigit(c) ('0' <= (c) && (c) <= '9')
#define l_isxdigit(c) \
(l_isdigit(c) || ('A' <= (c) && (c) <= 'F') || ('a' <= (c) && (c) <= 'f'))
/* Read one byte from stream, convert to unsigned char, then int, and
return. return EOF on end of file. This corresponds to the
behaviour of fgetc(). */
typedef int (*get_func)(void *data);
typedef struct {
get_func get;
void *data;
char buffer[5];
size_t buffer_pos;
int state;
int line;
int column, last_column;
size_t position;
} stream_t;
typedef struct {
stream_t stream;
strbuffer_t saved_text;
size_t flags;
size_t depth;
int token;
union {
struct {
char *val;
size_t len;
} string;
json_int_t integer;
double real;
} value;
} lex_t;
#define stream_to_lex(stream) container_of(stream, lex_t, stream)
/*** error reporting ***/
static void error_set(json_error_t *error, const lex_t *lex,
const char *msg, ...)
{
va_list ap;
char msg_text[JSON_ERROR_TEXT_LENGTH];
char msg_with_context[JSON_ERROR_TEXT_LENGTH];
int line = -1, col = -1;
size_t pos = 0;
const char *result = msg_text;
if(!error)
return;
va_start(ap, msg);
vsnprintf(msg_text, JSON_ERROR_TEXT_LENGTH, msg, ap);
msg_text[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
va_end(ap);
if(lex)
{
const char *saved_text = strbuffer_value(&lex->saved_text);
line = lex->stream.line;
col = lex->stream.column;
pos = lex->stream.position;
if(saved_text && saved_text[0])
{
if(lex->saved_text.length <= 20) {
snprintf(msg_with_context, JSON_ERROR_TEXT_LENGTH,
"%s near '%s'", msg_text, saved_text);
msg_with_context[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
result = msg_with_context;
}
}
else
{
if(lex->stream.state == STREAM_STATE_ERROR) {
/* No context for UTF-8 decoding errors */
result = msg_text;
}
else {
snprintf(msg_with_context, JSON_ERROR_TEXT_LENGTH,
"%s near end of file", msg_text);
msg_with_context[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
result = msg_with_context;
}
}
}
jsonp_error_set(error, line, col, pos, "%s", result);
}
/*** lexical analyzer ***/
static void
stream_init(stream_t *stream, get_func get, void *data)
{
stream->get = get;
stream->data = data;
stream->buffer[0] = '\0';
stream->buffer_pos = 0;
stream->state = STREAM_STATE_OK;
stream->line = 1;
stream->column = 0;
stream->position = 0;
}
static int stream_get(stream_t *stream, json_error_t *error)
{
int c;
if(stream->state != STREAM_STATE_OK)
return stream->state;
if(!stream->buffer[stream->buffer_pos])
{
c = stream->get(stream->data);
if(c == EOF) {
stream->state = STREAM_STATE_EOF;
return STREAM_STATE_EOF;
}
stream->buffer[0] = c;
stream->buffer_pos = 0;
if(0x80 <= c && c <= 0xFF)
{
/* multi-byte UTF-8 sequence */
size_t i, count;
count = utf8_check_first(c);
if(!count)
goto out;
assert(count >= 2);
for(i = 1; i < count; i++)
stream->buffer[i] = stream->get(stream->data);
if(!utf8_check_full(stream->buffer, count, NULL))
goto out;
stream->buffer[count] = '\0';
}
else
stream->buffer[1] = '\0';
}
c = stream->buffer[stream->buffer_pos++];
stream->position++;
if(c == '\n') {
stream->line++;
stream->last_column = stream->column;
stream->column = 0;
}
else if(utf8_check_first(c)) {
/* track the Unicode character column, so increment only if
this is the first character of a UTF-8 sequence */
stream->column++;
}
return c;
out:
stream->state = STREAM_STATE_ERROR;
error_set(error, stream_to_lex(stream), "unable to decode byte 0x%x", c);
return STREAM_STATE_ERROR;
}
static void stream_unget(stream_t *stream, int c)
{
if(c == STREAM_STATE_EOF || c == STREAM_STATE_ERROR)
return;
stream->position--;
if(c == '\n') {
stream->line--;
stream->column = stream->last_column;
}
else if(utf8_check_first(c))
stream->column--;
assert(stream->buffer_pos > 0);
stream->buffer_pos--;
assert(stream->buffer[stream->buffer_pos] == c);
}
static int lex_get(lex_t *lex, json_error_t *error)
{
return stream_get(&lex->stream, error);
}
static void lex_save(lex_t *lex, int c)
{
strbuffer_append_byte(&lex->saved_text, c);
}
static int lex_get_save(lex_t *lex, json_error_t *error)
{
int c = stream_get(&lex->stream, error);
if(c != STREAM_STATE_EOF && c != STREAM_STATE_ERROR)
lex_save(lex, c);
return c;
}
static void lex_unget(lex_t *lex, int c)
{
stream_unget(&lex->stream, c);
}
static void lex_unget_unsave(lex_t *lex, int c)
{
if(c != STREAM_STATE_EOF && c != STREAM_STATE_ERROR) {
/* Since we treat warnings as errors, when assertions are turned
* off the "d" variable would be set but never used. Which is
* treated as an error by GCC.
*/
#ifndef NDEBUG
char d;
#endif
stream_unget(&lex->stream, c);
#ifndef NDEBUG
d =
#endif
strbuffer_pop(&lex->saved_text);
assert(c == d);
}
}
static void lex_save_cached(lex_t *lex)
{
while(lex->stream.buffer[lex->stream.buffer_pos] != '\0')
{
lex_save(lex, lex->stream.buffer[lex->stream.buffer_pos]);
lex->stream.buffer_pos++;
lex->stream.position++;
}
}
static void lex_free_string(lex_t *lex)
{
jsonp_free(lex->value.string.val);
lex->value.string.val = NULL;
lex->value.string.len = 0;
}
/* assumes that str points to 'u' plus at least 4 valid hex digits */
static int32_t decode_unicode_escape(const char *str)
{
int i;
int32_t value = 0;
assert(str[0] == 'u');
for(i = 1; i <= 4; i++) {
char c = str[i];
value <<= 4;
if(l_isdigit(c))
value += c - '0';
else if(l_islower(c))
value += c - 'a' + 10;
else if(l_isupper(c))
value += c - 'A' + 10;
else
return -1;
}
return value;
}
static void lex_scan_string(lex_t *lex, json_error_t *error)
{
int c;
const char *p;
char *t;
int i;
lex->value.string.val = NULL;
lex->token = TOKEN_INVALID;
c = lex_get_save(lex, error);
while(c != '"') {
if(c == STREAM_STATE_ERROR)
goto out;
else if(c == STREAM_STATE_EOF) {
error_set(error, lex, "premature end of input");
goto out;
}
else if(0 <= c && c <= 0x1F) {
/* control character */
lex_unget_unsave(lex, c);
if(c == '\n')
error_set(error, lex, "unexpected newline", c);
else
error_set(error, lex, "control character 0x%x", c);
goto out;
}
else if(c == '\\') {
c = lex_get_save(lex, error);
if(c == 'u') {
c = lex_get_save(lex, error);
for(i = 0; i < 4; i++) {
if(!l_isxdigit(c)) {
error_set(error, lex, "invalid escape");
goto out;
}
c = lex_get_save(lex, error);
}
}
else if(c == '"' || c == '\\' || c == '/' || c == 'b' ||
c == 'f' || c == 'n' || c == 'r' || c == 't')
c = lex_get_save(lex, error);
else {
error_set(error, lex, "invalid escape");
goto out;
}
}
else
c = lex_get_save(lex, error);
}
/* the actual value is at most of the same length as the source
string, because:
- shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte
- a single \uXXXX escape (length 6) is converted to at most 3 bytes
- two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair
are converted to 4 bytes
*/
t = jsonp_malloc(lex->saved_text.length + 1);
if(!t) {
/* this is not very nice, since TOKEN_INVALID is returned */
goto out;
}
lex->value.string.val = t;
/* + 1 to skip the " */
p = strbuffer_value(&lex->saved_text) + 1;
while(*p != '"') {
if(*p == '\\') {
p++;
if(*p == 'u') {
size_t length;
int32_t value;
value = decode_unicode_escape(p);
if(value < 0) {
error_set(error, lex, "invalid Unicode escape '%.6s'", p - 1);
goto out;
}
p += 5;
if(0xD800 <= value && value <= 0xDBFF) {
/* surrogate pair */
if(*p == '\\' && *(p + 1) == 'u') {
int32_t value2 = decode_unicode_escape(++p);
if(value2 < 0) {
error_set(error, lex, "invalid Unicode escape '%.6s'", p - 1);
goto out;
}
p += 5;
if(0xDC00 <= value2 && value2 <= 0xDFFF) {
/* valid second surrogate */
value =
((value - 0xD800) << 10) +
(value2 - 0xDC00) +
0x10000;
}
else {
/* invalid second surrogate */
error_set(error, lex,
"invalid Unicode '\\u%04X\\u%04X'",
value, value2);
goto out;
}
}
else {
/* no second surrogate */
error_set(error, lex, "invalid Unicode '\\u%04X'",
value);
goto out;
}
}
else if(0xDC00 <= value && value <= 0xDFFF) {
error_set(error, lex, "invalid Unicode '\\u%04X'", value);
goto out;
}
if(utf8_encode(value, t, &length))
assert(0);
t += length;
}
else {
switch(*p) {
case '"': case '\\': case '/':
*t = *p; break;
case 'b': *t = '\b'; break;
case 'f': *t = '\f'; break;
case 'n': *t = '\n'; break;
case 'r': *t = '\r'; break;
case 't': *t = '\t'; break;
default: assert(0);
}
t++;
p++;
}
}
else
*(t++) = *(p++);
}
*t = '\0';
lex->value.string.len = t - lex->value.string.val;
lex->token = TOKEN_STRING;
return;
out:
lex_free_string(lex);
}
#ifndef JANSSON_USING_CMAKE /* disabled if using cmake */
#if JSON_INTEGER_IS_LONG_LONG
#ifdef _MSC_VER /* Microsoft Visual Studio */
#define json_strtoint _strtoi64
#else
#define json_strtoint strtoll
#endif
#else
#define json_strtoint strtol
#endif
#endif
static int lex_scan_number(lex_t *lex, int c, json_error_t *error)
{
const char *saved_text;
char *end;
double doubleval;
lex->token = TOKEN_INVALID;
if(c == '-')
c = lex_get_save(lex, error);
if(c == '0') {
c = lex_get_save(lex, error);
if(l_isdigit(c)) {
lex_unget_unsave(lex, c);
goto out;
}
}
else if(l_isdigit(c)) {
do
c = lex_get_save(lex, error);
while(l_isdigit(c));
}
else {
lex_unget_unsave(lex, c);
goto out;
}
if(!(lex->flags & JSON_DECODE_INT_AS_REAL) &&
c != '.' && c != 'E' && c != 'e')
{
json_int_t intval;
lex_unget_unsave(lex, c);
saved_text = strbuffer_value(&lex->saved_text);
errno = 0;
intval = json_strtoint(saved_text, &end, 10);
if(errno == ERANGE) {
if(intval < 0)
error_set(error, lex, "too big negative integer");
else
error_set(error, lex, "too big integer");
goto out;
}
assert(end == saved_text + lex->saved_text.length);
lex->token = TOKEN_INTEGER;
lex->value.integer = intval;
return 0;
}
if(c == '.') {
c = lex_get(lex, error);
if(!l_isdigit(c)) {
lex_unget(lex, c);
goto out;
}
lex_save(lex, c);
do
c = lex_get_save(lex, error);
while(l_isdigit(c));
}
if(c == 'E' || c == 'e') {
c = lex_get_save(lex, error);
if(c == '+' || c == '-')
c = lex_get_save(lex, error);
if(!l_isdigit(c)) {
lex_unget_unsave(lex, c);
goto out;
}
do
c = lex_get_save(lex, error);
while(l_isdigit(c));
}
lex_unget_unsave(lex, c);
if(jsonp_strtod(&lex->saved_text, &doubleval)) {
error_set(error, lex, "real number overflow");
goto out;
}
lex->token = TOKEN_REAL;
lex->value.real = doubleval;
return 0;
out:
return -1;
}
static int lex_scan(lex_t *lex, json_error_t *error)
{
int c;
strbuffer_clear(&lex->saved_text);
if(lex->token == TOKEN_STRING)
lex_free_string(lex);
do
c = lex_get(lex, error);
while(c == ' ' || c == '\t' || c == '\n' || c == '\r');
if(c == STREAM_STATE_EOF) {
lex->token = TOKEN_EOF;
goto out;
}
if(c == STREAM_STATE_ERROR) {
lex->token = TOKEN_INVALID;
goto out;
}
lex_save(lex, c);
if(c == '{' || c == '}' || c == '[' || c == ']' || c == ':' || c == ',')
lex->token = c;
else if(c == '"')
lex_scan_string(lex, error);
else if(l_isdigit(c) || c == '-') {
if(lex_scan_number(lex, c, error))
goto out;
}
else if(l_isalpha(c)) {
/* eat up the whole identifier for clearer error messages */
const char *saved_text;
do
c = lex_get_save(lex, error);
while(l_isalpha(c));
lex_unget_unsave(lex, c);
saved_text = strbuffer_value(&lex->saved_text);
if(strcmp(saved_text, "true") == 0)
lex->token = TOKEN_TRUE;
else if(strcmp(saved_text, "false") == 0)
lex->token = TOKEN_FALSE;
else if(strcmp(saved_text, "null") == 0)
lex->token = TOKEN_NULL;
else
lex->token = TOKEN_INVALID;
}
else {
/* save the rest of the input UTF-8 sequence to get an error
message of valid UTF-8 */
lex_save_cached(lex);
lex->token = TOKEN_INVALID;
}
out:
return lex->token;
}
static char *lex_steal_string(lex_t *lex, size_t *out_len)
{
char *result = NULL;
if(lex->token == TOKEN_STRING) {
result = lex->value.string.val;
*out_len = lex->value.string.len;
lex->value.string.val = NULL;
lex->value.string.len = 0;
}
return result;
}
static int lex_init(lex_t *lex, get_func get, size_t flags, void *data)
{
stream_init(&lex->stream, get, data);
if(strbuffer_init(&lex->saved_text))
return -1;
lex->flags = flags;
lex->token = TOKEN_INVALID;
return 0;
}
static void lex_close(lex_t *lex)
{
if(lex->token == TOKEN_STRING)
lex_free_string(lex);
strbuffer_close(&lex->saved_text);
}
/*** parser ***/
static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error);
static json_t *parse_object(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *object = json_object();
if(!object)
return NULL;
lex_scan(lex, error);
if(lex->token == '}')
return object;
while(1) {
char *key;
size_t len;
json_t *value;
if(lex->token != TOKEN_STRING) {
error_set(error, lex, "string or '}' expected");
goto error;
}
key = lex_steal_string(lex, &len);
if(!key)
return NULL;
if (memchr(key, '\0', len)) {
jsonp_free(key);
error_set(error, lex, "NUL byte in object key not supported");
goto error;
}
if(flags & JSON_REJECT_DUPLICATES) {
if(json_object_get(object, key)) {
jsonp_free(key);
error_set(error, lex, "duplicate object key");
goto error;
}
}
lex_scan(lex, error);
if(lex->token != ':') {
jsonp_free(key);
error_set(error, lex, "':' expected");
goto error;
}
lex_scan(lex, error);
value = parse_value(lex, flags, error);
if(!value) {
jsonp_free(key);
goto error;
}
if(json_object_set_nocheck(object, key, value)) {
jsonp_free(key);
json_decref(value);
goto error;
}
json_decref(value);
jsonp_free(key);
lex_scan(lex, error);
if(lex->token != ',')
break;
lex_scan(lex, error);
}
if(lex->token != '}') {
error_set(error, lex, "'}' expected");
goto error;
}
return object;
error:
json_decref(object);
return NULL;
}
static json_t *parse_array(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *array = json_array();
if(!array)
return NULL;
lex_scan(lex, error);
if(lex->token == ']')
return array;
while(lex->token) {
json_t *elem = parse_value(lex, flags, error);
if(!elem)
goto error;
if(json_array_append(array, elem)) {
json_decref(elem);
goto error;
}
json_decref(elem);
lex_scan(lex, error);
if(lex->token != ',')
break;
lex_scan(lex, error);
}
if(lex->token != ']') {
error_set(error, lex, "']' expected");
goto error;
}
return array;
error:
json_decref(array);
return NULL;
}
static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *json;
lex->depth++;
if(lex->depth > JSON_PARSER_MAX_DEPTH) {
error_set(error, lex, "maximum parsing depth reached");
return NULL;
}
switch(lex->token) {
case TOKEN_STRING: {
const char *value = lex->value.string.val;
size_t len = lex->value.string.len;
if(!(flags & JSON_ALLOW_NUL)) {
if(memchr(value, '\0', len)) {
error_set(error, lex, "\\u0000 is not allowed without JSON_ALLOW_NUL");
return NULL;
}
}
json = jsonp_stringn_nocheck_own(value, len);
if(json) {
lex->value.string.val = NULL;
lex->value.string.len = 0;
}
break;
}
case TOKEN_INTEGER: {
json = json_integer(lex->value.integer);
break;
}
case TOKEN_REAL: {
json = json_real(lex->value.real);
break;
}
case TOKEN_TRUE:
json = json_true();
break;
case TOKEN_FALSE:
json = json_false();
break;
case TOKEN_NULL:
json = json_null();
break;
case '{':
json = parse_object(lex, flags, error);
break;
case '[':
json = parse_array(lex, flags, error);
break;
case TOKEN_INVALID:
error_set(error, lex, "invalid token");
return NULL;
default:
error_set(error, lex, "unexpected token");
return NULL;
}
if(!json)
return NULL;
lex->depth--;
return json;
}
static json_t *parse_json(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *result;
lex->depth = 0;
lex_scan(lex, error);
if(!(flags & JSON_DECODE_ANY)) {
if(lex->token != '[' && lex->token != '{') {
error_set(error, lex, "'[' or '{' expected");
return NULL;
}
}
result = parse_value(lex, flags, error);
if(!result)
return NULL;
if(!(flags & JSON_DISABLE_EOF_CHECK)) {
lex_scan(lex, error);
if(lex->token != TOKEN_EOF) {
error_set(error, lex, "end of file expected");
json_decref(result);
return NULL;
}
}
if(error) {
/* Save the position even though there was no error */
error->position = (int)lex->stream.position;
}
return result;
}
typedef struct
{
const char *data;
int pos;
} string_data_t;
static int string_get(void *data)
{
char c;
string_data_t *stream = (string_data_t *)data;
c = stream->data[stream->pos];
if(c == '\0')
return EOF;
else
{
stream->pos++;
return (unsigned char)c;
}
}
json_t *json_loads(const char *string, size_t flags, json_error_t *error)
{
lex_t lex;
json_t *result;
string_data_t stream_data;
jsonp_error_init(error, "<string>");
if (string == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
stream_data.data = string;
stream_data.pos = 0;
if(lex_init(&lex, string_get, flags, (void *)&stream_data))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
typedef struct
{
const char *data;
size_t len;
size_t pos;
} buffer_data_t;
static int buffer_get(void *data)
{
char c;
buffer_data_t *stream = data;
if(stream->pos >= stream->len)
return EOF;
c = stream->data[stream->pos];
stream->pos++;
return (unsigned char)c;
}
json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error)
{
lex_t lex;
json_t *result;
buffer_data_t stream_data;
jsonp_error_init(error, "<buffer>");
if (buffer == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
stream_data.data = buffer;
stream_data.pos = 0;
stream_data.len = buflen;
if(lex_init(&lex, buffer_get, flags, (void *)&stream_data))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
json_t *json_loadf(FILE *input, size_t flags, json_error_t *error)
{
lex_t lex;
const char *source;
json_t *result;
if(input == stdin)
source = "<stdin>";
else
source = "<stream>";
jsonp_error_init(error, source);
if (input == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
if(lex_init(&lex, (get_func)fgetc, flags, input))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
json_t *json_load_file(const char *path, size_t flags, json_error_t *error)
{
json_t *result;
FILE *fp;
jsonp_error_init(error, path);
if (path == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
fp = fopen(path, "rb");
if(!fp)
{
error_set(error, NULL, "unable to open %s: %s",
path, strerror(errno));
return NULL;
}
result = json_loadf(fp, flags, error);
fclose(fp);
return result;
}
#define MAX_BUF_LEN 1024
typedef struct
{
char data[MAX_BUF_LEN];
size_t len;
size_t pos;
json_load_callback_t callback;
void *arg;
} callback_data_t;
static int callback_get(void *data)
{
char c;
callback_data_t *stream = data;
if(stream->pos >= stream->len) {
stream->pos = 0;
stream->len = stream->callback(stream->data, MAX_BUF_LEN, stream->arg);
if(stream->len == 0 || stream->len == (size_t)-1)
return EOF;
}
c = stream->data[stream->pos];
stream->pos++;
return (unsigned char)c;
}
json_t *json_load_callback(json_load_callback_t callback, void *arg, size_t flags, json_error_t *error)
{
lex_t lex;
json_t *result;
callback_data_t stream_data;
memset(&stream_data, 0, sizeof(stream_data));
stream_data.callback = callback;
stream_data.arg = arg;
jsonp_error_init(error, "<callback>");
if (callback == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
if(lex_init(&lex, (get_func)callback_get, flags, &stream_data))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5039_4 |
crossvul-cpp_data_good_4699_0 | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.danga.com/memcached/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <mellon@pobox.com>
* Brad Fitzpatrick <brad@danga.com>
*/
#include "memcached.h"
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sysexits.h>
#include <stddef.h>
/* FreeBSD 4.x doesn't have IOV_MAX exposed. */
#ifndef IOV_MAX
#if defined(__FreeBSD__) || defined(__APPLE__)
# define IOV_MAX 1024
#endif
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static int try_read_command(conn *c);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occured (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static void conn_set_state(conn *c, enum conn_states state);
/* stats */
static void stats_init(void);
static void server_stats(ADD_STAT add_stats, conn *c);
static void process_stat_settings(ADD_STAT add_stats, void *c);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void process_command(conn *c, char *command);
static void write_and_free(conn *c, char *buf, int bytes);
static int ensure_iov_space(conn *c);
static int add_iov(conn *c, const void *buf, int len);
static int add_msghdr(conn *c);
/* time handling */
static void set_current_time(void); /* update the global variable holding
global 32-bit seconds-since-start time
(to avoid 64 bit time_t) */
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct settings settings;
time_t process_started; /* when the process was started */
/** file scope variables **/
static conn *listen_conn = NULL;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
static enum transmit_result transmit(conn *c);
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
static rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
stats.curr_items = stats.total_items = stats.curr_conns = stats.total_conns = stats.conn_structs = 0;
stats.get_cmds = stats.set_cmds = stats.get_hits = stats.get_misses = stats.evictions = 0;
stats.curr_bytes = stats.listen_disabled_num = 0;
stats.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - 2;
stats_prefix_init();
}
static void stats_reset(void) {
STATS_LOCK();
stats.total_items = stats.total_conns = 0;
stats.evictions = 0;
stats.listen_disabled_num = 0;
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 11211;
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_msghdr(conn *c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (! msg)
return -1;
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
if (c->request_addr_size > 0) {
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
}
c->msgbytes = 0;
c->msgused++;
if (IS_UDP(c->transport)) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE);
}
return 0;
}
/*
* Free list management for connections.
*/
static conn **freeconns;
static int freetotal;
static int freecurr;
/* Lock for connection freelist */
static pthread_mutex_t conn_lock = PTHREAD_MUTEX_INITIALIZER;
static void conn_init(void) {
freetotal = 200;
freecurr = 0;
if ((freeconns = calloc(freetotal, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
}
return;
}
/*
* Returns a connection from the freelist, if any.
*/
conn *conn_from_freelist() {
conn *c;
pthread_mutex_lock(&conn_lock);
if (freecurr > 0) {
c = freeconns[--freecurr];
} else {
c = NULL;
}
pthread_mutex_unlock(&conn_lock);
return c;
}
/*
* Adds a connection to the freelist. 0 = success.
*/
bool conn_add_to_freelist(conn *c) {
bool ret = true;
pthread_mutex_lock(&conn_lock);
if (freecurr < freetotal) {
freeconns[freecurr++] = c;
ret = false;
} else {
/* try to enlarge free connections array */
size_t newsize = freetotal * 2;
conn **new_freeconns = realloc(freeconns, sizeof(conn *) * newsize);
if (new_freeconns) {
freetotal = newsize;
freeconns = new_freeconns;
freeconns[freecurr++] = c;
ret = false;
}
}
pthread_mutex_unlock(&conn_lock);
return ret;
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
}
return rv;
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base) {
conn *c = conn_from_freelist();
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
fprintf(stderr, "calloc()\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->rbuf = c->wbuf = 0;
c->ilist = 0;
c->suffixlist = 0;
c->iov = 0;
c->msglist = 0;
c->hdrbuf = 0;
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->suffixsize = SUFFIX_LIST_INITIAL;
c->iovsize = IOV_LIST_INITIAL;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize);
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 ||
c->msglist == 0 || c->suffixlist == 0) {
conn_free(c);
fprintf(stderr, "malloc()\n");
return NULL;
}
STATS_LOCK();
stats.conn_structs++;
STATS_UNLOCK();
}
c->transport = transport;
c->protocol = settings.binding_protocol;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
c->sfd = sfd;
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = c->wbytes = 0;
c->wcurr = c->wbuf;
c->rcurr = c->rbuf;
c->ritem = 0;
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
c->ileft = 0;
c->suffixleft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->write_and_go = init_state;
c->write_and_free = 0;
c->item = 0;
c->noreply = false;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
if (conn_add_to_freelist(c)) {
conn_free(c);
}
perror("event_add");
return NULL;
}
STATS_LOCK();
stats.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
if (c->item) {
item_remove(c->item);
c->item = 0;
}
if (c->ileft != 0) {
for (; c->ileft > 0; c->ileft--,c->icurr++) {
item_remove(*(c->icurr));
}
}
if (c->suffixleft != 0) {
for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) {
cache_free(c->thread->suffix_cache, *(c->suffixcurr));
}
}
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
MEMCACHED_CONN_DESTROY(c);
if (c->hdrbuf)
free(c->hdrbuf);
if (c->msglist)
free(c->msglist);
if (c->rbuf)
free(c->rbuf);
if (c->wbuf)
free(c->wbuf);
if (c->ilist)
free(c->ilist);
if (c->suffixlist)
free(c->suffixlist);
if (c->iov)
free(c->iov);
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
MEMCACHED_CONN_RELEASE(c->sfd);
close(c->sfd);
accept_new_conns(true);
conn_cleanup(c);
/* if the connection has big buffers, just free it */
if (c->rsize > READ_BUFFER_HIGHWAT || conn_add_to_freelist(c)) {
conn_free(c);
}
STATS_LOCK();
stats.curr_conns--;
STATS_UNLOCK();
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
static void conn_shrink(conn *c) {
assert(c != NULL);
if (IS_UDP(c->transport))
return;
if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) {
char *newbuf;
if (c->rcurr != c->rbuf)
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
if (newbuf) {
c->rbuf = newbuf;
c->rsize = DATA_BUFFER_SIZE;
}
/* TODO check other branch... */
c->rcurr = c->rbuf;
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]));
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0]));
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->iovsize > IOV_LIST_HIGHWAT) {
struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0]));
if (newbuf) {
c->iov = newbuf;
c->iovsize = IOV_LIST_INITIAL;
}
/* TODO check return value */
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);
if (state != c->state) {
if (settings.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state),
state_text(state));
}
c->state = state;
if (state == conn_write || state == conn_mwrite) {
MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes);
}
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov = (struct iovec *)realloc(c->iov,
(c->iovsize * 2) * sizeof(struct iovec));
if (! new_iov)
return -1;
c->iov = new_iov;
c->iovsize *= 2;
/* Point all the msghdr structures at the new list. */
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_iov(conn *c, const void *buf, int len) {
struct msghdr *m;
int leftover;
bool limit_to_mtu;
assert(c != NULL);
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets, and the first payloads of TCP replies, to
* UDP_MAX_PAYLOAD_SIZE bytes.
*/
limit_to_mtu = IS_UDP(c->transport) || (1 == c->msgused);
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(limit_to_mtu && c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (limit_to_mtu && len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
static int build_udp_headers(conn *c) {
int i;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf)
new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE);
else
new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE);
if (! new_hdrbuf)
return -1;
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = (void*)hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = 0;
*hdr++ = 0;
assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn *c, const char *str) {
size_t len;
assert(c != NULL);
if (c->noreply) {
if (settings.verbose > 1)
fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str);
c->noreply = false;
conn_set_state(c, conn_new_cmd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
return;
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->cmd, and the item is ready in c->item.
*/
static void complete_nread_ascii(conn *c) {
assert(c != NULL);
item *it = c->item;
int comm = c->cmd;
enum store_item_type ret;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) != 0) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
ret = store_item(it, comm, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_CAS:
MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes,
cas);
break;
}
#endif
switch (ret) {
case STORED:
out_string(c, "STORED");
break;
case EXISTS:
out_string(c, "EXISTS");
break;
case NOT_FOUND:
out_string(c, "NOT_FOUND");
break;
case NOT_STORED:
out_string(c, "NOT_STORED");
break;
default:
out_string(c, "SERVER_ERROR Unhandled storage type.");
}
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
/**
* get a pointer to the start of the request struct for the current command
*/
static void* binary_get_request(conn *c) {
char *ret = c->rcurr;
ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen +
c->binary_header.request.extlen);
assert(ret >= c->rbuf);
return ret;
}
/**
* get a pointer to the key in this request
*/
static char* binary_get_key(conn *c) {
return c->rcurr - (c->binary_header.request.keylen);
}
static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) {
protocol_binary_response_header* header;
assert(c);
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
/* XXX: out_string is inappropriate here */
out_string(c, "SERVER_ERROR out of memory");
return;
}
header = (protocol_binary_response_header *)c->wbuf;
header->response.magic = (uint8_t)PROTOCOL_BINARY_RES;
header->response.opcode = c->binary_header.request.opcode;
header->response.keylen = (uint16_t)htons(key_len);
header->response.extlen = (uint8_t)hdr_len;
header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
header->response.status = (uint16_t)htons(err);
header->response.bodylen = htonl(body_len);
header->response.opaque = c->opaque;
header->response.cas = htonll(c->cas);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d Writing bin response:", c->sfd);
for (ii = 0; ii < sizeof(header->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n>%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", header->bytes[ii]);
}
fprintf(stderr, "\n");
}
add_iov(c, c->wbuf, sizeof(header->response));
}
static void write_bin_error(conn *c, protocol_binary_response_status err, int swallow) {
const char *errstr = "Unknown error";
size_t len;
switch (err) {
case PROTOCOL_BINARY_RESPONSE_ENOMEM:
errstr = "Out of memory";
break;
case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
errstr = "Unknown command";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
errstr = "Not found";
break;
case PROTOCOL_BINARY_RESPONSE_EINVAL:
errstr = "Invalid arguments";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
errstr = "Data exists for key.";
break;
case PROTOCOL_BINARY_RESPONSE_E2BIG:
errstr = "Too large.";
break;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL:
errstr = "Non-numeric server-side value for incr or decr";
break;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
errstr = "Not stored.";
break;
case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR:
errstr = "Auth failure.";
break;
default:
assert(false);
errstr = "UNHANDLED ERROR";
fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err);
}
if (settings.verbose > 1) {
fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr);
}
len = strlen(errstr);
add_bin_header(c, err, 0, 0, len);
if (len > 0) {
add_iov(c, errstr, len);
}
conn_set_state(c, conn_mwrite);
if(swallow > 0) {
c->sbytes = swallow;
c->write_and_go = conn_swallow;
} else {
c->write_and_go = conn_new_cmd;
}
}
/* Form and send a response to a command over the binary protocol */
static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) {
if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET ||
c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_bin_header(c, 0, hlen, keylen, dlen);
if(dlen > 0) {
add_iov(c, d, dlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
conn_set_state(c, conn_new_cmd);
}
}
static void complete_incr_bin(conn *c) {
item *it;
char *key;
size_t nkey;
protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf;
protocol_binary_request_incr* req = binary_get_request(c);
assert(c != NULL);
assert(c->wsize >= sizeof(*rsp));
/* fix byteorder in the request */
req->message.body.delta = ntohll(req->message.body.delta);
req->message.body.initial = ntohll(req->message.body.initial);
req->message.body.expiration = ntohl(req->message.body.expiration);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int i;
fprintf(stderr, "incr ");
for (i = 0; i < nkey; i++) {
fprintf(stderr, "%c", key[i]);
}
fprintf(stderr, " %lld, %llu, %d\n",
(long long)req->message.body.delta,
(long long)req->message.body.initial,
req->message.body.expiration);
}
it = item_get(key, nkey);
if (it && (c->binary_header.request.cas == 0 ||
c->binary_header.request.cas == ITEM_get_cas(it))) {
/* Weird magic in add_delta forces me to pad here */
char tmpbuf[INCR_MAX_STORAGE_LEN];
protocol_binary_response_status st = PROTOCOL_BINARY_RESPONSE_SUCCESS;
switch(add_delta(c, it, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT,
req->message.body.delta, tmpbuf)) {
case OK:
break;
case NON_NUMERIC:
st = PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL;
break;
case EOM:
st = PROTOCOL_BINARY_RESPONSE_ENOMEM;
break;
}
if (st != PROTOCOL_BINARY_RESPONSE_SUCCESS) {
write_bin_error(c, st, 0);
} else {
rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10));
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0,
sizeof(rsp->message.body.value));
}
item_remove(it); /* release our reference */
} else if (!it && req->message.body.expiration != 0xffffffff) {
/* Save some room for the response */
rsp->message.body.value = htonll(req->message.body.initial);
it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration),
INCR_MAX_STORAGE_LEN);
if (it != NULL) {
snprintf(ITEM_data(it), INCR_MAX_STORAGE_LEN, "%llu",
(unsigned long long)req->message.body.initial);
if (store_item(it, NREAD_SET, c)) {
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value));
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
}
} else if (it) {
/* incorrect CAS */
item_remove(it); /* release our reference */
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
static void complete_update_bin(conn *c) {
protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL;
enum store_item_type ret = NOT_STORED;
assert(c != NULL);
item *it = c->item;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We don't actually receive the trailing two characters in the bin
* protocol, so we're going to just set them here */
*(ITEM_data(it) + it->nbytes - 2) = '\r';
*(ITEM_data(it) + it->nbytes - 1) = '\n';
ret = store_item(it, c->cmd, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
}
#endif
switch (ret) {
case STORED:
/* Stored */
write_bin_response(c, NULL, 0, 0, 0);
break;
case EXISTS:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
break;
case NOT_FOUND:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
break;
case NOT_STORED:
if (c->cmd == NREAD_ADD) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;
} else if(c->cmd == NREAD_REPLACE) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED;
}
write_bin_error(c, eno, 0);
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
static void process_bin_get(conn *c) {
item *it;
protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf;
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d GET ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
it = item_get(key, nkey);
if (it) {
/* the length has two unnecessary bytes ("\r\n") */
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_cmds++;
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
bodylen += nkey;
keylen = nkey;
}
add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen);
rsp->message.header.response.cas = htonll(ITEM_get_cas(it));
// add the flags
rsp->message.body.flags = htonl(strtoul(ITEM_suffix(it), NULL, 10));
add_iov(c, &rsp->message.body, sizeof(rsp->message.body));
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_iov(c, ITEM_key(it), nkey);
}
/* Add the data minus the CRLF */
add_iov(c, ITEM_data(it), it->nbytes - 2);
conn_set_state(c, conn_mwrite);
/* Remember this command so we can garbage collect it later */
c->item = it;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_cmds++;
c->thread->stats.get_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
if (c->noreply) {
conn_set_state(c, conn_new_cmd);
} else {
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
char *ofs = c->wbuf + sizeof(protocol_binary_response_header);
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, nkey, nkey);
memcpy(ofs, key, nkey);
add_iov(c, ofs, nkey);
conn_set_state(c, conn_mwrite);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
}
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
}
static void append_bin_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *buf = c->stats.buffer + c->stats.offset;
uint32_t bodylen = klen + vlen;
protocol_binary_response_header header = {
.response.magic = (uint8_t)PROTOCOL_BINARY_RES,
.response.opcode = PROTOCOL_BINARY_CMD_STAT,
.response.keylen = (uint16_t)htons(klen),
.response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES,
.response.bodylen = htonl(bodylen),
.response.opaque = c->opaque
};
memcpy(buf, header.bytes, sizeof(header.response));
buf += sizeof(header.response);
if (klen > 0) {
memcpy(buf, key, klen);
buf += klen;
if (vlen > 0) {
memcpy(buf, val, vlen);
}
}
c->stats.offset += sizeof(header.response) + bodylen;
}
static void append_ascii_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *pos = c->stats.buffer + c->stats.offset;
uint32_t nbytes = 0;
int remaining = c->stats.size - c->stats.offset;
int room = remaining - 1;
if (klen == 0 && vlen == 0) {
nbytes = snprintf(pos, room, "END\r\n");
} else if (vlen == 0) {
nbytes = snprintf(pos, room, "STAT %s\r\n", key);
} else {
nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val);
}
c->stats.offset += nbytes;
}
static bool grow_stats_buf(conn *c, size_t needed) {
size_t nsize = c->stats.size;
size_t available = nsize - c->stats.offset;
bool rv = true;
/* Special case: No buffer -- need to allocate fresh */
if (c->stats.buffer == NULL) {
nsize = 1024;
available = c->stats.size = c->stats.offset = 0;
}
while (needed > available) {
assert(nsize > 0);
nsize = nsize << 1;
available = nsize - c->stats.offset;
}
if (nsize != c->stats.size) {
char *ptr = realloc(c->stats.buffer, nsize);
if (ptr) {
c->stats.buffer = ptr;
c->stats.size = nsize;
} else {
rv = false;
}
}
return rv;
}
static void append_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
const void *cookie)
{
/* value without a key is invalid */
if (klen == 0 && vlen > 0) {
return ;
}
conn *c = (conn*)cookie;
if (c->protocol == binary_prot) {
size_t needed = vlen + klen + sizeof(protocol_binary_response_header);
if (!grow_stats_buf(c, needed)) {
return ;
}
append_bin_stats(key, klen, val, vlen, c);
} else {
size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n"
if (!grow_stats_buf(c, needed)) {
return ;
}
append_ascii_stats(key, klen, val, vlen, c);
}
assert(c->stats.offset <= c->stats.size);
}
static void process_bin_stat(conn *c) {
char *subcommand = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d STATS ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", subcommand[ii]);
}
fprintf(stderr, "\n");
}
if (nkey == 0) {
/* request all statistics */
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strncmp(subcommand, "reset", 5) == 0) {
stats_reset();
} else if (strncmp(subcommand, "settings", 8) == 0) {
process_stat_settings(&append_stats, c);
} else if (strncmp(subcommand, "detail", 6) == 0) {
char *subcmd_pos = subcommand + 6;
if (strncmp(subcmd_pos, " dump", 5) == 0) {
int len;
char *dump_buf = stats_prefix_dump(&len);
if (dump_buf == NULL || len <= 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
return ;
} else {
append_stats("detailed", strlen("detailed"), dump_buf, len, c);
free(dump_buf);
}
} else if (strncmp(subcmd_pos, " on", 3) == 0) {
settings.detail_enabled = 1;
} else if (strncmp(subcmd_pos, " off", 4) == 0) {
settings.detail_enabled = 0;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
return;
}
} else {
if (get_stats(subcommand, nkey, &append_stats, c)) {
if (c->stats.buffer == NULL) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
return;
}
/* Append termination package and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) {
assert(c);
c->substate = next_substate;
c->rlbytes = c->keylen + extra;
/* Ok... do we have room for the extras and the key in the input buffer? */
ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf;
if (c->rlbytes > c->rsize - offset) {
size_t nsize = c->rsize;
size_t size = c->rlbytes + sizeof(protocol_binary_request_header);
while (size > nsize) {
nsize *= 2;
}
if (nsize != c->rsize) {
if (settings.verbose > 1) {
fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n",
c->sfd, (unsigned long)c->rsize, (unsigned long)nsize);
}
char *newm = realloc(c->rbuf, nsize);
if (newm == NULL) {
if (settings.verbose) {
fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n",
c->sfd);
}
conn_set_state(c, conn_closing);
return;
}
c->rbuf= newm;
/* rcurr should point to the same offset in the packet */
c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header);
c->rsize = nsize;
}
if (c->rbuf != c->rcurr) {
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Repack input buffer\n", c->sfd);
}
}
}
/* preserve the header in the buffer.. */
c->ritem = c->rcurr + sizeof(protocol_binary_request_header);
conn_set_state(c, conn_nread);
}
/* Just write an error message and disconnect the client */
static void handle_binary_protocol_error(conn *c) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, 0);
if (settings.verbose) {
fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n",
c->binary_header.request.opcode, c->sfd);
}
c->write_and_go = conn_closing;
}
static void init_sasl_conn(conn *c) {
assert(c);
/* should something else be returned? */
if (!settings.sasl)
return;
if (!c->sasl_conn) {
int result=sasl_server_new("memcached",
NULL, NULL, NULL, NULL,
NULL, 0, &c->sasl_conn);
if (result != SASL_OK) {
if (settings.verbose) {
fprintf(stderr, "Failed to initialize SASL conn.\n");
}
c->sasl_conn = NULL;
}
}
}
static void bin_list_sasl_mechs(conn *c) {
// Guard against a disabled SASL.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
init_sasl_conn(c);
const char *result_string = NULL;
unsigned int string_length = 0;
int result=sasl_listmech(c->sasl_conn, NULL,
"", /* What to prepend the string with */
" ", /* What to separate mechanisms with */
"", /* What to append to the string */
&result_string, &string_length,
NULL);
if (result != SASL_OK) {
/* Perhaps there's a better error for this... */
if (settings.verbose) {
fprintf(stderr, "Failed to list SASL mechanisms.\n");
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
return;
}
write_bin_response(c, (char*)result_string, 0, 0, string_length);
}
static void process_bin_sasl_auth(conn *c) {
// Guard for handling disabled SASL on the server.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
assert(c->binary_header.request.extlen == 0);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > MAX_SASL_MECH_LEN) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, vlen);
c->write_and_go = conn_swallow;
return;
}
char *key = binary_get_key(c);
assert(key);
item *it = item_alloc(key, nkey, 0, 0, vlen);
if (it == 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
c->write_and_go = conn_swallow;
return;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_reading_sasl_auth_data;
}
static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
}
}
static bool authenticated(conn *c) {
assert(settings.sasl);
bool rv = false;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */
rv = true;
break;
default:
if (c->sasl_conn) {
const void *uname = NULL;
sasl_getprop(c->sasl_conn, SASL_USERNAME, &uname);
rv = uname != NULL;
}
}
if (settings.verbose > 1) {
fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n",
c->cmd, rv ? "true" : "false");
}
return rv;
}
static void dispatch_bin_command(conn *c) {
int protocol_error = 0;
int extlen = c->binary_header.request.extlen;
int keylen = c->binary_header.request.keylen;
uint32_t bodylen = c->binary_header.request.bodylen;
if (settings.sasl && !authenticated(c)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
c->write_and_go = conn_closing;
return;
}
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
c->noreply = true;
/* binprot supports 16bit keys, but internals are still 8bit */
if (keylen > KEY_MAX_LENGTH) {
handle_binary_protocol_error(c);
return;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SETQ:
c->cmd = PROTOCOL_BINARY_CMD_SET;
break;
case PROTOCOL_BINARY_CMD_ADDQ:
c->cmd = PROTOCOL_BINARY_CMD_ADD;
break;
case PROTOCOL_BINARY_CMD_REPLACEQ:
c->cmd = PROTOCOL_BINARY_CMD_REPLACE;
break;
case PROTOCOL_BINARY_CMD_DELETEQ:
c->cmd = PROTOCOL_BINARY_CMD_DELETE;
break;
case PROTOCOL_BINARY_CMD_INCREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_INCREMENT;
break;
case PROTOCOL_BINARY_CMD_DECREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_DECREMENT;
break;
case PROTOCOL_BINARY_CMD_QUITQ:
c->cmd = PROTOCOL_BINARY_CMD_QUIT;
break;
case PROTOCOL_BINARY_CMD_FLUSHQ:
c->cmd = PROTOCOL_BINARY_CMD_FLUSH;
break;
case PROTOCOL_BINARY_CMD_APPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_PREPEND;
break;
case PROTOCOL_BINARY_CMD_GETQ:
c->cmd = PROTOCOL_BINARY_CMD_GET;
break;
case PROTOCOL_BINARY_CMD_GETKQ:
c->cmd = PROTOCOL_BINARY_CMD_GETK;
break;
default:
c->noreply = false;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_VERSION:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, VERSION, 0, 0, strlen(VERSION));
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_FLUSH:
if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) {
bin_read_key(c, bin_read_flush_exptime, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_NOOP:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_REPLACE:
if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) {
bin_read_key(c, bin_reading_set_header, 8);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETK:
if (extlen == 0 && bodylen == keylen && keylen > 0) {
bin_read_key(c, bin_reading_get_key, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_DELETE:
if (keylen > 0 && extlen == 0 && bodylen == keylen) {
bin_read_key(c, bin_reading_del_header, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_INCREMENT:
case PROTOCOL_BINARY_CMD_DECREMENT:
if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) {
bin_read_key(c, bin_reading_incr_header, 20);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_APPEND:
case PROTOCOL_BINARY_CMD_PREPEND:
if (keylen > 0 && extlen == 0) {
bin_read_key(c, bin_reading_set_header, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_STAT:
if (extlen == 0) {
bin_read_key(c, bin_reading_stat, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_QUIT:
if (keylen == 0 && extlen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
c->write_and_go = conn_closing;
if (c->noreply) {
conn_set_state(c, conn_closing);
}
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
bin_list_sasl_mechs(c);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_AUTH:
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (extlen == 0 && keylen != 0) {
bin_read_key(c, bin_reading_sasl_auth, 0);
} else {
protocol_error = 1;
}
break;
default:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, bodylen);
}
if (protocol_error)
handle_binary_protocol_error(c);
}
static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, vlen);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
}
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey);
if (it) {
item_unlink(it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_append_prepend(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
vlen = c->binary_header.request.bodylen - nkey;
if (settings.verbose > 1) {
fprintf(stderr, "Value len is %d\n", vlen);
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, 0, 0, vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, 0, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, vlen);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_APPEND:
c->cmd = NREAD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPEND:
c->cmd = NREAD_PREPEND;
break;
default:
assert(0);
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_flush(conn *c) {
time_t exptime = 0;
protocol_binary_request_flush* req = binary_get_request(c);
if (c->binary_header.request.extlen == sizeof(req->message.body)) {
exptime = ntohl(req->message.body.expiration);
}
set_current_time();
if (exptime > 0) {
settings.oldest_live = realtime(exptime) - 1;
} else {
settings.oldest_live = current_time - 1;
}
item_flush_expired();
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_response(c, NULL, 0, 0, 0);
}
static void process_bin_delete(conn *c) {
item *it;
protocol_binary_request_delete* req = binary_get_request(c);
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
assert(c != NULL);
if (settings.verbose > 1) {
fprintf(stderr, "Deleting %s\n", key);
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey);
if (it) {
uint64_t cas = ntohll(req->message.header.request.cas);
if (cas == 0 || cas == ITEM_get_cas(it)) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
item_unlink(it);
write_bin_response(c, NULL, 0, 0, 0);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
static void complete_nread_binary(conn *c) {
assert(c != NULL);
assert(c->cmd >= 0);
switch(c->substate) {
case bin_reading_set_header:
if (c->cmd == PROTOCOL_BINARY_CMD_APPEND ||
c->cmd == PROTOCOL_BINARY_CMD_PREPEND) {
process_bin_append_prepend(c);
} else {
process_bin_update(c);
}
break;
case bin_read_set_value:
complete_update_bin(c);
break;
case bin_reading_get_key:
process_bin_get(c);
break;
case bin_reading_stat:
process_bin_stat(c);
break;
case bin_reading_del_header:
process_bin_delete(c);
break;
case bin_reading_incr_header:
complete_incr_bin(c);
break;
case bin_read_flush_exptime:
process_bin_flush(c);
break;
case bin_reading_sasl_auth:
process_bin_sasl_auth(c);
break;
case bin_reading_sasl_auth_data:
process_bin_complete_sasl_auth(c);
break;
default:
fprintf(stderr, "Not handling substate %d\n", c->substate);
assert(0);
}
}
static void reset_cmd_handler(conn *c) {
c->cmd = -1;
c->substate = bin_no_state;
if(c->item != NULL) {
item_remove(c->item);
c->item = NULL;
}
conn_shrink(c);
if (c->rbytes > 0) {
conn_set_state(c, conn_parse_cmd);
} else {
conn_set_state(c, conn_waiting);
}
}
static void complete_nread(conn *c) {
assert(c != NULL);
assert(c->protocol == ascii_prot
|| c->protocol == binary_prot);
if (c->protocol == ascii_prot) {
complete_nread_ascii(c);
} else if (c->protocol == binary_prot) {
complete_nread_binary(c);
}
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns the state of storage.
*/
enum store_item_type do_store_item(item *it, int comm, conn *c) {
char *key = ITEM_key(it);
item *old_it = do_item_get(key, it->nkey);
enum store_item_type stored = NOT_STORED;
item *new_it = NULL;
int flags;
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && (comm == NREAD_REPLACE
|| comm == NREAD_APPEND || comm == NREAD_PREPEND))
{
/* replace only replaces an existing value; don't store */
} else if (comm == NREAD_CAS) {
/* validate cas operation */
if(old_it == NULL) {
// LRU expired
stored = NOT_FOUND;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.cas_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) {
// cas validates
// it and old_it may belong to different classes.
// I'm updating the stats for the one that's getting pushed out
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[old_it->slabs_clsid].cas_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_replace(old_it, it);
stored = STORED;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[old_it->slabs_clsid].cas_badval++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(settings.verbose > 1) {
fprintf(stderr, "CAS: failure: expected %llu, got %llu\n",
(unsigned long long)ITEM_get_cas(old_it),
(unsigned long long)ITEM_get_cas(it));
}
stored = EXISTS;
}
} else {
/*
* Append - combine new and old record into single one. Here it's
* atomic and thread-safe.
*/
if (comm == NREAD_APPEND || comm == NREAD_PREPEND) {
/*
* Validate CAS
*/
if (ITEM_get_cas(it) != 0) {
// CAS much be equal
if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) {
stored = EXISTS;
}
}
if (stored == NOT_STORED) {
/* we have it and old_it here - alloc memory to hold both */
/* flags was already lost - so recover them from ITEM_suffix(it) */
flags = (int) strtol(ITEM_suffix(old_it), (char **) NULL, 10);
new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */);
if (new_it == NULL) {
/* SERVER_ERROR out of memory */
if (old_it != NULL)
do_item_remove(old_it);
return NOT_STORED;
}
/* copy data from it and old_it to new_it */
if (comm == NREAD_APPEND) {
memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes);
memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(it), it->nbytes);
} else {
/* NREAD_PREPEND */
memcpy(ITEM_data(new_it), ITEM_data(it), it->nbytes);
memcpy(ITEM_data(new_it) + it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes);
}
it = new_it;
}
}
if (stored == NOT_STORED) {
if (old_it != NULL)
item_replace(old_it, it);
else
do_item_link(it);
c->cas = ITEM_get_cas(it);
stored = STORED;
}
}
if (old_it != NULL)
do_item_remove(old_it); /* release our reference */
if (new_it != NULL)
do_item_remove(new_it);
if (stored == STORED) {
c->cas = ITEM_get_cas(it);
}
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 8
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
for (s = e = command; ntokens < max_tokens - 1; ++e) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
}
s = e + 1;
}
else if (*e == '\0') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
break; /* string end */
}
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
/* set up a connection to write a buffer then free it, used for stats */
static void write_and_free(conn *c, char *buf, int bytes) {
if (buf) {
c->write_and_free = buf;
c->wcurr = buf;
c->wbytes = bytes;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
} else {
out_string(c, "SERVER_ERROR out of memory writing stats");
}
}
static inline void set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens)
{
int noreply_index = ntokens - 2;
/*
NOTE: this function is not the first place where we are going to
send the reply. We could send it instead from process_command()
if the request line has wrong number of tokens. However parsing
malformed line for "noreply" option is not reliable anyway, so
it can't be helped.
*/
if (tokens[noreply_index].value
&& strcmp(tokens[noreply_index].value, "noreply") == 0) {
c->noreply = true;
}
}
void append_stat(const char *name, ADD_STAT add_stats, conn *c,
const char *fmt, ...) {
char val_str[STAT_VAL_LEN];
int vlen;
va_list ap;
assert(name);
assert(add_stats);
assert(c);
assert(fmt);
va_start(ap, fmt);
vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap);
va_end(ap);
add_stats(name, strlen(name), val_str, vlen, c);
}
inline static void process_stats_detail(conn *c, const char *command) {
assert(c != NULL);
if (strcmp(command, "on") == 0) {
settings.detail_enabled = 1;
out_string(c, "OK");
}
else if (strcmp(command, "off") == 0) {
settings.detail_enabled = 0;
out_string(c, "OK");
}
else if (strcmp(command, "dump") == 0) {
int len;
char *stats = stats_prefix_dump(&len);
write_and_free(c, stats, len);
}
else {
out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump");
}
}
/* return server specific stats only */
static void server_stats(ADD_STAT add_stats, conn *c) {
pid_t pid = getpid();
rel_time_t now = current_time;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(&thread_stats);
struct slab_stats slab_stats;
slab_stats_aggregate(&thread_stats, &slab_stats);
#ifndef WIN32
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
#endif /* !WIN32 */
STATS_LOCK();
APPEND_STAT("pid", "%lu", (long)pid);
APPEND_STAT("uptime", "%u", now);
APPEND_STAT("time", "%ld", now + (long)process_started);
APPEND_STAT("version", "%s", VERSION);
APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *)));
#ifndef WIN32
append_stat("rusage_user", add_stats, c, "%ld.%06ld",
(long)usage.ru_utime.tv_sec,
(long)usage.ru_utime.tv_usec);
append_stat("rusage_system", add_stats, c, "%ld.%06ld",
(long)usage.ru_stime.tv_sec,
(long)usage.ru_stime.tv_usec);
#endif /* !WIN32 */
APPEND_STAT("curr_connections", "%u", stats.curr_conns - 1);
APPEND_STAT("total_connections", "%u", stats.total_conns);
APPEND_STAT("connection_structures", "%u", stats.conn_structs);
APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds);
APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds);
APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds);
APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits);
APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses);
APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses);
APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits);
APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses);
APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits);
APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses);
APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits);
APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses);
APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits);
APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval);
APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read);
APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written);
APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("accepting_conns", "%u", stats.accepting_conns);
APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num);
APPEND_STAT("threads", "%d", settings.num_threads);
APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields);
STATS_UNLOCK();
}
static void process_stat_settings(ADD_STAT add_stats, void *c) {
assert(add_stats);
APPEND_STAT("maxbytes", "%u", (unsigned int)settings.maxbytes);
APPEND_STAT("maxconns", "%d", settings.maxconns);
APPEND_STAT("tcpport", "%d", settings.port);
APPEND_STAT("udpport", "%d", settings.udpport);
APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL");
APPEND_STAT("verbosity", "%d", settings.verbose);
APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live);
APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off");
APPEND_STAT("domain_socket", "%s",
settings.socketpath ? settings.socketpath : "NULL");
APPEND_STAT("umask", "%o", settings.access);
APPEND_STAT("growth_factor", "%.2f", settings.factor);
APPEND_STAT("chunk_size", "%d", settings.chunk_size);
APPEND_STAT("num_threads", "%d", settings.num_threads);
APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter);
APPEND_STAT("detail_enabled", "%s",
settings.detail_enabled ? "yes" : "no");
APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event);
APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no");
APPEND_STAT("tcp_backlog", "%d", settings.backlog);
APPEND_STAT("binding_protocol", "%s",
prot_text(settings.binding_protocol));
APPEND_STAT("item_size_max", "%d", settings.item_size_max);
}
static void process_stat(conn *c, token_t *tokens, const size_t ntokens) {
const char *subcommand = tokens[SUBCOMMAND_TOKEN].value;
assert(c != NULL);
if (ntokens < 2) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (ntokens == 2) {
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strcmp(subcommand, "reset") == 0) {
stats_reset();
out_string(c, "RESET");
return ;
} else if (strcmp(subcommand, "detail") == 0) {
/* NOTE: how to tackle detail with binary? */
if (ntokens < 4)
process_stats_detail(c, ""); /* outputs the error message */
else
process_stats_detail(c, tokens[2].value);
/* Output already generated */
return ;
} else if (strcmp(subcommand, "settings") == 0) {
process_stat_settings(&append_stats, c);
} else if (strcmp(subcommand, "cachedump") == 0) {
char *buf;
unsigned int bytes, id, limit = 0;
if (ntokens < 5) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (!safe_strtoul(tokens[2].value, &id) ||
!safe_strtoul(tokens[3].value, &limit)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (id >= POWER_LARGEST) {
out_string(c, "CLIENT_ERROR Illegal slab id");
return;
}
buf = item_cachedump(id, limit, &bytes);
write_and_free(c, buf, bytes);
return ;
} else {
/* getting here means that the subcommand is either engine specific or
is invalid. query the engine and see. */
if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_string(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
out_string(c, "ERROR");
}
return ;
}
/* append terminator and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_string(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
/* ntokens is overwritten here... shrug.. */
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) {
char *key;
size_t nkey;
int i = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
assert(c != NULL);
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
it = item_get(key, nkey);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
item_remove(it);
break;
}
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
item_remove(it);
break;
}
}
suffix = cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
out_string(c, "SERVER_ERROR out of memory making CAS suffix");
item_remove(it);
return;
}
*(c->suffixlist + i) = suffix;
int suffix_len = snprintf(suffix, SUFFIX_SIZE,
" %llu\r\n",
(unsigned long long)ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0 ||
add_iov(c, suffix, suffix_len) != 0 ||
add_iov(c, ITEM_data(it), it->nbytes) != 0)
{
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
}
if (settings.verbose > 1)
fprintf(stderr, ">%d sending key %s\n", c->sfd, ITEM_key(it));
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_update(it);
*(c->ilist + i) = it;
i++;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas) {
c->suffixcurr = c->suffixlist;
c->suffixleft = i;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_string(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
return;
}
static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
// does cas value exist?
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
vlen += 2;
if (vlen < 0 || vlen - 2 < 0) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
if (! item_size_ok(nkey, flags, vlen))
out_string(c, "SERVER_ERROR object too large for cache");
else
out_string(c, "SERVER_ERROR out of memory storing object");
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey);
if (it) {
item_unlink(it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) {
char temp[INCR_MAX_STORAGE_LEN];
item *it;
uint64_t delta;
char *key;
size_t nkey;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtoull(tokens[2].value, &delta)) {
out_string(c, "CLIENT_ERROR invalid numeric delta argument");
return;
}
it = item_get(key, nkey);
if (!it) {
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
return;
}
switch(add_delta(c, it, incr, delta, temp)) {
case OK:
out_string(c, temp);
break;
case NON_NUMERIC:
out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value");
break;
case EOM:
out_string(c, "SERVER_ERROR out of memory");
break;
}
item_remove(it); /* release our reference */
}
/*
* adds a delta value to a numeric item.
*
* c connection requesting the operation
* it item to adjust
* incr true to increment value, false to decrement
* delta amount to adjust value by
* buf buffer for response string
*
* returns a response string to send back to the client.
*/
enum delta_result_type do_add_delta(conn *c, item *it, const bool incr,
const int64_t delta, char *buf) {
char *ptr;
uint64_t value;
int res;
ptr = ITEM_data(it);
if (!safe_strtoull(ptr, &value)) {
return NON_NUMERIC;
}
if (incr) {
value += delta;
MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value);
} else {
if(delta > value) {
value = 0;
} else {
value -= delta;
}
MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value);
}
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.slab_stats[it->slabs_clsid].incr_hits++;
} else {
c->thread->stats.slab_stats[it->slabs_clsid].decr_hits++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value);
res = strlen(buf);
if (res + 2 > it->nbytes) { /* need to realloc */
item *new_it;
new_it = do_item_alloc(ITEM_key(it), it->nkey, atoi(ITEM_suffix(it) + 1), it->exptime, res + 2 );
if (new_it == 0) {
return EOM;
}
memcpy(ITEM_data(new_it), buf, res);
memcpy(ITEM_data(new_it) + res, "\r\n", 2);
item_replace(it, new_it);
do_item_remove(new_it); /* release our reference */
} else { /* replace in-place */
/* When changing the value without replacing the item, we
need to update the CAS on the existing item. */
ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
memcpy(ITEM_data(it), buf, res);
memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2);
}
return OK;
}
static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey);
if (it) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
item_remove(it); /* release our reference */
out_string(c, "DELETED");
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
level = strtoul(tokens[1].value, NULL, 10);
settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level;
out_string(c, "OK");
return;
}
static void process_command(conn *c, char *command) {
token_t tokens[MAX_TOKENS];
size_t ntokens;
int comm;
assert(c != NULL);
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
if (settings.verbose > 1)
fprintf(stderr, "<%d %s\n", c->sfd, command);
/*
* for commands set/add/replace, we build an item and read the data
* directly into it, then continue in nread_complete().
*/
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory preparing response");
return;
}
ntokens = tokenize_command(command, tokens, MAX_TOKENS);
if (ntokens >= 3 &&
((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) ||
(strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) {
process_get_command(c, tokens, ntokens, false);
} else if ((ntokens == 6 || ntokens == 7) &&
((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) {
process_update_command(c, tokens, ntokens, comm, false);
} else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) {
process_update_command(c, tokens, ntokens, comm, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 1);
} else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) {
process_get_command(c, tokens, ntokens, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 0);
} else if (ntokens >= 3 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) {
process_delete_command(c, tokens, ntokens);
} else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) {
process_stat(c, tokens, ntokens);
} else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) {
time_t exptime = 0;
set_current_time();
set_noreply_maybe(c, tokens, ntokens);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(ntokens == (c->noreply ? 3 : 2)) {
settings.oldest_live = current_time - 1;
item_flush_expired();
out_string(c, "OK");
return;
}
exptime = strtol(tokens[1].value, NULL, 10);
if(errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/*
If exptime is zero realtime() would return zero too, and
realtime(exptime) - 1 would overflow to the max unsigned
value. So we process exptime == 0 the same way we do when
no delay is given at all.
*/
if (exptime > 0)
settings.oldest_live = realtime(exptime) - 1;
else /* exptime == 0 */
settings.oldest_live = current_time - 1;
item_flush_expired();
out_string(c, "OK");
return;
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) {
out_string(c, "VERSION " VERSION);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) {
conn_set_state(c, conn_closing);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) {
process_verbosity_command(c, tokens, ntokens);
} else {
out_string(c, "ERROR");
}
return;
}
/*
* if we have a complete line in the buffer, process it.
*/
static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
/*
* read a UDP request.
*/
static enum try_read_result try_read_udp(conn *c) {
int res;
assert(c != NULL);
c->request_addr_size = sizeof(c->request_addr);
res = recvfrom(c->sfd, c->rbuf, c->rsize,
0, &c->request_addr, &c->request_addr_size);
if (res > 8) {
unsigned char *buf = (unsigned char *)c->rbuf;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* Beginning of UDP packet is the request ID; save it. */
c->request_id = buf[0] * 256 + buf[1];
/* If this is a multi-packet request, drop it. */
if (buf[4] != 0 || buf[5] != 1) {
out_string(c, "SERVER_ERROR multi-packet request not supported");
return READ_NO_DATA_RECEIVED;
}
/* Don't care about any of the rest of the header. */
res -= 8;
memmove(c->rbuf, c->rbuf + 8, res);
c->rbytes += res;
c->rcurr = c->rbuf;
return READ_DATA_RECEIVED;
}
return READ_NO_DATA_RECEIVED;
}
/*
* read from network as much as we can, handle buffer overflow and connection
* close.
* before reading, move the remaining incomplete fragment of a command
* (if any) to the beginning of the buffer.
*
* To protect us from someone flooding a connection with bogus data causing
* the connection to eat up all available memory, break out and start looking
* at the data I've got after a number of reallocs...
*
* @return enum try_read_result
*/
static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
int num_allocs = 0;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
if (num_allocs == 4) {
return gotdata;
}
++num_allocs;
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't realloc input buffer\n");
c->rbytes = 0; /* ignore what we read */
out_string(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = read(c->sfd, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
static bool update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags)
return true;
if (event_del(&c->event) == -1) return false;
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) return false;
return true;
}
/*
* Sets whether we are listening for new connections or not.
*/
void do_accept_new_conns(const bool do_accept) {
conn *next;
for (next = listen_conn; next; next = next->next) {
if (do_accept) {
update_event(next, EV_READ | EV_PERSIST);
if (listen(next->sfd, settings.backlog) != 0) {
perror("listen");
}
}
else {
update_event(next, 0);
if (listen(next->sfd, 0) != 0) {
perror("listen");
}
}
}
if (do_accept) {
STATS_LOCK();
stats.accepting_conns = true;
STATS_UNLOCK();
} else {
STATS_LOCK();
stats.accepting_conns = false;
stats.listen_disabled_num++;
STATS_UNLOCK();
}
}
/*
* Transmit the next chunk of data from our list of msgbuf structures.
*
* Returns:
* TRANSMIT_COMPLETE All done writing.
* TRANSMIT_INCOMPLETE More data remaining to write.
* TRANSMIT_SOFT_ERROR Can't write any more right now.
* TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
*/
static enum transmit_result transmit(conn *c) {
assert(c != NULL);
if (c->msgcurr < c->msgused &&
c->msglist[c->msgcurr].msg_iovlen == 0) {
/* Finished writing the current msg; advance to the next. */
c->msgcurr++;
}
if (c->msgcurr < c->msgused) {
ssize_t res;
struct msghdr *m = &c->msglist[c->msgcurr];
res = sendmsg(c->sfd, m, 0);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_written += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We've written some of the data. Remove the completed
iovec entries from the list of pending writes. */
while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) {
res -= m->msg_iov->iov_len;
m->msg_iovlen--;
m->msg_iov++;
}
/* Might have written just part of the last iovec entry;
adjust it so the next write will do the rest. */
if (res > 0) {
m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res;
m->msg_iov->iov_len -= res;
}
return TRANSMIT_INCOMPLETE;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
}
return TRANSMIT_SOFT_ERROR;
}
/* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK,
we have a real error, on which we close the connection */
if (settings.verbose > 0)
perror("Failed to write, and not due to blocking");
if (IS_UDP(c->transport))
conn_set_state(c, conn_read);
else
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
} else {
return TRANSMIT_COMPLETE;
}
}
static void drive_machine(conn *c) {
bool stop = false;
int sfd, flags = 1;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, tcp_transport);
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = read(c->sfd, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes == 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
while (c->suffixleft > 0) {
char *suffix = *(c->suffixcurr);
cache_free(c->thread->suffix_cache, suffix);
c->suffixcurr++;
c->suffixleft--;
}
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
}
void event_handler(const int fd, const short which, void *arg) {
conn *c;
c = (conn *)arg;
assert(c != NULL);
c->which = which;
/* sanity */
if (fd != c->sfd) {
if (settings.verbose > 0)
fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n");
conn_close(c);
return;
}
drive_machine(c);
/* wait for next event */
return;
}
static int new_socket(struct addrinfo *ai) {
int sfd;
int flags;
if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
/*
* Sets a socket's send buffer size to the maximum allowed by the system.
*/
static void maximize_sndbuf(const int sfd) {
socklen_t intsize = sizeof(int);
int last_good = 0;
int min, max, avg;
int old_size;
/* Start with the default size. */
if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) {
if (settings.verbose > 0)
perror("getsockopt(SO_SNDBUF)");
return;
}
/* Binary-search for the real maximum. */
min = old_size;
max = MAX_SENDBUF_SIZE;
while (min <= max) {
avg = ((unsigned int)(min + max)) / 2;
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) {
last_good = avg;
min = avg + 1;
} else {
max = avg - 1;
}
}
if (settings.verbose > 1)
fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good);
}
/**
* Create a socket and bind it to a specific port number
* @param port the port number to bind to
* @param transport the transport protocol (TCP / UDP)
* @param portnumber_file A filepointer to write the port numbers to
* when they are successfully added to the list of ports we
* listen on.
*/
static int server_socket(int port, enum network_transport transport,
FILE *portnumber_file) {
int sfd;
struct linger ling = {0, 0};
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = { .ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC };
char port_buf[NI_MAXSERV];
int error;
int success = 0;
int flags =1;
hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM;
if (port == -1) {
port = 0;
}
snprintf(port_buf, sizeof(port_buf), "%d", port);
error= getaddrinfo(settings.inter, port_buf, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM)
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
else
perror("getaddrinfo()");
return 1;
}
for (next= ai; next; next= next->ai_next) {
conn *listen_conn_add;
if ((sfd = new_socket(next)) == -1) {
/* getaddrinfo can return "junk" addresses,
* we make sure at least one works before erroring.
*/
continue;
}
#ifdef IPV6_V6ONLY
if (next->ai_family == AF_INET6) {
error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags));
if (error != 0) {
perror("setsockopt");
close(sfd);
continue;
}
}
#endif
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
if (IS_UDP(transport)) {
maximize_sndbuf(sfd);
} else {
error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
}
if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
if (errno != EADDRINUSE) {
perror("bind()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
close(sfd);
continue;
} else {
success++;
if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
if (portnumber_file != NULL &&
(next->ai_addr->sa_family == AF_INET ||
next->ai_addr->sa_family == AF_INET6)) {
union {
struct sockaddr_in in;
struct sockaddr_in6 in6;
} my_sockaddr;
socklen_t len = sizeof(my_sockaddr);
if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
if (next->ai_addr->sa_family == AF_INET) {
fprintf(portnumber_file, "%s INET: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in.sin_port));
} else {
fprintf(portnumber_file, "%s INET6: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in6.sin6_port));
}
}
}
}
if (IS_UDP(transport)) {
int c;
for (c = 0; c < settings.num_threads; c++) {
/* this is guaranteed to hit all threads because we round-robin */
dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,
UDP_READ_BUFFER_SIZE, transport);
}
} else {
if (!(listen_conn_add = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
listen_conn_add->next = listen_conn;
listen_conn = listen_conn_add;
}
}
freeaddrinfo(ai);
/* Return zero iff we detected no errors in starting up connections */
return success == 0;
}
static int new_socket_unix(void) {
int sfd;
int flags;
if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket()");
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
static int server_socket_unix(const char *path, int access_mask) {
int sfd;
struct linger ling = {0, 0};
struct sockaddr_un addr;
struct stat tstat;
int flags =1;
int old_umask;
if (!path) {
return 1;
}
if ((sfd = new_socket_unix()) == -1) {
return 1;
}
/*
* Clean up a previous socket file if we left it around
*/
if (lstat(path, &tstat) == 0) {
if (S_ISSOCK(tstat.st_mode))
unlink(path);
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/*
* the memset call clears nonstandard fields in some impementations
* that otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
assert(strcmp(addr.sun_path, path) == 0);
old_umask = umask( ~(access_mask&0777));
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind()");
close(sfd);
umask(old_umask);
return 1;
}
umask(old_umask);
if (listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
return 1;
}
if (!(listen_conn = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
local_transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*
* We keep the current time of day in a global variable that's updated by a
* timer event. This saves us a bunch of time() system calls (we really only
* need to get the time once a second, whereas there can be tens of thousands
* of requests a second) and allows us to use server-start-relative timestamps
* rather than absolute UNIX timestamps, a space savings on systems where
* sizeof(time_t) > sizeof(unsigned int).
*/
volatile rel_time_t current_time;
static struct event clockevent;
/* time-sensitive callers can call it by hand with this, outside the normal ever-1-second timer */
static void set_current_time(void) {
struct timeval timer;
gettimeofday(&timer, NULL);
current_time = (rel_time_t) (timer.tv_sec - process_started);
}
static void clock_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
static bool initialized = false;
if (initialized) {
/* only delete the event if it's actually there. */
evtimer_del(&clockevent);
} else {
initialized = true;
}
evtimer_set(&clockevent, clock_handler, 0);
event_base_set(main_base, &clockevent);
evtimer_add(&clockevent, &t);
set_current_time();
}
static void usage(void) {
printf(PACKAGE " " VERSION "\n");
printf("-p <num> TCP port number to listen on (default: 11211)\n"
"-U <num> UDP port number to listen on (default: 11211, 0 is off)\n"
"-s <file> UNIX socket path to listen on (disables network support)\n"
"-a <mask> access mask for UNIX socket, in octal (default: 0700)\n"
"-l <ip_addr> interface to listen on (default: INADDR_ANY, all addresses)\n"
"-d run as a daemon\n"
"-r maximize core file limit\n"
"-u <username> assume identity of <username> (only when run as root)\n"
"-m <num> max memory to use for items in megabytes (default: 64 MB)\n"
"-M return error on memory exhausted (rather than removing items)\n"
"-c <num> max simultaneous connections (default: 1024)\n"
"-k lock down all paged memory. Note that there is a\n"
" limit on how much memory you may lock. Trying to\n"
" allocate more than that would fail, so be sure you\n"
" set the limit correctly for the user you started\n"
" the daemon with (not for -u <username> user;\n"
" under sh this is done with 'ulimit -S -l NUM_KB').\n"
"-v verbose (print errors/warnings while in event loop)\n"
"-vv very verbose (also print client commands/reponses)\n"
"-vvv extremely verbose (also print internal state transitions)\n"
"-h print this help and exit\n"
"-i print memcached and libevent license\n"
"-P <file> save PID in <file>, only used with -d option\n"
"-f <factor> chunk size growth factor (default: 1.25)\n"
"-n <bytes> minimum space allocated for key+value+flags (default: 48)\n");
printf("-L Try to use large memory pages (if available). Increasing\n"
" the memory page size could reduce the number of TLB misses\n"
" and improve the performance. In order to get large pages\n"
" from the OS, memcached will allocate the total item-cache\n"
" in one large chunk.\n");
printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n"
" This is used for per-prefix stats reporting. The default is\n"
" \":\" (colon). If this option is specified, stats collection\n"
" is turned on automatically; if not, then it may be turned on\n"
" by sending the \"stats detail on\" command to the server.\n");
printf("-t <num> number of threads to use (default: 4)\n");
printf("-R Maximum number of requests per event, limits the number of\n"
" requests process for a given connection to prevent \n"
" starvation (default: 20)\n");
printf("-C Disable use of CAS\n");
printf("-b Set the backlog queue limit (default: 1024)\n");
printf("-B Binding protocol - one of ascii, binary, or auto (default)\n");
printf("-I Override the size of each slab page. Adjusts max item size\n"
" (default: 1mb, min: 1k, max: 128m)\n");
#ifdef ENABLE_SASL
printf("-S Turn on Sasl authentication\n");
#endif
return;
}
static void usage_license(void) {
printf(PACKAGE " " VERSION "\n\n");
printf(
"Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are\n"
"met:\n"
"\n"
" * Redistributions of source code must retain the above copyright\n"
"notice, this list of conditions and the following disclaimer.\n"
"\n"
" * Redistributions in binary form must reproduce the above\n"
"copyright notice, this list of conditions and the following disclaimer\n"
"in the documentation and/or other materials provided with the\n"
"distribution.\n"
"\n"
" * Neither the name of the Danga Interactive nor the names of its\n"
"contributors may be used to endorse or promote products derived from\n"
"this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"\n"
"\n"
"This product includes software developed by Niels Provos.\n"
"\n"
"[ libevent ]\n"
"\n"
"Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions\n"
"are met:\n"
"1. Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
"3. All advertising materials mentioning features or use of this software\n"
" must display the following acknowledgement:\n"
" This product includes software developed by Niels Provos.\n"
"4. The name of the author may not be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n"
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
);
return;
}
static void save_pid(const pid_t pid, const char *pid_file) {
FILE *fp;
if (pid_file == NULL)
return;
if ((fp = fopen(pid_file, "w")) == NULL) {
fprintf(stderr, "Could not open the pid file %s for writing\n", pid_file);
return;
}
fprintf(fp,"%ld\n", (long)pid);
if (fclose(fp) == -1) {
fprintf(stderr, "Could not close the pid file %s.\n", pid_file);
return;
}
}
static void remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
fprintf(stderr, "Could not remove the pid file %s.\n", pid_file);
}
}
static void sig_handler(const int sig) {
printf("SIGINT handled.\n");
exit(EXIT_SUCCESS);
}
#ifndef HAVE_SIGIGNORE
static int sigignore(int sig) {
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 };
if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) {
return -1;
}
return 0;
}
#endif
/*
* On systems that supports multiple page sizes we may reduce the
* number of TLB-misses by using the biggest available page size
*/
static int enable_large_pages(void) {
#if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL)
int ret = -1;
size_t sizes[32];
int avail = getpagesizes(sizes, 32);
if (avail != -1) {
size_t max = sizes[0];
struct memcntl_mha arg = {0};
int ii;
for (ii = 1; ii < avail; ++ii) {
if (max < sizes[ii]) {
max = sizes[ii];
}
}
arg.mha_flags = 0;
arg.mha_pagesize = max;
arg.mha_cmd = MHA_MAPSIZE_BSSBRK;
if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) {
fprintf(stderr, "Failed to set large pages: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
} else {
ret = 0;
}
} else {
fprintf(stderr, "Failed to get supported pagesizes: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
}
return ret;
#else
return 0;
#endif
}
int main (int argc, char **argv) {
int c;
bool lock_memory = false;
bool do_daemonize = false;
bool preallocate = false;
int maxcore = 0;
char *username = NULL;
char *pid_file = NULL;
struct passwd *pw;
struct rlimit rlim;
char unit = '\0';
int size_max = 0;
/* listening sockets */
static int *l_socket = NULL;
/* udp socket */
static int *u_socket = NULL;
bool protocol_specified = false;
/* handle SIGINT */
signal(SIGINT, sig_handler);
/* init settings */
settings_init();
/* set stderr non-buffering (for running under, say, daemontools) */
setbuf(stderr, NULL);
/* process arguments */
while (-1 != (c = getopt(argc, argv,
"a:" /* access mask for unix socket */
"p:" /* TCP port number to listen on */
"s:" /* unix socket path to listen on */
"U:" /* UDP port number to listen on */
"m:" /* max memory to use for items in megabytes */
"M" /* return error on memory exhausted */
"c:" /* max simultaneous connections */
"k" /* lock down all paged memory */
"hi" /* help, licence info */
"r" /* maximize core file limit */
"v" /* verbose */
"d" /* daemon mode */
"l:" /* interface to listen on */
"u:" /* user identity to run as */
"P:" /* save PID in file */
"f:" /* factor? */
"n:" /* minimum space allocated for key+value+flags */
"t:" /* threads */
"D:" /* prefix delimiter? */
"L" /* Large memory pages */
"R:" /* max requests per event */
"C" /* Disable use of CAS */
"b:" /* backlog queue limit */
"B:" /* Binding protocol */
"I:" /* Max item size */
"S" /* Sasl ON */
))) {
switch (c) {
case 'a':
/* access for unix domain socket, as octal mask (like chmod)*/
settings.access= strtol(optarg,NULL,8);
break;
case 'U':
settings.udpport = atoi(optarg);
break;
case 'p':
settings.port = atoi(optarg);
break;
case 's':
settings.socketpath = optarg;
break;
case 'm':
settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
break;
case 'M':
settings.evict_to_free = 0;
break;
case 'c':
settings.maxconns = atoi(optarg);
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'i':
usage_license();
exit(EXIT_SUCCESS);
case 'k':
lock_memory = true;
break;
case 'v':
settings.verbose++;
break;
case 'l':
settings.inter= strdup(optarg);
break;
case 'd':
do_daemonize = true;
break;
case 'r':
maxcore = 1;
break;
case 'R':
settings.reqs_per_event = atoi(optarg);
if (settings.reqs_per_event == 0) {
fprintf(stderr, "Number of requests per event must be greater than 0\n");
return 1;
}
break;
case 'u':
username = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'f':
settings.factor = atof(optarg);
if (settings.factor <= 1.0) {
fprintf(stderr, "Factor must be greater than 1\n");
return 1;
}
break;
case 'n':
settings.chunk_size = atoi(optarg);
if (settings.chunk_size == 0) {
fprintf(stderr, "Chunk size must be greater than 0\n");
return 1;
}
break;
case 't':
settings.num_threads = atoi(optarg);
if (settings.num_threads <= 0) {
fprintf(stderr, "Number of threads must be greater than 0\n");
return 1;
}
/* There're other problems when you get above 64 threads.
* In the future we should portably detect # of cores for the
* default.
*/
if (settings.num_threads > 64) {
fprintf(stderr, "WARNING: Setting a high number of worker"
"threads is not recommended.\n"
" Set this value to the number of cores in"
" your machine or less.\n");
}
break;
case 'D':
if (! optarg || ! optarg[0]) {
fprintf(stderr, "No delimiter specified\n");
return 1;
}
settings.prefix_delimiter = optarg[0];
settings.detail_enabled = 1;
break;
case 'L' :
if (enable_large_pages() == 0) {
preallocate = true;
}
break;
case 'C' :
settings.use_cas = false;
break;
case 'b' :
settings.backlog = atoi(optarg);
break;
case 'B':
protocol_specified = true;
if (strcmp(optarg, "auto") == 0) {
settings.binding_protocol = negotiating_prot;
} else if (strcmp(optarg, "binary") == 0) {
settings.binding_protocol = binary_prot;
} else if (strcmp(optarg, "ascii") == 0) {
settings.binding_protocol = ascii_prot;
} else {
fprintf(stderr, "Invalid value for binding protocol: %s\n"
" -- should be one of auto, binary, or ascii\n", optarg);
exit(EX_USAGE);
}
break;
case 'I':
unit = optarg[strlen(optarg)-1];
if (unit == 'k' || unit == 'm' ||
unit == 'K' || unit == 'M') {
optarg[strlen(optarg)-1] = '\0';
size_max = atoi(optarg);
if (unit == 'k' || unit == 'K')
size_max *= 1024;
if (unit == 'm' || unit == 'M')
size_max *= 1024 * 1024;
settings.item_size_max = size_max;
} else {
settings.item_size_max = atoi(optarg);
}
if (settings.item_size_max < 1024) {
fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n");
return 1;
}
if (settings.item_size_max > 1024 * 1024 * 128) {
fprintf(stderr, "Cannot set item size limit higher than 128 mb.\n");
return 1;
}
if (settings.item_size_max > 1024 * 1024) {
fprintf(stderr, "WARNING: Setting item max size above 1MB is not"
" recommended!\n"
" Raising this limit increases the minimum memory requirements\n"
" and will decrease your memory efficiency.\n"
);
}
break;
case 'S': /* set Sasl authentication to true. Default is false */
#ifndef ENABLE_SASL
fprintf(stderr, "This server is not built with SASL support.\n");
exit(EX_USAGE);
#endif
settings.sasl = true;
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
return 1;
}
}
if (settings.sasl) {
if (!protocol_specified) {
settings.binding_protocol = binary_prot;
} else {
if (settings.binding_protocol != binary_prot) {
fprintf(stderr, "WARNING: You shouldn't allow the ASCII protocol while using SASL\n");
exit(EX_USAGE);
}
}
}
if (maxcore != 0) {
struct rlimit rlim_new;
/*
* First try raising to infinity; if that fails, try bringing
* the soft limit to the hard.
*/
if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) {
/* failed. try raising just to the old max */
rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
(void)setrlimit(RLIMIT_CORE, &rlim_new);
}
}
/*
* getrlimit again to see what we ended up with. Only fail if
* the soft limit ends up 0, because then no core files will be
* created at all.
*/
if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) {
fprintf(stderr, "failed to ensure corefile creation\n");
exit(EX_OSERR);
}
}
/*
* If needed, increase rlimits to allow as many connections
* as needed.
*/
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to getrlimit number of files\n");
exit(EX_OSERR);
} else {
int maxfiles = settings.maxconns;
if (rlim.rlim_cur < maxfiles)
rlim.rlim_cur = maxfiles;
if (rlim.rlim_max < rlim.rlim_cur)
rlim.rlim_max = rlim.rlim_cur;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to set rlimit for open files. Try running as root or requesting smaller maxconns value.\n");
exit(EX_OSERR);
}
}
/* lose root privileges if we have them */
if (getuid() == 0 || geteuid() == 0) {
if (username == 0 || *username == '\0') {
fprintf(stderr, "can't run as root without the -u switch\n");
exit(EX_USAGE);
}
if ((pw = getpwnam(username)) == 0) {
fprintf(stderr, "can't find the user %s to switch to\n", username);
exit(EX_NOUSER);
}
if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
fprintf(stderr, "failed to assume identity of user %s\n", username);
exit(EX_OSERR);
}
}
/* Initialize Sasl if -S was specified */
if (settings.sasl) {
init_sasl();
}
/* daemonize if requested */
/* if we want to ensure our ability to dump core, don't chdir to / */
if (do_daemonize) {
if (sigignore(SIGHUP) == -1) {
perror("Failed to ignore SIGHUP");
}
if (daemonize(maxcore, settings.verbose) == -1) {
fprintf(stderr, "failed to daemon() in order to daemonize\n");
exit(EXIT_FAILURE);
}
}
/* lock paged memory if needed */
if (lock_memory) {
#ifdef HAVE_MLOCKALL
int res = mlockall(MCL_CURRENT | MCL_FUTURE);
if (res != 0) {
fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n",
strerror(errno));
}
#else
fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n");
#endif
}
/* initialize main thread libevent instance */
main_base = event_init();
/* initialize other stuff */
stats_init();
assoc_init();
conn_init();
slabs_init(settings.maxbytes, settings.factor, preallocate);
/*
* ignore SIGPIPE signals; we can use errno == EPIPE if we
* need that information
*/
if (sigignore(SIGPIPE) == -1) {
perror("failed to ignore SIGPIPE; sigaction");
exit(EX_OSERR);
}
/* start up worker threads if MT mode */
thread_init(settings.num_threads, main_base);
/* save the PID in if we're a daemon, do this after thread_init due to
a file descriptor handling bug somewhere in libevent */
if (start_assoc_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (do_daemonize)
save_pid(getpid(), pid_file);
/* initialise clock event */
clock_handler(0, 0, 0);
/* create unix mode sockets after dropping privileges */
if (settings.socketpath != NULL) {
errno = 0;
if (server_socket_unix(settings.socketpath,settings.access)) {
vperror("failed to listen on UNIX socket: %s", settings.socketpath);
exit(EX_OSERR);
}
}
/* create the listening socket, bind it, and init */
if (settings.socketpath == NULL) {
int udp_port;
const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME");
char temp_portnumber_filename[PATH_MAX];
FILE *portnumber_file = NULL;
if (portnumber_filename != NULL) {
snprintf(temp_portnumber_filename,
sizeof(temp_portnumber_filename),
"%s.lck", portnumber_filename);
portnumber_file = fopen(temp_portnumber_filename, "a");
if (portnumber_file == NULL) {
fprintf(stderr, "Failed to open \"%s\": %s\n",
temp_portnumber_filename, strerror(errno));
}
}
errno = 0;
if (settings.port && server_socket(settings.port, tcp_transport,
portnumber_file)) {
vperror("failed to listen on TCP port %d", settings.port);
exit(EX_OSERR);
}
/*
* initialization order: first create the listening sockets
* (may need root on low ports), then drop root if needed,
* then daemonise if needed, then init libevent (in some cases
* descriptors created by libevent wouldn't survive forking).
*/
udp_port = settings.udpport ? settings.udpport : settings.port;
/* create the UDP listening socket and bind it */
errno = 0;
if (settings.udpport && server_socket(settings.udpport, udp_transport,
portnumber_file)) {
vperror("failed to listen on UDP port %d", settings.udpport);
exit(EX_OSERR);
}
if (portnumber_file) {
fclose(portnumber_file);
rename(temp_portnumber_filename, portnumber_filename);
}
}
/* Drop privileges no longer needed */
drop_privileges();
/* enter the event loop */
event_base_loop(main_base, 0);
stop_assoc_maintenance_thread();
/* remove the PID file if we're a daemon */
if (do_daemonize)
remove_pidfile(pid_file);
/* Clean up strdup() call for bind() address */
if (settings.inter)
free(settings.inter);
if (l_socket)
free(l_socket);
if (u_socket)
free(u_socket);
return EXIT_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4699_0 |
crossvul-cpp_data_bad_5844_0 | /*
* IEEE 802.15.4 dgram socket interface
*
* Copyright 2007, 2008 Siemens AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Written by:
* Sergey Lapin <slapin@ossfans.org>
* Dmitry Eremin-Solenikov <dbaryshkov@gmail.com>
*/
#include <linux/net.h>
#include <linux/module.h>
#include <linux/if_arp.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_ieee802154.h>
#include <net/ieee802154.h>
#include <net/ieee802154_netdev.h>
#include <asm/ioctls.h>
#include "af802154.h"
static HLIST_HEAD(dgram_head);
static DEFINE_RWLOCK(dgram_lock);
struct dgram_sock {
struct sock sk;
struct ieee802154_addr src_addr;
struct ieee802154_addr dst_addr;
unsigned int bound:1;
unsigned int want_ack:1;
};
static inline struct dgram_sock *dgram_sk(const struct sock *sk)
{
return container_of(sk, struct dgram_sock, sk);
}
static void dgram_hash(struct sock *sk)
{
write_lock_bh(&dgram_lock);
sk_add_node(sk, &dgram_head);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
write_unlock_bh(&dgram_lock);
}
static void dgram_unhash(struct sock *sk)
{
write_lock_bh(&dgram_lock);
if (sk_del_node_init(sk))
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&dgram_lock);
}
static int dgram_init(struct sock *sk)
{
struct dgram_sock *ro = dgram_sk(sk);
ro->dst_addr.addr_type = IEEE802154_ADDR_LONG;
ro->dst_addr.pan_id = 0xffff;
ro->want_ack = 1;
memset(&ro->dst_addr.hwaddr, 0xff, sizeof(ro->dst_addr.hwaddr));
return 0;
}
static void dgram_close(struct sock *sk, long timeout)
{
sk_common_release(sk);
}
static int dgram_bind(struct sock *sk, struct sockaddr *uaddr, int len)
{
struct sockaddr_ieee802154 *addr = (struct sockaddr_ieee802154 *)uaddr;
struct dgram_sock *ro = dgram_sk(sk);
int err = -EINVAL;
struct net_device *dev;
lock_sock(sk);
ro->bound = 0;
if (len < sizeof(*addr))
goto out;
if (addr->family != AF_IEEE802154)
goto out;
dev = ieee802154_get_dev(sock_net(sk), &addr->addr);
if (!dev) {
err = -ENODEV;
goto out;
}
if (dev->type != ARPHRD_IEEE802154) {
err = -ENODEV;
goto out_put;
}
memcpy(&ro->src_addr, &addr->addr, sizeof(struct ieee802154_addr));
ro->bound = 1;
err = 0;
out_put:
dev_put(dev);
out:
release_sock(sk);
return err;
}
static int dgram_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
unsigned long amount;
amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL) {
/*
* We will only return the amount
* of this packet since that is all
* that will be read.
*/
/* FIXME: parse the header for more correct value */
amount = skb->len - (3+8+8);
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
}
return -ENOIOCTLCMD;
}
/* FIXME: autobind */
static int dgram_connect(struct sock *sk, struct sockaddr *uaddr,
int len)
{
struct sockaddr_ieee802154 *addr = (struct sockaddr_ieee802154 *)uaddr;
struct dgram_sock *ro = dgram_sk(sk);
int err = 0;
if (len < sizeof(*addr))
return -EINVAL;
if (addr->family != AF_IEEE802154)
return -EINVAL;
lock_sock(sk);
if (!ro->bound) {
err = -ENETUNREACH;
goto out;
}
memcpy(&ro->dst_addr, &addr->addr, sizeof(struct ieee802154_addr));
out:
release_sock(sk);
return err;
}
static int dgram_disconnect(struct sock *sk, int flags)
{
struct dgram_sock *ro = dgram_sk(sk);
lock_sock(sk);
ro->dst_addr.addr_type = IEEE802154_ADDR_LONG;
memset(&ro->dst_addr.hwaddr, 0xff, sizeof(ro->dst_addr.hwaddr));
release_sock(sk);
return 0;
}
static int dgram_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t size)
{
struct net_device *dev;
unsigned int mtu;
struct sk_buff *skb;
struct dgram_sock *ro = dgram_sk(sk);
int hlen, tlen;
int err;
if (msg->msg_flags & MSG_OOB) {
pr_debug("msg->msg_flags = 0x%x\n", msg->msg_flags);
return -EOPNOTSUPP;
}
if (!ro->bound)
dev = dev_getfirstbyhwtype(sock_net(sk), ARPHRD_IEEE802154);
else
dev = ieee802154_get_dev(sock_net(sk), &ro->src_addr);
if (!dev) {
pr_debug("no dev\n");
err = -ENXIO;
goto out;
}
mtu = dev->mtu;
pr_debug("name = %s, mtu = %u\n", dev->name, mtu);
if (size > mtu) {
pr_debug("size = %Zu, mtu = %u\n", size, mtu);
err = -EINVAL;
goto out_dev;
}
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = sock_alloc_send_skb(sk, hlen + tlen + size,
msg->msg_flags & MSG_DONTWAIT,
&err);
if (!skb)
goto out_dev;
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
mac_cb(skb)->flags = IEEE802154_FC_TYPE_DATA;
if (ro->want_ack)
mac_cb(skb)->flags |= MAC_CB_FLAG_ACKREQ;
mac_cb(skb)->seq = ieee802154_mlme_ops(dev)->get_dsn(dev);
err = dev_hard_header(skb, dev, ETH_P_IEEE802154, &ro->dst_addr,
ro->bound ? &ro->src_addr : NULL, size);
if (err < 0)
goto out_skb;
skb_reset_mac_header(skb);
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err < 0)
goto out_skb;
skb->dev = dev;
skb->sk = sk;
skb->protocol = htons(ETH_P_IEEE802154);
dev_put(dev);
err = dev_queue_xmit(skb);
if (err > 0)
err = net_xmit_errno(err);
return err ?: size;
out_skb:
kfree_skb(skb);
out_dev:
dev_put(dev);
out:
return err;
}
static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock, int flags,
int *addr_len)
{
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
struct sockaddr_ieee802154 *saddr;
saddr = (struct sockaddr_ieee802154 *)msg->msg_name;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* FIXME: skip headers if necessary ?! */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
if (saddr) {
saddr->family = AF_IEEE802154;
saddr->addr = mac_cb(skb)->sa;
}
if (addr_len)
*addr_len = sizeof(*saddr);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
static int dgram_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
return NET_RX_DROP;
}
return NET_RX_SUCCESS;
}
static inline int ieee802154_match_sock(u8 *hw_addr, u16 pan_id,
u16 short_addr, struct dgram_sock *ro)
{
if (!ro->bound)
return 1;
if (ro->src_addr.addr_type == IEEE802154_ADDR_LONG &&
!memcmp(ro->src_addr.hwaddr, hw_addr, IEEE802154_ADDR_LEN))
return 1;
if (ro->src_addr.addr_type == IEEE802154_ADDR_SHORT &&
pan_id == ro->src_addr.pan_id &&
short_addr == ro->src_addr.short_addr)
return 1;
return 0;
}
int ieee802154_dgram_deliver(struct net_device *dev, struct sk_buff *skb)
{
struct sock *sk, *prev = NULL;
int ret = NET_RX_SUCCESS;
u16 pan_id, short_addr;
/* Data frame processing */
BUG_ON(dev->type != ARPHRD_IEEE802154);
pan_id = ieee802154_mlme_ops(dev)->get_pan_id(dev);
short_addr = ieee802154_mlme_ops(dev)->get_short_addr(dev);
read_lock(&dgram_lock);
sk_for_each(sk, &dgram_head) {
if (ieee802154_match_sock(dev->dev_addr, pan_id, short_addr,
dgram_sk(sk))) {
if (prev) {
struct sk_buff *clone;
clone = skb_clone(skb, GFP_ATOMIC);
if (clone)
dgram_rcv_skb(prev, clone);
}
prev = sk;
}
}
if (prev)
dgram_rcv_skb(prev, skb);
else {
kfree_skb(skb);
ret = NET_RX_DROP;
}
read_unlock(&dgram_lock);
return ret;
}
static int dgram_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct dgram_sock *ro = dgram_sk(sk);
int val, len;
if (level != SOL_IEEE802154)
return -EOPNOTSUPP;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
switch (optname) {
case WPAN_WANTACK:
val = ro->want_ack;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int dgram_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct dgram_sock *ro = dgram_sk(sk);
int val;
int err = 0;
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case WPAN_WANTACK:
ro->want_ack = !!val;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
struct proto ieee802154_dgram_prot = {
.name = "IEEE-802.15.4-MAC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct dgram_sock),
.init = dgram_init,
.close = dgram_close,
.bind = dgram_bind,
.sendmsg = dgram_sendmsg,
.recvmsg = dgram_recvmsg,
.hash = dgram_hash,
.unhash = dgram_unhash,
.connect = dgram_connect,
.disconnect = dgram_disconnect,
.ioctl = dgram_ioctl,
.getsockopt = dgram_getsockopt,
.setsockopt = dgram_setsockopt,
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_0 |
crossvul-cpp_data_good_5765_0 | /*
* Kernel-based Virtual Machine driver for Linux
*
* This module enables machines with Intel VT-x extensions to run virtual
* machines without emulation or binary translation.
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include "iodev.h"
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/percpu.h>
#include <linux/mm.h>
#include <linux/miscdevice.h>
#include <linux/vmalloc.h>
#include <linux/reboot.h>
#include <linux/debugfs.h>
#include <linux/highmem.h>
#include <linux/file.h>
#include <linux/syscore_ops.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
#include <linux/smp.h>
#include <linux/anon_inodes.h>
#include <linux/profile.h>
#include <linux/kvm_para.h>
#include <linux/pagemap.h>
#include <linux/mman.h>
#include <linux/swap.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/srcu.h>
#include <linux/hugetlb.h>
#include <linux/slab.h>
#include <linux/sort.h>
#include <linux/bsearch.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include "coalesced_mmio.h"
#include "async_pf.h"
#define CREATE_TRACE_POINTS
#include <trace/events/kvm.h>
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
/*
* Ordering of locks:
*
* kvm->lock --> kvm->slots_lock --> kvm->irq_lock
*/
DEFINE_SPINLOCK(kvm_lock);
static DEFINE_RAW_SPINLOCK(kvm_count_lock);
LIST_HEAD(vm_list);
static cpumask_var_t cpus_hardware_enabled;
static int kvm_usage_count = 0;
static atomic_t hardware_enable_failed;
struct kmem_cache *kvm_vcpu_cache;
EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
static __read_mostly struct preempt_ops kvm_preempt_ops;
struct dentry *kvm_debugfs_dir;
static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
#ifdef CONFIG_COMPAT
static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
#endif
static int hardware_enable_all(void);
static void hardware_disable_all(void);
static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
bool kvm_rebooting;
EXPORT_SYMBOL_GPL(kvm_rebooting);
static bool largepages_enabled = true;
bool kvm_is_mmio_pfn(pfn_t pfn)
{
if (pfn_valid(pfn))
return PageReserved(pfn_to_page(pfn));
return true;
}
/*
* Switches to specified vcpu, until a matching vcpu_put()
*/
int vcpu_load(struct kvm_vcpu *vcpu)
{
int cpu;
if (mutex_lock_killable(&vcpu->mutex))
return -EINTR;
if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
/* The thread running this VCPU changed. */
struct pid *oldpid = vcpu->pid;
struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
rcu_assign_pointer(vcpu->pid, newpid);
synchronize_rcu();
put_pid(oldpid);
}
cpu = get_cpu();
preempt_notifier_register(&vcpu->preempt_notifier);
kvm_arch_vcpu_load(vcpu, cpu);
put_cpu();
return 0;
}
void vcpu_put(struct kvm_vcpu *vcpu)
{
preempt_disable();
kvm_arch_vcpu_put(vcpu);
preempt_notifier_unregister(&vcpu->preempt_notifier);
preempt_enable();
mutex_unlock(&vcpu->mutex);
}
static void ack_flush(void *_completed)
{
}
static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
{
int i, cpu, me;
cpumask_var_t cpus;
bool called = true;
struct kvm_vcpu *vcpu;
zalloc_cpumask_var(&cpus, GFP_ATOMIC);
me = get_cpu();
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_make_request(req, vcpu);
cpu = vcpu->cpu;
/* Set ->requests bit before we read ->mode */
smp_mb();
if (cpus != NULL && cpu != -1 && cpu != me &&
kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
cpumask_set_cpu(cpu, cpus);
}
if (unlikely(cpus == NULL))
smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
else if (!cpumask_empty(cpus))
smp_call_function_many(cpus, ack_flush, NULL, 1);
else
called = false;
put_cpu();
free_cpumask_var(cpus);
return called;
}
void kvm_flush_remote_tlbs(struct kvm *kvm)
{
long dirty_count = kvm->tlbs_dirty;
smp_mb();
if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
++kvm->stat.remote_tlb_flush;
cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
}
EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
void kvm_reload_remote_mmus(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
}
void kvm_make_mclock_inprogress_request(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
}
void kvm_make_scan_ioapic_request(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
}
int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
{
struct page *page;
int r;
mutex_init(&vcpu->mutex);
vcpu->cpu = -1;
vcpu->kvm = kvm;
vcpu->vcpu_id = id;
vcpu->pid = NULL;
init_waitqueue_head(&vcpu->wq);
kvm_async_pf_vcpu_init(vcpu);
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->run = page_address(page);
kvm_vcpu_set_in_spin_loop(vcpu, false);
kvm_vcpu_set_dy_eligible(vcpu, false);
vcpu->preempted = false;
r = kvm_arch_vcpu_init(vcpu);
if (r < 0)
goto fail_free_run;
return 0;
fail_free_run:
free_page((unsigned long)vcpu->run);
fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_vcpu_init);
void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
{
put_pid(vcpu->pid);
kvm_arch_vcpu_uninit(vcpu);
free_page((unsigned long)vcpu->run);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
{
return container_of(mn, struct kvm, mmu_notifier);
}
static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush, idx;
/*
* When ->invalidate_page runs, the linux pte has been zapped
* already but the page is still allocated until
* ->invalidate_page returns. So if we increase the sequence
* here the kvm page fault will notice if the spte can't be
* established because the page is going to be freed. If
* instead the kvm page fault establishes the spte before
* ->invalidate_page runs, kvm_unmap_hva will release it
* before returning.
*
* The sequence increase only need to be seen at spin_unlock
* time, and not at spin_lock time.
*
* Increasing the sequence after the spin_unlock would be
* unsafe because the kvm page fault could then establish the
* pte after kvm_unmap_hva returned, without noticing the page
* is going to be freed.
*/
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address,
pte_t pte)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
kvm_set_spte_hva(kvm, address, pte);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush = 0, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
/*
* The count increase must become visible at unlock time as no
* spte can be established without taking the mmu_lock and
* count is also read inside the mmu_lock critical section.
*/
kvm->mmu_notifier_count++;
need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
need_tlb_flush |= kvm->tlbs_dirty;
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
spin_lock(&kvm->mmu_lock);
/*
* This sequence increase will notify the kvm page fault that
* the page that is going to be mapped in the spte could have
* been freed.
*/
kvm->mmu_notifier_seq++;
smp_wmb();
/*
* The above sequence increase must be visible before the
* below count decrease, which is ensured by the smp_wmb above
* in conjunction with the smp_rmb in mmu_notifier_retry().
*/
kvm->mmu_notifier_count--;
spin_unlock(&kvm->mmu_lock);
BUG_ON(kvm->mmu_notifier_count < 0);
}
static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_age_hva(kvm, address);
if (young)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
return young;
}
static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_test_age_hva(kvm, address);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
return young;
}
static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
struct mm_struct *mm)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
kvm_arch_flush_shadow_all(kvm);
srcu_read_unlock(&kvm->srcu, idx);
}
static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
.invalidate_page = kvm_mmu_notifier_invalidate_page,
.invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
.invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
.clear_flush_young = kvm_mmu_notifier_clear_flush_young,
.test_young = kvm_mmu_notifier_test_young,
.change_pte = kvm_mmu_notifier_change_pte,
.release = kvm_mmu_notifier_release,
};
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
}
#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
return 0;
}
#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
static void kvm_init_memslots_id(struct kvm *kvm)
{
int i;
struct kvm_memslots *slots = kvm->memslots;
for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
slots->id_to_index[i] = slots->memslots[i].id = i;
}
static struct kvm *kvm_create_vm(unsigned long type)
{
int r, i;
struct kvm *kvm = kvm_arch_alloc_vm();
if (!kvm)
return ERR_PTR(-ENOMEM);
r = kvm_arch_init_vm(kvm, type);
if (r)
goto out_err_nodisable;
r = hardware_enable_all();
if (r)
goto out_err_nodisable;
#ifdef CONFIG_HAVE_KVM_IRQCHIP
INIT_HLIST_HEAD(&kvm->mask_notifier_list);
INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
#endif
BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
r = -ENOMEM;
kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!kvm->memslots)
goto out_err_nosrcu;
kvm_init_memslots_id(kvm);
if (init_srcu_struct(&kvm->srcu))
goto out_err_nosrcu;
for (i = 0; i < KVM_NR_BUSES; i++) {
kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
GFP_KERNEL);
if (!kvm->buses[i])
goto out_err;
}
spin_lock_init(&kvm->mmu_lock);
kvm->mm = current->mm;
atomic_inc(&kvm->mm->mm_count);
kvm_eventfd_init(kvm);
mutex_init(&kvm->lock);
mutex_init(&kvm->irq_lock);
mutex_init(&kvm->slots_lock);
atomic_set(&kvm->users_count, 1);
INIT_LIST_HEAD(&kvm->devices);
r = kvm_init_mmu_notifier(kvm);
if (r)
goto out_err;
spin_lock(&kvm_lock);
list_add(&kvm->vm_list, &vm_list);
spin_unlock(&kvm_lock);
return kvm;
out_err:
cleanup_srcu_struct(&kvm->srcu);
out_err_nosrcu:
hardware_disable_all();
out_err_nodisable:
for (i = 0; i < KVM_NR_BUSES; i++)
kfree(kvm->buses[i]);
kfree(kvm->memslots);
kvm_arch_free_vm(kvm);
return ERR_PTR(r);
}
/*
* Avoid using vmalloc for a small buffer.
* Should not be used when the size is statically known.
*/
void *kvm_kvzalloc(unsigned long size)
{
if (size > PAGE_SIZE)
return vzalloc(size);
else
return kzalloc(size, GFP_KERNEL);
}
void kvm_kvfree(const void *addr)
{
if (is_vmalloc_addr(addr))
vfree(addr);
else
kfree(addr);
}
static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
{
if (!memslot->dirty_bitmap)
return;
kvm_kvfree(memslot->dirty_bitmap);
memslot->dirty_bitmap = NULL;
}
/*
* Free any memory in @free but not in @dont.
*/
static void kvm_free_physmem_slot(struct kvm *kvm, struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
kvm_destroy_dirty_bitmap(free);
kvm_arch_free_memslot(kvm, free, dont);
free->npages = 0;
}
void kvm_free_physmem(struct kvm *kvm)
{
struct kvm_memslots *slots = kvm->memslots;
struct kvm_memory_slot *memslot;
kvm_for_each_memslot(memslot, slots)
kvm_free_physmem_slot(kvm, memslot, NULL);
kfree(kvm->memslots);
}
static void kvm_destroy_devices(struct kvm *kvm)
{
struct list_head *node, *tmp;
list_for_each_safe(node, tmp, &kvm->devices) {
struct kvm_device *dev =
list_entry(node, struct kvm_device, vm_node);
list_del(node);
dev->ops->destroy(dev);
}
}
static void kvm_destroy_vm(struct kvm *kvm)
{
int i;
struct mm_struct *mm = kvm->mm;
kvm_arch_sync_events(kvm);
spin_lock(&kvm_lock);
list_del(&kvm->vm_list);
spin_unlock(&kvm_lock);
kvm_free_irq_routing(kvm);
for (i = 0; i < KVM_NR_BUSES; i++)
kvm_io_bus_destroy(kvm->buses[i]);
kvm_coalesced_mmio_free(kvm);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
#else
kvm_arch_flush_shadow_all(kvm);
#endif
kvm_arch_destroy_vm(kvm);
kvm_destroy_devices(kvm);
kvm_free_physmem(kvm);
cleanup_srcu_struct(&kvm->srcu);
kvm_arch_free_vm(kvm);
hardware_disable_all();
mmdrop(mm);
}
void kvm_get_kvm(struct kvm *kvm)
{
atomic_inc(&kvm->users_count);
}
EXPORT_SYMBOL_GPL(kvm_get_kvm);
void kvm_put_kvm(struct kvm *kvm)
{
if (atomic_dec_and_test(&kvm->users_count))
kvm_destroy_vm(kvm);
}
EXPORT_SYMBOL_GPL(kvm_put_kvm);
static int kvm_vm_release(struct inode *inode, struct file *filp)
{
struct kvm *kvm = filp->private_data;
kvm_irqfd_release(kvm);
kvm_put_kvm(kvm);
return 0;
}
/*
* Allocation size is twice as large as the actual dirty bitmap size.
* See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
*/
static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
{
#ifndef CONFIG_S390
unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
if (!memslot->dirty_bitmap)
return -ENOMEM;
#endif /* !CONFIG_S390 */
return 0;
}
static int cmp_memslot(const void *slot1, const void *slot2)
{
struct kvm_memory_slot *s1, *s2;
s1 = (struct kvm_memory_slot *)slot1;
s2 = (struct kvm_memory_slot *)slot2;
if (s1->npages < s2->npages)
return 1;
if (s1->npages > s2->npages)
return -1;
return 0;
}
/*
* Sort the memslots base on its size, so the larger slots
* will get better fit.
*/
static void sort_memslots(struct kvm_memslots *slots)
{
int i;
sort(slots->memslots, KVM_MEM_SLOTS_NUM,
sizeof(struct kvm_memory_slot), cmp_memslot, NULL);
for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
slots->id_to_index[slots->memslots[i].id] = i;
}
void update_memslots(struct kvm_memslots *slots, struct kvm_memory_slot *new,
u64 last_generation)
{
if (new) {
int id = new->id;
struct kvm_memory_slot *old = id_to_memslot(slots, id);
unsigned long npages = old->npages;
*old = *new;
if (new->npages != npages)
sort_memslots(slots);
}
slots->generation = last_generation + 1;
}
static int check_memory_region_flags(struct kvm_userspace_memory_region *mem)
{
u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
#ifdef KVM_CAP_READONLY_MEM
valid_flags |= KVM_MEM_READONLY;
#endif
if (mem->flags & ~valid_flags)
return -EINVAL;
return 0;
}
static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
struct kvm_memslots *slots, struct kvm_memory_slot *new)
{
struct kvm_memslots *old_memslots = kvm->memslots;
update_memslots(slots, new, kvm->memslots->generation);
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_memslots_updated(kvm);
return old_memslots;
}
/*
* Allocate some memory and give it an address in the guest physical address
* space.
*
* Discontiguous memory is allowed, mostly for framebuffers.
*
* Must be called holding mmap_sem for write.
*/
int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem)
{
int r;
gfn_t base_gfn;
unsigned long npages;
struct kvm_memory_slot *slot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots = NULL, *old_memslots;
enum kvm_mr_change change;
r = check_memory_region_flags(mem);
if (r)
goto out;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if ((mem->slot < KVM_USER_MEM_SLOTS) &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
slot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *slot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
r = -EINVAL;
if (npages) {
if (!old.npages)
change = KVM_MR_CREATE;
else { /* Modify an existing slot. */
if ((mem->userspace_addr != old.userspace_addr) ||
(npages != old.npages) ||
((new.flags ^ old.flags) & KVM_MEM_READONLY))
goto out;
if (base_gfn != old.base_gfn)
change = KVM_MR_MOVE;
else if (new.flags != old.flags)
change = KVM_MR_FLAGS_ONLY;
else { /* Nothing to change. */
r = 0;
goto out;
}
}
} else if (old.npages) {
change = KVM_MR_DELETE;
} else /* Modify a non-existent slot: disallowed. */
goto out;
if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
/* Check for overlaps */
r = -EEXIST;
kvm_for_each_memslot(slot, kvm->memslots) {
if ((slot->id >= KVM_USER_MEM_SLOTS) ||
(slot->id == mem->slot))
continue;
if (!((base_gfn + npages <= slot->base_gfn) ||
(base_gfn >= slot->base_gfn + slot->npages)))
goto out;
}
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
if (change == KVM_MR_CREATE) {
new.userspace_addr = mem->userspace_addr;
if (kvm_arch_create_memslot(kvm, &new, npages))
goto out_free;
}
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
}
if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
old_memslots = install_new_memslots(kvm, slots, NULL);
/* slot was deleted or moved, clear iommu mapping */
kvm_iommu_unmap_pages(kvm, &old);
/* From this point no new shadow pages pointing to a deleted,
* or moved, memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow_memslot(kvm, slot);
slots = old_memslots;
}
r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
if (r)
goto out_slots;
r = -ENOMEM;
/*
* We can re-use the old_memslots from above, the only difference
* from the currently installed memslots is the invalid flag. This
* will get overwritten by update_memslots anyway.
*/
if (!slots) {
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
}
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (change == KVM_MR_DELETE) {
new.dirty_bitmap = NULL;
memset(&new.arch, 0, sizeof(new.arch));
}
old_memslots = install_new_memslots(kvm, slots, &new);
kvm_arch_commit_memory_region(kvm, mem, &old, change);
kvm_free_physmem_slot(kvm, &old, &new);
kfree(old_memslots);
/*
* IOMMU mapping: New slots need to be mapped. Old slots need to be
* un-mapped and re-mapped if their base changes. Since base change
* unmapping is handled above with slot deletion, mapping alone is
* needed here. Anything else the iommu might care about for existing
* slots (size changes, userspace addr changes and read-only flag
* changes) is disallowed above, so any other attribute changes getting
* here can be skipped.
*/
if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
r = kvm_iommu_map_pages(kvm, &new);
return r;
}
return 0;
out_slots:
kfree(slots);
out_free:
kvm_free_physmem_slot(kvm, &new, &old);
out:
return r;
}
EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
int kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem)
{
int r;
mutex_lock(&kvm->slots_lock);
r = __kvm_set_memory_region(kvm, mem);
mutex_unlock(&kvm->slots_lock);
return r;
}
EXPORT_SYMBOL_GPL(kvm_set_memory_region);
int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem)
{
if (mem->slot >= KVM_USER_MEM_SLOTS)
return -EINVAL;
return kvm_set_memory_region(kvm, mem);
}
int kvm_get_dirty_log(struct kvm *kvm,
struct kvm_dirty_log *log, int *is_dirty)
{
struct kvm_memory_slot *memslot;
int r, i;
unsigned long n;
unsigned long any = 0;
r = -EINVAL;
if (log->slot >= KVM_USER_MEM_SLOTS)
goto out;
memslot = id_to_memslot(kvm->memslots, log->slot);
r = -ENOENT;
if (!memslot->dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
for (i = 0; !any && i < n/sizeof(long); ++i)
any = memslot->dirty_bitmap[i];
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
goto out;
if (any)
*is_dirty = 1;
r = 0;
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
bool kvm_largepages_enabled(void)
{
return largepages_enabled;
}
void kvm_disable_largepages(void)
{
largepages_enabled = false;
}
EXPORT_SYMBOL_GPL(kvm_disable_largepages);
struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_memslot(kvm_memslots(kvm), gfn);
}
EXPORT_SYMBOL_GPL(gfn_to_memslot);
int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
memslot->flags & KVM_MEMSLOT_INVALID)
return 0;
return 1;
}
EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
{
struct vm_area_struct *vma;
unsigned long addr, size;
size = PAGE_SIZE;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return PAGE_SIZE;
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, addr);
if (!vma)
goto out;
size = vma_kernel_pagesize(vma);
out:
up_read(¤t->mm->mmap_sem);
return size;
}
static bool memslot_is_readonly(struct kvm_memory_slot *slot)
{
return slot->flags & KVM_MEM_READONLY;
}
static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
gfn_t *nr_pages, bool write)
{
if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
return KVM_HVA_ERR_BAD;
if (memslot_is_readonly(slot) && write)
return KVM_HVA_ERR_RO_BAD;
if (nr_pages)
*nr_pages = slot->npages - (gfn - slot->base_gfn);
return __gfn_to_hva_memslot(slot, gfn);
}
static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
gfn_t *nr_pages)
{
return __gfn_to_hva_many(slot, gfn, nr_pages, true);
}
unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
gfn_t gfn)
{
return gfn_to_hva_many(slot, gfn, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
{
return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_hva);
/*
* If writable is set to false, the hva returned by this function is only
* allowed to be read.
*/
unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
{
struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
if (!kvm_is_error_hva(hva) && writable)
*writable = !memslot_is_readonly(slot);
return hva;
}
static int kvm_read_hva(void *data, void __user *hva, int len)
{
return __copy_from_user(data, hva, len);
}
static int kvm_read_hva_atomic(void *data, void __user *hva, int len)
{
return __copy_from_user_inatomic(data, hva, len);
}
static int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int write, struct page **page)
{
int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
if (write)
flags |= FOLL_WRITE;
return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
}
static inline int check_user_page_hwpoison(unsigned long addr)
{
int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
rc = __get_user_pages(current, current->mm, addr, 1,
flags, NULL, NULL, NULL);
return rc == -EHWPOISON;
}
/*
* The atomic path to get the writable pfn which will be stored in @pfn,
* true indicates success, otherwise false is returned.
*/
static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
bool write_fault, bool *writable, pfn_t *pfn)
{
struct page *page[1];
int npages;
if (!(async || atomic))
return false;
/*
* Fast pin a writable pfn only if it is a write fault request
* or the caller allows to map a writable pfn for a read fault
* request.
*/
if (!(write_fault || writable))
return false;
npages = __get_user_pages_fast(addr, 1, 1, page);
if (npages == 1) {
*pfn = page_to_pfn(page[0]);
if (writable)
*writable = true;
return true;
}
return false;
}
/*
* The slow path to get the pfn of the specified host virtual address,
* 1 indicates success, -errno is returned if error is detected.
*/
static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
bool *writable, pfn_t *pfn)
{
struct page *page[1];
int npages = 0;
might_sleep();
if (writable)
*writable = write_fault;
if (async) {
down_read(¤t->mm->mmap_sem);
npages = get_user_page_nowait(current, current->mm,
addr, write_fault, page);
up_read(¤t->mm->mmap_sem);
} else
npages = get_user_pages_fast(addr, 1, write_fault,
page);
if (npages != 1)
return npages;
/* map read fault as writable if possible */
if (unlikely(!write_fault) && writable) {
struct page *wpage[1];
npages = __get_user_pages_fast(addr, 1, 1, wpage);
if (npages == 1) {
*writable = true;
put_page(page[0]);
page[0] = wpage[0];
}
npages = 1;
}
*pfn = page_to_pfn(page[0]);
return npages;
}
static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
{
if (unlikely(!(vma->vm_flags & VM_READ)))
return false;
if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
return false;
return true;
}
/*
* Pin guest page in memory and return its pfn.
* @addr: host virtual address which maps memory to the guest
* @atomic: whether this function can sleep
* @async: whether this function need to wait IO complete if the
* host page is not in the memory
* @write_fault: whether we should get a writable host page
* @writable: whether it allows to map a writable host page for !@write_fault
*
* The function will map a writable host page for these two cases:
* 1): @write_fault = true
* 2): @write_fault = false && @writable, @writable will tell the caller
* whether the mapping is writable.
*/
static pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
bool write_fault, bool *writable)
{
struct vm_area_struct *vma;
pfn_t pfn = 0;
int npages;
/* we can do it either atomically or asynchronously, not both */
BUG_ON(atomic && async);
if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
return pfn;
if (atomic)
return KVM_PFN_ERR_FAULT;
npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
if (npages == 1)
return pfn;
down_read(¤t->mm->mmap_sem);
if (npages == -EHWPOISON ||
(!async && check_user_page_hwpoison(addr))) {
pfn = KVM_PFN_ERR_HWPOISON;
goto exit;
}
vma = find_vma_intersection(current->mm, addr, addr + 1);
if (vma == NULL)
pfn = KVM_PFN_ERR_FAULT;
else if ((vma->vm_flags & VM_PFNMAP)) {
pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
vma->vm_pgoff;
BUG_ON(!kvm_is_mmio_pfn(pfn));
} else {
if (async && vma_is_valid(vma, write_fault))
*async = true;
pfn = KVM_PFN_ERR_FAULT;
}
exit:
up_read(¤t->mm->mmap_sem);
return pfn;
}
static pfn_t
__gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn, bool atomic,
bool *async, bool write_fault, bool *writable)
{
unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
if (addr == KVM_HVA_ERR_RO_BAD)
return KVM_PFN_ERR_RO_FAULT;
if (kvm_is_error_hva(addr))
return KVM_PFN_NOSLOT;
/* Do not map writable pfn in the readonly memslot. */
if (writable && memslot_is_readonly(slot)) {
*writable = false;
writable = NULL;
}
return hva_to_pfn(addr, atomic, async, write_fault,
writable);
}
static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
bool write_fault, bool *writable)
{
struct kvm_memory_slot *slot;
if (async)
*async = false;
slot = gfn_to_memslot(kvm, gfn);
return __gfn_to_pfn_memslot(slot, gfn, atomic, async, write_fault,
writable);
}
pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
bool write_fault, bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn);
pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
{
return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
}
pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
{
return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
int nr_pages)
{
unsigned long addr;
gfn_t entry;
addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
if (kvm_is_error_hva(addr))
return -1;
if (entry < nr_pages)
return 0;
return __get_user_pages_fast(addr, nr_pages, 1, pages);
}
EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
static struct page *kvm_pfn_to_page(pfn_t pfn)
{
if (is_error_noslot_pfn(pfn))
return KVM_ERR_PTR_BAD_PAGE;
if (kvm_is_mmio_pfn(pfn)) {
WARN_ON(1);
return KVM_ERR_PTR_BAD_PAGE;
}
return pfn_to_page(pfn);
}
struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
{
pfn_t pfn;
pfn = gfn_to_pfn(kvm, gfn);
return kvm_pfn_to_page(pfn);
}
EXPORT_SYMBOL_GPL(gfn_to_page);
void kvm_release_page_clean(struct page *page)
{
WARN_ON(is_error_page(page));
kvm_release_pfn_clean(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_clean);
void kvm_release_pfn_clean(pfn_t pfn)
{
if (!is_error_noslot_pfn(pfn) && !kvm_is_mmio_pfn(pfn))
put_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
void kvm_release_page_dirty(struct page *page)
{
WARN_ON(is_error_page(page));
kvm_release_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
void kvm_release_pfn_dirty(pfn_t pfn)
{
kvm_set_pfn_dirty(pfn);
kvm_release_pfn_clean(pfn);
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
void kvm_set_page_dirty(struct page *page)
{
kvm_set_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
void kvm_set_pfn_dirty(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn)) {
struct page *page = pfn_to_page(pfn);
if (!PageReserved(page))
SetPageDirty(page);
}
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
void kvm_set_pfn_accessed(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
mark_page_accessed(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
void kvm_get_pfn(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
get_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_get_pfn);
static int next_segment(unsigned long len, int offset)
{
if (len > PAGE_SIZE - offset)
return PAGE_SIZE - offset;
else
return len;
}
int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva_prot(kvm, gfn, NULL);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = kvm_read_hva(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page);
int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest);
int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
unsigned long len)
{
int r;
unsigned long addr;
gfn_t gfn = gpa >> PAGE_SHIFT;
int offset = offset_in_page(gpa);
addr = gfn_to_hva_prot(kvm, gfn, NULL);
if (kvm_is_error_hva(addr))
return -EFAULT;
pagefault_disable();
r = kvm_read_hva_atomic(data, (void __user *)addr + offset, len);
pagefault_enable();
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL(kvm_read_guest_atomic);
int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
int offset, int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = __copy_to_user((void __user *)addr + offset, data, len);
if (r)
return -EFAULT;
mark_page_dirty(kvm, gfn);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_page);
int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
gpa_t gpa, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int offset = offset_in_page(gpa);
gfn_t start_gfn = gpa >> PAGE_SHIFT;
gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
gfn_t nr_pages_avail;
ghc->gpa = gpa;
ghc->generation = slots->generation;
ghc->len = len;
ghc->memslot = gfn_to_memslot(kvm, start_gfn);
ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, &nr_pages_avail);
if (!kvm_is_error_hva(ghc->hva) && nr_pages_avail >= nr_pages_needed) {
ghc->hva += offset;
} else {
/*
* If the requested region crosses two memslots, we still
* verify that the entire region is valid here.
*/
while (start_gfn <= end_gfn) {
ghc->memslot = gfn_to_memslot(kvm, start_gfn);
ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
&nr_pages_avail);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
start_gfn += nr_pages_avail;
}
/* Use the slow path for cross page reads and writes. */
ghc->memslot = NULL;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
void *data, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int r;
BUG_ON(len > ghc->len);
if (slots->generation != ghc->generation)
kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
if (unlikely(!ghc->memslot))
return kvm_write_guest(kvm, ghc->gpa, data, len);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
r = __copy_to_user((void __user *)ghc->hva, data, len);
if (r)
return -EFAULT;
mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
void *data, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int r;
BUG_ON(len > ghc->len);
if (slots->generation != ghc->generation)
kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
if (unlikely(!ghc->memslot))
return kvm_read_guest(kvm, ghc->gpa, data, len);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
r = __copy_from_user(data, (void __user *)ghc->hva, len);
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
{
const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
}
EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_clear_guest);
void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
gfn_t gfn)
{
if (memslot && memslot->dirty_bitmap) {
unsigned long rel_gfn = gfn - memslot->base_gfn;
set_bit_le(rel_gfn, memslot->dirty_bitmap);
}
}
void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *memslot;
memslot = gfn_to_memslot(kvm, gfn);
mark_page_dirty_in_slot(kvm, memslot, gfn);
}
EXPORT_SYMBOL_GPL(mark_page_dirty);
/*
* The vCPU has executed a HLT instruction with in-kernel mode enabled.
*/
void kvm_vcpu_block(struct kvm_vcpu *vcpu)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
if (kvm_arch_vcpu_runnable(vcpu)) {
kvm_make_request(KVM_REQ_UNHALT, vcpu);
break;
}
if (kvm_cpu_has_pending_timer(vcpu))
break;
if (signal_pending(current))
break;
schedule();
}
finish_wait(&vcpu->wq, &wait);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_block);
#ifndef CONFIG_S390
/*
* Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
*/
void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
{
int me;
int cpu = vcpu->cpu;
wait_queue_head_t *wqp;
wqp = kvm_arch_vcpu_wq(vcpu);
if (waitqueue_active(wqp)) {
wake_up_interruptible(wqp);
++vcpu->stat.halt_wakeup;
}
me = get_cpu();
if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
if (kvm_arch_vcpu_should_kick(vcpu))
smp_send_reschedule(cpu);
put_cpu();
}
EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
#endif /* !CONFIG_S390 */
void kvm_resched(struct kvm_vcpu *vcpu)
{
if (!need_resched())
return;
cond_resched();
}
EXPORT_SYMBOL_GPL(kvm_resched);
bool kvm_vcpu_yield_to(struct kvm_vcpu *target)
{
struct pid *pid;
struct task_struct *task = NULL;
bool ret = false;
rcu_read_lock();
pid = rcu_dereference(target->pid);
if (pid)
task = get_pid_task(target->pid, PIDTYPE_PID);
rcu_read_unlock();
if (!task)
return ret;
if (task->flags & PF_VCPU) {
put_task_struct(task);
return ret;
}
ret = yield_to(task, 1);
put_task_struct(task);
return ret;
}
EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
/*
* Helper that checks whether a VCPU is eligible for directed yield.
* Most eligible candidate to yield is decided by following heuristics:
*
* (a) VCPU which has not done pl-exit or cpu relax intercepted recently
* (preempted lock holder), indicated by @in_spin_loop.
* Set at the beiginning and cleared at the end of interception/PLE handler.
*
* (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
* chance last time (mostly it has become eligible now since we have probably
* yielded to lockholder in last iteration. This is done by toggling
* @dy_eligible each time a VCPU checked for eligibility.)
*
* Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
* to preempted lock-holder could result in wrong VCPU selection and CPU
* burning. Giving priority for a potential lock-holder increases lock
* progress.
*
* Since algorithm is based on heuristics, accessing another VCPU data without
* locking does not harm. It may result in trying to yield to same VCPU, fail
* and continue with next VCPU and so on.
*/
bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
{
bool eligible;
eligible = !vcpu->spin_loop.in_spin_loop ||
(vcpu->spin_loop.in_spin_loop &&
vcpu->spin_loop.dy_eligible);
if (vcpu->spin_loop.in_spin_loop)
kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
return eligible;
}
#endif
void kvm_vcpu_on_spin(struct kvm_vcpu *me)
{
struct kvm *kvm = me->kvm;
struct kvm_vcpu *vcpu;
int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
int yielded = 0;
int try = 3;
int pass;
int i;
kvm_vcpu_set_in_spin_loop(me, true);
/*
* We boost the priority of a VCPU that is runnable but not
* currently running, because it got preempted by something
* else and called schedule in __vcpu_run. Hopefully that
* VCPU is holding the lock that we need and will release it.
* We approximate round-robin by starting at the last boosted VCPU.
*/
for (pass = 0; pass < 2 && !yielded && try; pass++) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (!pass && i <= last_boosted_vcpu) {
i = last_boosted_vcpu;
continue;
} else if (pass && i > last_boosted_vcpu)
break;
if (!ACCESS_ONCE(vcpu->preempted))
continue;
if (vcpu == me)
continue;
if (waitqueue_active(&vcpu->wq))
continue;
if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
continue;
yielded = kvm_vcpu_yield_to(vcpu);
if (yielded > 0) {
kvm->last_boosted_vcpu = i;
break;
} else if (yielded < 0) {
try--;
if (!try)
break;
}
}
}
kvm_vcpu_set_in_spin_loop(me, false);
/* Ensure vcpu is not eligible during next spinloop */
kvm_vcpu_set_dy_eligible(me, false);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct kvm_vcpu *vcpu = vma->vm_file->private_data;
struct page *page;
if (vmf->pgoff == 0)
page = virt_to_page(vcpu->run);
#ifdef CONFIG_X86
else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
page = virt_to_page(vcpu->arch.pio_data);
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
#endif
else
return kvm_arch_vcpu_fault(vcpu, vmf);
get_page(page);
vmf->page = page;
return 0;
}
static const struct vm_operations_struct kvm_vcpu_vm_ops = {
.fault = kvm_vcpu_fault,
};
static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &kvm_vcpu_vm_ops;
return 0;
}
static int kvm_vcpu_release(struct inode *inode, struct file *filp)
{
struct kvm_vcpu *vcpu = filp->private_data;
kvm_put_kvm(vcpu->kvm);
return 0;
}
static struct file_operations kvm_vcpu_fops = {
.release = kvm_vcpu_release,
.unlocked_ioctl = kvm_vcpu_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_vcpu_compat_ioctl,
#endif
.mmap = kvm_vcpu_mmap,
.llseek = noop_llseek,
};
/*
* Allocates an inode for the vcpu.
*/
static int create_vcpu_fd(struct kvm_vcpu *vcpu)
{
return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
}
/*
* Creates some virtual cpus. Good luck creating more than one.
*/
static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
if (id >= KVM_MAX_VCPUS)
return -EINVAL;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
goto vcpu_destroy;
mutex_lock(&kvm->lock);
if (!kvm_vcpu_compatible(vcpu)) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto unlock_vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto unlock_vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
mutex_unlock(&kvm->lock);
kvm_arch_vcpu_postcreate(vcpu);
return r;
unlock_vcpu_destroy:
mutex_unlock(&kvm->lock);
vcpu_destroy:
kvm_arch_vcpu_destroy(vcpu);
return r;
}
static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
{
if (sigset) {
sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
vcpu->sigset_active = 1;
vcpu->sigset = *sigset;
} else
vcpu->sigset_active = 0;
return 0;
}
static long kvm_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
struct kvm_fpu *fpu = NULL;
struct kvm_sregs *kvm_sregs = NULL;
if (vcpu->kvm->mm != current->mm)
return -EIO;
#if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
/*
* Special cases: vcpu ioctls that are asynchronous to vcpu execution,
* so vcpu_load() would break it.
*/
if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
#endif
r = vcpu_load(vcpu);
if (r)
return r;
switch (ioctl) {
case KVM_RUN:
r = -EINVAL;
if (arg)
goto out;
r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
break;
case KVM_GET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
if (!kvm_regs)
goto out;
r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
if (r)
goto out_free1;
r = -EFAULT;
if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
goto out_free1;
r = 0;
out_free1:
kfree(kvm_regs);
break;
}
case KVM_SET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
if (IS_ERR(kvm_regs)) {
r = PTR_ERR(kvm_regs);
goto out;
}
r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
kfree(kvm_regs);
break;
}
case KVM_GET_SREGS: {
kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
r = -ENOMEM;
if (!kvm_sregs)
goto out;
r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
goto out;
r = 0;
break;
}
case KVM_SET_SREGS: {
kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
if (IS_ERR(kvm_sregs)) {
r = PTR_ERR(kvm_sregs);
kvm_sregs = NULL;
goto out;
}
r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
break;
}
case KVM_GET_MP_STATE: {
struct kvm_mp_state mp_state;
r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &mp_state, sizeof mp_state))
goto out;
r = 0;
break;
}
case KVM_SET_MP_STATE: {
struct kvm_mp_state mp_state;
r = -EFAULT;
if (copy_from_user(&mp_state, argp, sizeof mp_state))
goto out;
r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
break;
}
case KVM_TRANSLATE: {
struct kvm_translation tr;
r = -EFAULT;
if (copy_from_user(&tr, argp, sizeof tr))
goto out;
r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tr, sizeof tr))
goto out;
r = 0;
break;
}
case KVM_SET_GUEST_DEBUG: {
struct kvm_guest_debug dbg;
r = -EFAULT;
if (copy_from_user(&dbg, argp, sizeof dbg))
goto out;
r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
break;
}
case KVM_SET_SIGNAL_MASK: {
struct kvm_signal_mask __user *sigmask_arg = argp;
struct kvm_signal_mask kvm_sigmask;
sigset_t sigset, *p;
p = NULL;
if (argp) {
r = -EFAULT;
if (copy_from_user(&kvm_sigmask, argp,
sizeof kvm_sigmask))
goto out;
r = -EINVAL;
if (kvm_sigmask.len != sizeof sigset)
goto out;
r = -EFAULT;
if (copy_from_user(&sigset, sigmask_arg->sigset,
sizeof sigset))
goto out;
p = &sigset;
}
r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
break;
}
case KVM_GET_FPU: {
fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
r = -ENOMEM;
if (!fpu)
goto out;
r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
goto out;
r = 0;
break;
}
case KVM_SET_FPU: {
fpu = memdup_user(argp, sizeof(*fpu));
if (IS_ERR(fpu)) {
r = PTR_ERR(fpu);
fpu = NULL;
goto out;
}
r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
break;
}
default:
r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
}
out:
vcpu_put(vcpu);
kfree(fpu);
kfree(kvm_sregs);
return r;
}
#ifdef CONFIG_COMPAT
static long kvm_vcpu_compat_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = compat_ptr(arg);
int r;
if (vcpu->kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_SET_SIGNAL_MASK: {
struct kvm_signal_mask __user *sigmask_arg = argp;
struct kvm_signal_mask kvm_sigmask;
compat_sigset_t csigset;
sigset_t sigset;
if (argp) {
r = -EFAULT;
if (copy_from_user(&kvm_sigmask, argp,
sizeof kvm_sigmask))
goto out;
r = -EINVAL;
if (kvm_sigmask.len != sizeof csigset)
goto out;
r = -EFAULT;
if (copy_from_user(&csigset, sigmask_arg->sigset,
sizeof csigset))
goto out;
sigset_from_compat(&sigset, &csigset);
r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
} else
r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
break;
}
default:
r = kvm_vcpu_ioctl(filp, ioctl, arg);
}
out:
return r;
}
#endif
static int kvm_device_ioctl_attr(struct kvm_device *dev,
int (*accessor)(struct kvm_device *dev,
struct kvm_device_attr *attr),
unsigned long arg)
{
struct kvm_device_attr attr;
if (!accessor)
return -EPERM;
if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
return -EFAULT;
return accessor(dev, &attr);
}
static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
unsigned long arg)
{
struct kvm_device *dev = filp->private_data;
switch (ioctl) {
case KVM_SET_DEVICE_ATTR:
return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
case KVM_GET_DEVICE_ATTR:
return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
case KVM_HAS_DEVICE_ATTR:
return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
default:
if (dev->ops->ioctl)
return dev->ops->ioctl(dev, ioctl, arg);
return -ENOTTY;
}
}
static int kvm_device_release(struct inode *inode, struct file *filp)
{
struct kvm_device *dev = filp->private_data;
struct kvm *kvm = dev->kvm;
kvm_put_kvm(kvm);
return 0;
}
static const struct file_operations kvm_device_fops = {
.unlocked_ioctl = kvm_device_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_device_ioctl,
#endif
.release = kvm_device_release,
};
struct kvm_device *kvm_device_from_filp(struct file *filp)
{
if (filp->f_op != &kvm_device_fops)
return NULL;
return filp->private_data;
}
static int kvm_ioctl_create_device(struct kvm *kvm,
struct kvm_create_device *cd)
{
struct kvm_device_ops *ops = NULL;
struct kvm_device *dev;
bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
int ret;
switch (cd->type) {
#ifdef CONFIG_KVM_MPIC
case KVM_DEV_TYPE_FSL_MPIC_20:
case KVM_DEV_TYPE_FSL_MPIC_42:
ops = &kvm_mpic_ops;
break;
#endif
#ifdef CONFIG_KVM_XICS
case KVM_DEV_TYPE_XICS:
ops = &kvm_xics_ops;
break;
#endif
#ifdef CONFIG_KVM_VFIO
case KVM_DEV_TYPE_VFIO:
ops = &kvm_vfio_ops;
break;
#endif
default:
return -ENODEV;
}
if (test)
return 0;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->ops = ops;
dev->kvm = kvm;
ret = ops->create(dev, cd->type);
if (ret < 0) {
kfree(dev);
return ret;
}
ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
if (ret < 0) {
ops->destroy(dev);
return ret;
}
list_add(&dev->vm_node, &kvm->devices);
kvm_get_kvm(kvm);
cd->fd = ret;
return 0;
}
static long kvm_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_CREATE_VCPU:
r = kvm_vm_ioctl_create_vcpu(kvm, arg);
break;
case KVM_SET_USER_MEMORY_REGION: {
struct kvm_userspace_memory_region kvm_userspace_mem;
r = -EFAULT;
if (copy_from_user(&kvm_userspace_mem, argp,
sizeof kvm_userspace_mem))
goto out;
r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
break;
}
case KVM_GET_DIRTY_LOG: {
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&log, argp, sizeof log))
goto out;
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
break;
}
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
case KVM_REGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
break;
}
case KVM_UNREGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
break;
}
#endif
case KVM_IRQFD: {
struct kvm_irqfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_irqfd(kvm, &data);
break;
}
case KVM_IOEVENTFD: {
struct kvm_ioeventfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_ioeventfd(kvm, &data);
break;
}
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_SET_BOOT_CPU_ID:
r = 0;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) != 0)
r = -EBUSY;
else
kvm->bsp_vcpu_id = arg;
mutex_unlock(&kvm->lock);
break;
#endif
#ifdef CONFIG_HAVE_KVM_MSI
case KVM_SIGNAL_MSI: {
struct kvm_msi msi;
r = -EFAULT;
if (copy_from_user(&msi, argp, sizeof msi))
goto out;
r = kvm_send_userspace_msi(kvm, &msi);
break;
}
#endif
#ifdef __KVM_HAVE_IRQ_LINE
case KVM_IRQ_LINE_STATUS:
case KVM_IRQ_LINE: {
struct kvm_irq_level irq_event;
r = -EFAULT;
if (copy_from_user(&irq_event, argp, sizeof irq_event))
goto out;
r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
ioctl == KVM_IRQ_LINE_STATUS);
if (r)
goto out;
r = -EFAULT;
if (ioctl == KVM_IRQ_LINE_STATUS) {
if (copy_to_user(argp, &irq_event, sizeof irq_event))
goto out;
}
r = 0;
break;
}
#endif
#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
case KVM_SET_GSI_ROUTING: {
struct kvm_irq_routing routing;
struct kvm_irq_routing __user *urouting;
struct kvm_irq_routing_entry *entries;
r = -EFAULT;
if (copy_from_user(&routing, argp, sizeof(routing)))
goto out;
r = -EINVAL;
if (routing.nr >= KVM_MAX_IRQ_ROUTES)
goto out;
if (routing.flags)
goto out;
r = -ENOMEM;
entries = vmalloc(routing.nr * sizeof(*entries));
if (!entries)
goto out;
r = -EFAULT;
urouting = argp;
if (copy_from_user(entries, urouting->entries,
routing.nr * sizeof(*entries)))
goto out_free_irq_routing;
r = kvm_set_irq_routing(kvm, entries, routing.nr,
routing.flags);
out_free_irq_routing:
vfree(entries);
break;
}
#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
case KVM_CREATE_DEVICE: {
struct kvm_create_device cd;
r = -EFAULT;
if (copy_from_user(&cd, argp, sizeof(cd)))
goto out;
r = kvm_ioctl_create_device(kvm, &cd);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &cd, sizeof(cd)))
goto out;
r = 0;
break;
}
default:
r = kvm_arch_vm_ioctl(filp, ioctl, arg);
if (r == -ENOTTY)
r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
}
out:
return r;
}
#ifdef CONFIG_COMPAT
struct compat_kvm_dirty_log {
__u32 slot;
__u32 padding1;
union {
compat_uptr_t dirty_bitmap; /* one bit per page */
__u64 padding2;
};
};
static long kvm_vm_compat_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_GET_DIRTY_LOG: {
struct compat_kvm_dirty_log compat_log;
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&compat_log, (void __user *)arg,
sizeof(compat_log)))
goto out;
log.slot = compat_log.slot;
log.padding1 = compat_log.padding1;
log.padding2 = compat_log.padding2;
log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
break;
}
default:
r = kvm_vm_ioctl(filp, ioctl, arg);
}
out:
return r;
}
#endif
static struct file_operations kvm_vm_fops = {
.release = kvm_vm_release,
.unlocked_ioctl = kvm_vm_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_vm_compat_ioctl,
#endif
.llseek = noop_llseek,
};
static int kvm_dev_ioctl_create_vm(unsigned long type)
{
int r;
struct kvm *kvm;
kvm = kvm_create_vm(type);
if (IS_ERR(kvm))
return PTR_ERR(kvm);
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r = kvm_coalesced_mmio_init(kvm);
if (r < 0) {
kvm_put_kvm(kvm);
return r;
}
#endif
r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR | O_CLOEXEC);
if (r < 0)
kvm_put_kvm(kvm);
return r;
}
static long kvm_dev_ioctl_check_extension_generic(long arg)
{
switch (arg) {
case KVM_CAP_USER_MEMORY:
case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_CAP_SET_BOOT_CPU_ID:
#endif
case KVM_CAP_INTERNAL_ERROR_DATA:
#ifdef CONFIG_HAVE_KVM_MSI
case KVM_CAP_SIGNAL_MSI:
#endif
#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
case KVM_CAP_IRQFD_RESAMPLE:
#endif
return 1;
#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
case KVM_CAP_IRQ_ROUTING:
return KVM_MAX_IRQ_ROUTES;
#endif
default:
break;
}
return kvm_dev_ioctl_check_extension(arg);
}
static long kvm_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
long r = -EINVAL;
switch (ioctl) {
case KVM_GET_API_VERSION:
r = -EINVAL;
if (arg)
goto out;
r = KVM_API_VERSION;
break;
case KVM_CREATE_VM:
r = kvm_dev_ioctl_create_vm(arg);
break;
case KVM_CHECK_EXTENSION:
r = kvm_dev_ioctl_check_extension_generic(arg);
break;
case KVM_GET_VCPU_MMAP_SIZE:
r = -EINVAL;
if (arg)
goto out;
r = PAGE_SIZE; /* struct kvm_run */
#ifdef CONFIG_X86
r += PAGE_SIZE; /* pio data page */
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r += PAGE_SIZE; /* coalesced mmio ring page */
#endif
break;
case KVM_TRACE_ENABLE:
case KVM_TRACE_PAUSE:
case KVM_TRACE_DISABLE:
r = -EOPNOTSUPP;
break;
default:
return kvm_arch_dev_ioctl(filp, ioctl, arg);
}
out:
return r;
}
static struct file_operations kvm_chardev_ops = {
.unlocked_ioctl = kvm_dev_ioctl,
.compat_ioctl = kvm_dev_ioctl,
.llseek = noop_llseek,
};
static struct miscdevice kvm_dev = {
KVM_MINOR,
"kvm",
&kvm_chardev_ops,
};
static void hardware_enable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
int r;
if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_set_cpu(cpu, cpus_hardware_enabled);
r = kvm_arch_hardware_enable(NULL);
if (r) {
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
atomic_inc(&hardware_enable_failed);
printk(KERN_INFO "kvm: enabling virtualization on "
"CPU%d failed\n", cpu);
}
}
static void hardware_enable(void)
{
raw_spin_lock(&kvm_count_lock);
if (kvm_usage_count)
hardware_enable_nolock(NULL);
raw_spin_unlock(&kvm_count_lock);
}
static void hardware_disable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
kvm_arch_hardware_disable(NULL);
}
static void hardware_disable(void)
{
raw_spin_lock(&kvm_count_lock);
if (kvm_usage_count)
hardware_disable_nolock(NULL);
raw_spin_unlock(&kvm_count_lock);
}
static void hardware_disable_all_nolock(void)
{
BUG_ON(!kvm_usage_count);
kvm_usage_count--;
if (!kvm_usage_count)
on_each_cpu(hardware_disable_nolock, NULL, 1);
}
static void hardware_disable_all(void)
{
raw_spin_lock(&kvm_count_lock);
hardware_disable_all_nolock();
raw_spin_unlock(&kvm_count_lock);
}
static int hardware_enable_all(void)
{
int r = 0;
raw_spin_lock(&kvm_count_lock);
kvm_usage_count++;
if (kvm_usage_count == 1) {
atomic_set(&hardware_enable_failed, 0);
on_each_cpu(hardware_enable_nolock, NULL, 1);
if (atomic_read(&hardware_enable_failed)) {
hardware_disable_all_nolock();
r = -EBUSY;
}
}
raw_spin_unlock(&kvm_count_lock);
return r;
}
static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
void *v)
{
int cpu = (long)v;
val &= ~CPU_TASKS_FROZEN;
switch (val) {
case CPU_DYING:
printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
cpu);
hardware_disable();
break;
case CPU_STARTING:
printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
cpu);
hardware_enable();
break;
}
return NOTIFY_OK;
}
static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
void *v)
{
/*
* Some (well, at least mine) BIOSes hang on reboot if
* in vmx root mode.
*
* And Intel TXT required VMX off for all cpu when system shutdown.
*/
printk(KERN_INFO "kvm: exiting hardware virtualization\n");
kvm_rebooting = true;
on_each_cpu(hardware_disable_nolock, NULL, 1);
return NOTIFY_OK;
}
static struct notifier_block kvm_reboot_notifier = {
.notifier_call = kvm_reboot,
.priority = 0,
};
static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
{
int i;
for (i = 0; i < bus->dev_count; i++) {
struct kvm_io_device *pos = bus->range[i].dev;
kvm_iodevice_destructor(pos);
}
kfree(bus);
}
static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
const struct kvm_io_range *r2)
{
if (r1->addr < r2->addr)
return -1;
if (r1->addr + r1->len > r2->addr + r2->len)
return 1;
return 0;
}
static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
{
return kvm_io_bus_cmp(p1, p2);
}
static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
gpa_t addr, int len)
{
bus->range[bus->dev_count++] = (struct kvm_io_range) {
.addr = addr,
.len = len,
.dev = dev,
};
sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
kvm_io_bus_sort_cmp, NULL);
return 0;
}
static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
gpa_t addr, int len)
{
struct kvm_io_range *range, key;
int off;
key = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
range = bsearch(&key, bus->range, bus->dev_count,
sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
if (range == NULL)
return -ENOENT;
off = range - bus->range;
while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
off--;
return off;
}
static int __kvm_io_bus_write(struct kvm_io_bus *bus,
struct kvm_io_range *range, const void *val)
{
int idx;
idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
if (idx < 0)
return -EOPNOTSUPP;
while (idx < bus->dev_count &&
kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
if (!kvm_iodevice_write(bus->range[idx].dev, range->addr,
range->len, val))
return idx;
idx++;
}
return -EOPNOTSUPP;
}
/* kvm_io_bus_write - called under kvm->slots_lock */
int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, const void *val)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
int r;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
r = __kvm_io_bus_write(bus, &range, val);
return r < 0 ? r : 0;
}
/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
int kvm_io_bus_write_cookie(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, const void *val, long cookie)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
/* First try the device referenced by cookie. */
if ((cookie >= 0) && (cookie < bus->dev_count) &&
(kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
if (!kvm_iodevice_write(bus->range[cookie].dev, addr, len,
val))
return cookie;
/*
* cookie contained garbage; fall back to search and return the
* correct cookie value.
*/
return __kvm_io_bus_write(bus, &range, val);
}
static int __kvm_io_bus_read(struct kvm_io_bus *bus, struct kvm_io_range *range,
void *val)
{
int idx;
idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
if (idx < 0)
return -EOPNOTSUPP;
while (idx < bus->dev_count &&
kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
if (!kvm_iodevice_read(bus->range[idx].dev, range->addr,
range->len, val))
return idx;
idx++;
}
return -EOPNOTSUPP;
}
/* kvm_io_bus_read - called under kvm->slots_lock */
int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
int r;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
r = __kvm_io_bus_read(bus, &range, val);
return r < 0 ? r : 0;
}
/* kvm_io_bus_read_cookie - called under kvm->slots_lock */
int kvm_io_bus_read_cookie(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val, long cookie)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
/* First try the device referenced by cookie. */
if ((cookie >= 0) && (cookie < bus->dev_count) &&
(kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
if (!kvm_iodevice_read(bus->range[cookie].dev, addr, len,
val))
return cookie;
/*
* cookie contained garbage; fall back to search and return the
* correct cookie value.
*/
return __kvm_io_bus_read(bus, &range, val);
}
/* Caller must hold slots_lock. */
int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, struct kvm_io_device *dev)
{
struct kvm_io_bus *new_bus, *bus;
bus = kvm->buses[bus_idx];
/* exclude ioeventfd which is limited by maximum fd */
if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
return -ENOSPC;
new_bus = kzalloc(sizeof(*bus) + ((bus->dev_count + 1) *
sizeof(struct kvm_io_range)), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
sizeof(struct kvm_io_range)));
kvm_io_bus_insert_dev(new_bus, dev, addr, len);
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return 0;
}
/* Caller must hold slots_lock. */
int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
int i, r;
struct kvm_io_bus *new_bus, *bus;
bus = kvm->buses[bus_idx];
r = -ENOENT;
for (i = 0; i < bus->dev_count; i++)
if (bus->range[i].dev == dev) {
r = 0;
break;
}
if (r)
return r;
new_bus = kzalloc(sizeof(*bus) + ((bus->dev_count - 1) *
sizeof(struct kvm_io_range)), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
new_bus->dev_count--;
memcpy(new_bus->range + i, bus->range + i + 1,
(new_bus->dev_count - i) * sizeof(struct kvm_io_range));
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return r;
}
static struct notifier_block kvm_cpu_notifier = {
.notifier_call = kvm_cpu_hotplug,
};
static int vm_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
*val = 0;
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
*val += *(u32 *)((void *)kvm + offset);
spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
static int vcpu_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
*val = 0;
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
*val += *(u32 *)((void *)vcpu + offset);
spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
static const struct file_operations *stat_fops[] = {
[KVM_STAT_VCPU] = &vcpu_stat_fops,
[KVM_STAT_VM] = &vm_stat_fops,
};
static int kvm_init_debug(void)
{
int r = -EEXIST;
struct kvm_stats_debugfs_item *p;
kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
if (kvm_debugfs_dir == NULL)
goto out;
for (p = debugfs_entries; p->name; ++p) {
p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
(void *)(long)p->offset,
stat_fops[p->kind]);
if (p->dentry == NULL)
goto out_dir;
}
return 0;
out_dir:
debugfs_remove_recursive(kvm_debugfs_dir);
out:
return r;
}
static void kvm_exit_debug(void)
{
struct kvm_stats_debugfs_item *p;
for (p = debugfs_entries; p->name; ++p)
debugfs_remove(p->dentry);
debugfs_remove(kvm_debugfs_dir);
}
static int kvm_suspend(void)
{
if (kvm_usage_count)
hardware_disable_nolock(NULL);
return 0;
}
static void kvm_resume(void)
{
if (kvm_usage_count) {
WARN_ON(raw_spin_is_locked(&kvm_count_lock));
hardware_enable_nolock(NULL);
}
}
static struct syscore_ops kvm_syscore_ops = {
.suspend = kvm_suspend,
.resume = kvm_resume,
};
static inline
struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
{
return container_of(pn, struct kvm_vcpu, preempt_notifier);
}
static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
if (vcpu->preempted)
vcpu->preempted = false;
kvm_arch_vcpu_load(vcpu, cpu);
}
static void kvm_sched_out(struct preempt_notifier *pn,
struct task_struct *next)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
if (current->state == TASK_RUNNING)
vcpu->preempted = true;
kvm_arch_vcpu_put(vcpu);
}
int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
struct module *module)
{
int r;
int cpu;
r = kvm_arch_init(opaque);
if (r)
goto out_fail;
/*
* kvm_arch_init makes sure there's at most one caller
* for architectures that support multiple implementations,
* like intel and amd on x86.
* kvm_arch_init must be called before kvm_irqfd_init to avoid creating
* conflicts in case kvm is already setup for another implementation.
*/
r = kvm_irqfd_init();
if (r)
goto out_irqfd;
if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
r = -ENOMEM;
goto out_free_0;
}
r = kvm_arch_hardware_setup();
if (r < 0)
goto out_free_0a;
for_each_online_cpu(cpu) {
smp_call_function_single(cpu,
kvm_arch_check_processor_compat,
&r, 1);
if (r < 0)
goto out_free_1;
}
r = register_cpu_notifier(&kvm_cpu_notifier);
if (r)
goto out_free_2;
register_reboot_notifier(&kvm_reboot_notifier);
/* A kmem cache lets us meet the alignment requirements of fx_save. */
if (!vcpu_align)
vcpu_align = __alignof__(struct kvm_vcpu);
kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
0, NULL);
if (!kvm_vcpu_cache) {
r = -ENOMEM;
goto out_free_3;
}
r = kvm_async_pf_init();
if (r)
goto out_free;
kvm_chardev_ops.owner = module;
kvm_vm_fops.owner = module;
kvm_vcpu_fops.owner = module;
r = misc_register(&kvm_dev);
if (r) {
printk(KERN_ERR "kvm: misc device register failed\n");
goto out_unreg;
}
register_syscore_ops(&kvm_syscore_ops);
kvm_preempt_ops.sched_in = kvm_sched_in;
kvm_preempt_ops.sched_out = kvm_sched_out;
r = kvm_init_debug();
if (r) {
printk(KERN_ERR "kvm: create debugfs files failed\n");
goto out_undebugfs;
}
return 0;
out_undebugfs:
unregister_syscore_ops(&kvm_syscore_ops);
misc_deregister(&kvm_dev);
out_unreg:
kvm_async_pf_deinit();
out_free:
kmem_cache_destroy(kvm_vcpu_cache);
out_free_3:
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
out_free_2:
out_free_1:
kvm_arch_hardware_unsetup();
out_free_0a:
free_cpumask_var(cpus_hardware_enabled);
out_free_0:
kvm_irqfd_exit();
out_irqfd:
kvm_arch_exit();
out_fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_init);
void kvm_exit(void)
{
kvm_exit_debug();
misc_deregister(&kvm_dev);
kmem_cache_destroy(kvm_vcpu_cache);
kvm_async_pf_deinit();
unregister_syscore_ops(&kvm_syscore_ops);
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
on_each_cpu(hardware_disable_nolock, NULL, 1);
kvm_arch_hardware_unsetup();
kvm_arch_exit();
kvm_irqfd_exit();
free_cpumask_var(cpus_hardware_enabled);
}
EXPORT_SYMBOL_GPL(kvm_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5765_0 |
crossvul-cpp_data_good_5794_0 |
/*
* Local APIC virtualization
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright (C) 2007 Novell
* Copyright (C) 2007 Intel
* Copyright 2009 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Dor Laor <dor.laor@qumranet.com>
* Gregory Haskins <ghaskins@novell.com>
* Yaozu (Eddie) Dong <eddie.dong@intel.com>
*
* Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*/
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/hrtimer.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/math64.h>
#include <linux/slab.h>
#include <asm/processor.h>
#include <asm/msr.h>
#include <asm/page.h>
#include <asm/current.h>
#include <asm/apicdef.h>
#include <linux/atomic.h>
#include <linux/jump_label.h>
#include "kvm_cache_regs.h"
#include "irq.h"
#include "trace.h"
#include "x86.h"
#include "cpuid.h"
#ifndef CONFIG_X86_64
#define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
#else
#define mod_64(x, y) ((x) % (y))
#endif
#define PRId64 "d"
#define PRIx64 "llx"
#define PRIu64 "u"
#define PRIo64 "o"
#define APIC_BUS_CYCLE_NS 1
/* #define apic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) */
#define apic_debug(fmt, arg...)
#define APIC_LVT_NUM 6
/* 14 is the version for Xeon and Pentium 8.4.8*/
#define APIC_VERSION (0x14UL | ((APIC_LVT_NUM - 1) << 16))
#define LAPIC_MMIO_LENGTH (1 << 12)
/* followed define is not in apicdef.h */
#define APIC_SHORT_MASK 0xc0000
#define APIC_DEST_NOSHORT 0x0
#define APIC_DEST_MASK 0x800
#define MAX_APIC_VECTOR 256
#define APIC_VECTORS_PER_REG 32
#define VEC_POS(v) ((v) & (32 - 1))
#define REG_POS(v) (((v) >> 5) << 4)
static unsigned int min_timer_period_us = 500;
module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
static inline void apic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
{
*((u32 *) (apic->regs + reg_off)) = val;
}
static inline int apic_test_vector(int vec, void *bitmap)
{
return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
{
struct kvm_lapic *apic = vcpu->arch.apic;
return apic_test_vector(vector, apic->regs + APIC_ISR) ||
apic_test_vector(vector, apic->regs + APIC_IRR);
}
static inline void apic_set_vector(int vec, void *bitmap)
{
set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
static inline void apic_clear_vector(int vec, void *bitmap)
{
clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
static inline int __apic_test_and_set_vector(int vec, void *bitmap)
{
return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
{
return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
struct static_key_deferred apic_hw_disabled __read_mostly;
struct static_key_deferred apic_sw_disabled __read_mostly;
static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
{
if ((kvm_apic_get_reg(apic, APIC_SPIV) ^ val) & APIC_SPIV_APIC_ENABLED) {
if (val & APIC_SPIV_APIC_ENABLED)
static_key_slow_dec_deferred(&apic_sw_disabled);
else
static_key_slow_inc(&apic_sw_disabled.key);
}
apic_set_reg(apic, APIC_SPIV, val);
}
static inline int apic_enabled(struct kvm_lapic *apic)
{
return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
}
#define LVT_MASK \
(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
#define LINT_MASK \
(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
static inline int kvm_apic_id(struct kvm_lapic *apic)
{
return (kvm_apic_get_reg(apic, APIC_ID) >> 24) & 0xff;
}
static void recalculate_apic_map(struct kvm *kvm)
{
struct kvm_apic_map *new, *old = NULL;
struct kvm_vcpu *vcpu;
int i;
new = kzalloc(sizeof(struct kvm_apic_map), GFP_KERNEL);
mutex_lock(&kvm->arch.apic_map_lock);
if (!new)
goto out;
new->ldr_bits = 8;
/* flat mode is default */
new->cid_shift = 8;
new->cid_mask = 0;
new->lid_mask = 0xff;
kvm_for_each_vcpu(i, vcpu, kvm) {
struct kvm_lapic *apic = vcpu->arch.apic;
u16 cid, lid;
u32 ldr;
if (!kvm_apic_present(vcpu))
continue;
/*
* All APICs have to be configured in the same mode by an OS.
* We take advatage of this while building logical id loockup
* table. After reset APICs are in xapic/flat mode, so if we
* find apic with different setting we assume this is the mode
* OS wants all apics to be in; build lookup table accordingly.
*/
if (apic_x2apic_mode(apic)) {
new->ldr_bits = 32;
new->cid_shift = 16;
new->cid_mask = new->lid_mask = 0xffff;
} else if (kvm_apic_sw_enabled(apic) &&
!new->cid_mask /* flat mode */ &&
kvm_apic_get_reg(apic, APIC_DFR) == APIC_DFR_CLUSTER) {
new->cid_shift = 4;
new->cid_mask = 0xf;
new->lid_mask = 0xf;
}
new->phys_map[kvm_apic_id(apic)] = apic;
ldr = kvm_apic_get_reg(apic, APIC_LDR);
cid = apic_cluster_id(new, ldr);
lid = apic_logical_id(new, ldr);
if (lid)
new->logical_map[cid][ffs(lid) - 1] = apic;
}
out:
old = rcu_dereference_protected(kvm->arch.apic_map,
lockdep_is_held(&kvm->arch.apic_map_lock));
rcu_assign_pointer(kvm->arch.apic_map, new);
mutex_unlock(&kvm->arch.apic_map_lock);
if (old)
kfree_rcu(old, rcu);
kvm_vcpu_request_scan_ioapic(kvm);
}
static inline void kvm_apic_set_id(struct kvm_lapic *apic, u8 id)
{
apic_set_reg(apic, APIC_ID, id << 24);
recalculate_apic_map(apic->vcpu->kvm);
}
static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
{
apic_set_reg(apic, APIC_LDR, id);
recalculate_apic_map(apic->vcpu->kvm);
}
static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
{
return !(kvm_apic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
}
static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
{
return kvm_apic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
}
static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
{
return ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) == APIC_LVT_TIMER_ONESHOT);
}
static inline int apic_lvtt_period(struct kvm_lapic *apic)
{
return ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) == APIC_LVT_TIMER_PERIODIC);
}
static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
{
return ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) ==
APIC_LVT_TIMER_TSCDEADLINE);
}
static inline int apic_lvt_nmi_mode(u32 lvt_val)
{
return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
}
void kvm_apic_set_version(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
struct kvm_cpuid_entry2 *feat;
u32 v = APIC_VERSION;
if (!kvm_vcpu_has_lapic(vcpu))
return;
feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))))
v |= APIC_LVR_DIRECTED_EOI;
apic_set_reg(apic, APIC_LVR, v);
}
static const unsigned int apic_lvt_mask[APIC_LVT_NUM] = {
LVT_MASK , /* part LVTT mask, timer mode mask added at runtime */
LVT_MASK | APIC_MODE_MASK, /* LVTTHMR */
LVT_MASK | APIC_MODE_MASK, /* LVTPC */
LINT_MASK, LINT_MASK, /* LVT0-1 */
LVT_MASK /* LVTERR */
};
static int find_highest_vector(void *bitmap)
{
int vec;
u32 *reg;
for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
vec >= 0; vec -= APIC_VECTORS_PER_REG) {
reg = bitmap + REG_POS(vec);
if (*reg)
return fls(*reg) - 1 + vec;
}
return -1;
}
static u8 count_vectors(void *bitmap)
{
int vec;
u32 *reg;
u8 count = 0;
for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
reg = bitmap + REG_POS(vec);
count += hweight32(*reg);
}
return count;
}
void kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir)
{
u32 i, pir_val;
struct kvm_lapic *apic = vcpu->arch.apic;
for (i = 0; i <= 7; i++) {
pir_val = xchg(&pir[i], 0);
if (pir_val)
*((u32 *)(apic->regs + APIC_IRR + i * 0x10)) |= pir_val;
}
}
EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
static inline void apic_set_irr(int vec, struct kvm_lapic *apic)
{
apic->irr_pending = true;
apic_set_vector(vec, apic->regs + APIC_IRR);
}
static inline int apic_search_irr(struct kvm_lapic *apic)
{
return find_highest_vector(apic->regs + APIC_IRR);
}
static inline int apic_find_highest_irr(struct kvm_lapic *apic)
{
int result;
/*
* Note that irr_pending is just a hint. It will be always
* true with virtual interrupt delivery enabled.
*/
if (!apic->irr_pending)
return -1;
kvm_x86_ops->sync_pir_to_irr(apic->vcpu);
result = apic_search_irr(apic);
ASSERT(result == -1 || result >= 16);
return result;
}
static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
{
apic->irr_pending = false;
apic_clear_vector(vec, apic->regs + APIC_IRR);
if (apic_search_irr(apic) != -1)
apic->irr_pending = true;
}
static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
{
if (!__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
++apic->isr_count;
BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
/*
* ISR (in service register) bit is set when injecting an interrupt.
* The highest vector is injected. Thus the latest bit set matches
* the highest bit in ISR.
*/
apic->highest_isr_cache = vec;
}
static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
{
if (__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
--apic->isr_count;
BUG_ON(apic->isr_count < 0);
apic->highest_isr_cache = -1;
}
int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
{
int highest_irr;
/* This may race with setting of irr in __apic_accept_irq() and
* value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
* will cause vmexit immediately and the value will be recalculated
* on the next vmentry.
*/
if (!kvm_vcpu_has_lapic(vcpu))
return 0;
highest_irr = apic_find_highest_irr(vcpu->arch.apic);
return highest_irr;
}
static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
int vector, int level, int trig_mode,
unsigned long *dest_map);
int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
unsigned long *dest_map)
{
struct kvm_lapic *apic = vcpu->arch.apic;
return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
irq->level, irq->trig_mode, dest_map);
}
static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
{
return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
sizeof(val));
}
static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
{
return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
sizeof(*val));
}
static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
{
return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
}
static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
{
u8 val;
if (pv_eoi_get_user(vcpu, &val) < 0)
apic_debug("Can't read EOI MSR value: 0x%llx\n",
(unsigned long long)vcpi->arch.pv_eoi.msr_val);
return val & 0x1;
}
static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
{
if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
apic_debug("Can't set EOI MSR value: 0x%llx\n",
(unsigned long long)vcpi->arch.pv_eoi.msr_val);
return;
}
__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
}
static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
{
if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
apic_debug("Can't clear EOI MSR value: 0x%llx\n",
(unsigned long long)vcpi->arch.pv_eoi.msr_val);
return;
}
__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
}
static inline int apic_find_highest_isr(struct kvm_lapic *apic)
{
int result;
/* Note that isr_count is always 1 with vid enabled */
if (!apic->isr_count)
return -1;
if (likely(apic->highest_isr_cache != -1))
return apic->highest_isr_cache;
result = find_highest_vector(apic->regs + APIC_ISR);
ASSERT(result == -1 || result >= 16);
return result;
}
void kvm_apic_update_tmr(struct kvm_vcpu *vcpu, u32 *tmr)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int i;
for (i = 0; i < 8; i++)
apic_set_reg(apic, APIC_TMR + 0x10 * i, tmr[i]);
}
static void apic_update_ppr(struct kvm_lapic *apic)
{
u32 tpr, isrv, ppr, old_ppr;
int isr;
old_ppr = kvm_apic_get_reg(apic, APIC_PROCPRI);
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI);
isr = apic_find_highest_isr(apic);
isrv = (isr != -1) ? isr : 0;
if ((tpr & 0xf0) >= (isrv & 0xf0))
ppr = tpr & 0xff;
else
ppr = isrv & 0xf0;
apic_debug("vlapic %p, ppr 0x%x, isr 0x%x, isrv 0x%x",
apic, ppr, isr, isrv);
if (old_ppr != ppr) {
apic_set_reg(apic, APIC_PROCPRI, ppr);
if (ppr < old_ppr)
kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
}
}
static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
{
apic_set_reg(apic, APIC_TASKPRI, tpr);
apic_update_ppr(apic);
}
int kvm_apic_match_physical_addr(struct kvm_lapic *apic, u16 dest)
{
return dest == 0xff || kvm_apic_id(apic) == dest;
}
int kvm_apic_match_logical_addr(struct kvm_lapic *apic, u8 mda)
{
int result = 0;
u32 logical_id;
if (apic_x2apic_mode(apic)) {
logical_id = kvm_apic_get_reg(apic, APIC_LDR);
return logical_id & mda;
}
logical_id = GET_APIC_LOGICAL_ID(kvm_apic_get_reg(apic, APIC_LDR));
switch (kvm_apic_get_reg(apic, APIC_DFR)) {
case APIC_DFR_FLAT:
if (logical_id & mda)
result = 1;
break;
case APIC_DFR_CLUSTER:
if (((logical_id >> 4) == (mda >> 0x4))
&& (logical_id & mda & 0xf))
result = 1;
break;
default:
apic_debug("Bad DFR vcpu %d: %08x\n",
apic->vcpu->vcpu_id, kvm_apic_get_reg(apic, APIC_DFR));
break;
}
return result;
}
int kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
int short_hand, int dest, int dest_mode)
{
int result = 0;
struct kvm_lapic *target = vcpu->arch.apic;
apic_debug("target %p, source %p, dest 0x%x, "
"dest_mode 0x%x, short_hand 0x%x\n",
target, source, dest, dest_mode, short_hand);
ASSERT(target);
switch (short_hand) {
case APIC_DEST_NOSHORT:
if (dest_mode == 0)
/* Physical mode. */
result = kvm_apic_match_physical_addr(target, dest);
else
/* Logical mode. */
result = kvm_apic_match_logical_addr(target, dest);
break;
case APIC_DEST_SELF:
result = (target == source);
break;
case APIC_DEST_ALLINC:
result = 1;
break;
case APIC_DEST_ALLBUT:
result = (target != source);
break;
default:
apic_debug("kvm: apic: Bad dest shorthand value %x\n",
short_hand);
break;
}
return result;
}
bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
struct kvm_lapic_irq *irq, int *r, unsigned long *dest_map)
{
struct kvm_apic_map *map;
unsigned long bitmap = 1;
struct kvm_lapic **dst;
int i;
bool ret = false;
*r = -1;
if (irq->shorthand == APIC_DEST_SELF) {
*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
return true;
}
if (irq->shorthand)
return false;
rcu_read_lock();
map = rcu_dereference(kvm->arch.apic_map);
if (!map)
goto out;
if (irq->dest_mode == 0) { /* physical mode */
if (irq->delivery_mode == APIC_DM_LOWEST ||
irq->dest_id == 0xff)
goto out;
dst = &map->phys_map[irq->dest_id & 0xff];
} else {
u32 mda = irq->dest_id << (32 - map->ldr_bits);
dst = map->logical_map[apic_cluster_id(map, mda)];
bitmap = apic_logical_id(map, mda);
if (irq->delivery_mode == APIC_DM_LOWEST) {
int l = -1;
for_each_set_bit(i, &bitmap, 16) {
if (!dst[i])
continue;
if (l < 0)
l = i;
else if (kvm_apic_compare_prio(dst[i]->vcpu, dst[l]->vcpu) < 0)
l = i;
}
bitmap = (l >= 0) ? 1 << l : 0;
}
}
for_each_set_bit(i, &bitmap, 16) {
if (!dst[i])
continue;
if (*r < 0)
*r = 0;
*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
}
ret = true;
out:
rcu_read_unlock();
return ret;
}
/*
* Add a pending IRQ into lapic.
* Return 1 if successfully added and 0 if discarded.
*/
static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
int vector, int level, int trig_mode,
unsigned long *dest_map)
{
int result = 0;
struct kvm_vcpu *vcpu = apic->vcpu;
switch (delivery_mode) {
case APIC_DM_LOWEST:
vcpu->arch.apic_arb_prio++;
case APIC_DM_FIXED:
/* FIXME add logic for vcpu on reset */
if (unlikely(!apic_enabled(apic)))
break;
result = 1;
if (dest_map)
__set_bit(vcpu->vcpu_id, dest_map);
if (kvm_x86_ops->deliver_posted_interrupt)
kvm_x86_ops->deliver_posted_interrupt(vcpu, vector);
else {
apic_set_irr(vector, apic);
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
}
trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
trig_mode, vector, false);
break;
case APIC_DM_REMRD:
result = 1;
vcpu->arch.pv.pv_unhalted = 1;
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
break;
case APIC_DM_SMI:
apic_debug("Ignoring guest SMI\n");
break;
case APIC_DM_NMI:
result = 1;
kvm_inject_nmi(vcpu);
kvm_vcpu_kick(vcpu);
break;
case APIC_DM_INIT:
if (!trig_mode || level) {
result = 1;
/* assumes that there are only KVM_APIC_INIT/SIPI */
apic->pending_events = (1UL << KVM_APIC_INIT);
/* make sure pending_events is visible before sending
* the request */
smp_wmb();
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
} else {
apic_debug("Ignoring de-assert INIT to vcpu %d\n",
vcpu->vcpu_id);
}
break;
case APIC_DM_STARTUP:
apic_debug("SIPI to vcpu %d vector 0x%02x\n",
vcpu->vcpu_id, vector);
result = 1;
apic->sipi_vector = vector;
/* make sure sipi_vector is visible for the receiver */
smp_wmb();
set_bit(KVM_APIC_SIPI, &apic->pending_events);
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
break;
case APIC_DM_EXTINT:
/*
* Should only be called by kvm_apic_local_deliver() with LVT0,
* before NMI watchdog was enabled. Already handled by
* kvm_apic_accept_pic_intr().
*/
break;
default:
printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
delivery_mode);
break;
}
return result;
}
int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
{
return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
}
static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
{
if (!(kvm_apic_get_reg(apic, APIC_SPIV) & APIC_SPIV_DIRECTED_EOI) &&
kvm_ioapic_handles_vector(apic->vcpu->kvm, vector)) {
int trigger_mode;
if (apic_test_vector(vector, apic->regs + APIC_TMR))
trigger_mode = IOAPIC_LEVEL_TRIG;
else
trigger_mode = IOAPIC_EDGE_TRIG;
kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
}
}
static int apic_set_eoi(struct kvm_lapic *apic)
{
int vector = apic_find_highest_isr(apic);
trace_kvm_eoi(apic, vector);
/*
* Not every write EOI will has corresponding ISR,
* one example is when Kernel check timer on setup_IO_APIC
*/
if (vector == -1)
return vector;
apic_clear_isr(vector, apic);
apic_update_ppr(apic);
kvm_ioapic_send_eoi(apic, vector);
kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
return vector;
}
/*
* this interface assumes a trap-like exit, which has already finished
* desired side effect including vISR and vPPR update.
*/
void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
{
struct kvm_lapic *apic = vcpu->arch.apic;
trace_kvm_eoi(apic, vector);
kvm_ioapic_send_eoi(apic, vector);
kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
}
EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
static void apic_send_ipi(struct kvm_lapic *apic)
{
u32 icr_low = kvm_apic_get_reg(apic, APIC_ICR);
u32 icr_high = kvm_apic_get_reg(apic, APIC_ICR2);
struct kvm_lapic_irq irq;
irq.vector = icr_low & APIC_VECTOR_MASK;
irq.delivery_mode = icr_low & APIC_MODE_MASK;
irq.dest_mode = icr_low & APIC_DEST_MASK;
irq.level = icr_low & APIC_INT_ASSERT;
irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
irq.shorthand = icr_low & APIC_SHORT_MASK;
if (apic_x2apic_mode(apic))
irq.dest_id = icr_high;
else
irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
trace_kvm_apic_ipi(icr_low, irq.dest_id);
apic_debug("icr_high 0x%x, icr_low 0x%x, "
"short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
"dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x\n",
icr_high, icr_low, irq.shorthand, irq.dest_id,
irq.trig_mode, irq.level, irq.dest_mode, irq.delivery_mode,
irq.vector);
kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
}
static u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0 ||
apic->lapic_timer.period == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
static void __report_tpr_access(struct kvm_lapic *apic, bool write)
{
struct kvm_vcpu *vcpu = apic->vcpu;
struct kvm_run *run = vcpu->run;
kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
run->tpr_access.rip = kvm_rip_read(vcpu);
run->tpr_access.is_write = write;
}
static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
{
if (apic->vcpu->arch.tpr_access_reporting)
__report_tpr_access(apic, write);
}
static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
{
u32 val = 0;
if (offset >= LAPIC_MMIO_LENGTH)
return 0;
switch (offset) {
case APIC_ID:
if (apic_x2apic_mode(apic))
val = kvm_apic_id(apic);
else
val = kvm_apic_id(apic) << 24;
break;
case APIC_ARBPRI:
apic_debug("Access APIC ARBPRI register which is for P6\n");
break;
case APIC_TMCCT: /* Timer CCR */
if (apic_lvtt_tscdeadline(apic))
return 0;
val = apic_get_tmcct(apic);
break;
case APIC_PROCPRI:
apic_update_ppr(apic);
val = kvm_apic_get_reg(apic, offset);
break;
case APIC_TASKPRI:
report_tpr_access(apic, false);
/* fall thru */
default:
val = kvm_apic_get_reg(apic, offset);
break;
}
return val;
}
static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_lapic, dev);
}
static int apic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
void *data)
{
unsigned char alignment = offset & 0xf;
u32 result;
/* this bitmask has a bit cleared for each reserved register */
static const u64 rmask = 0x43ff01ffffffe70cULL;
if ((alignment + len) > 4) {
apic_debug("KVM_APIC_READ: alignment error %x %d\n",
offset, len);
return 1;
}
if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
apic_debug("KVM_APIC_READ: read reserved register %x\n",
offset);
return 1;
}
result = __apic_read(apic, offset & ~0xf);
trace_kvm_apic_read(offset, result);
switch (len) {
case 1:
case 2:
case 4:
memcpy(data, (char *)&result + alignment, len);
break;
default:
printk(KERN_ERR "Local APIC read with len = %x, "
"should be 1,2, or 4 instead\n", len);
break;
}
return 0;
}
static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
{
return kvm_apic_hw_enabled(apic) &&
addr >= apic->base_address &&
addr < apic->base_address + LAPIC_MMIO_LENGTH;
}
static int apic_mmio_read(struct kvm_io_device *this,
gpa_t address, int len, void *data)
{
struct kvm_lapic *apic = to_lapic(this);
u32 offset = address - apic->base_address;
if (!apic_mmio_in_range(apic, address))
return -EOPNOTSUPP;
apic_reg_read(apic, offset, len, data);
return 0;
}
static void update_divide_count(struct kvm_lapic *apic)
{
u32 tmp1, tmp2, tdcr;
tdcr = kvm_apic_get_reg(apic, APIC_TDCR);
tmp1 = tdcr & 0xf;
tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
apic->divide_count = 0x1 << (tmp2 & 0x7);
apic_debug("timer divide count is 0x%x\n",
apic->divide_count);
}
static void start_apic_timer(struct kvm_lapic *apic)
{
ktime_t now;
atomic_set(&apic->lapic_timer.pending, 0);
if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
/* lapic timer in oneshot or periodic mode */
now = apic->lapic_timer.timer.base->get_time();
apic->lapic_timer.period = (u64)kvm_apic_get_reg(apic, APIC_TMICT)
* APIC_BUS_CYCLE_NS * apic->divide_count;
if (!apic->lapic_timer.period)
return;
/*
* Do not allow the guest to program periodic timers with small
* interval, since the hrtimers are not throttled by the host
* scheduler.
*/
if (apic_lvtt_period(apic)) {
s64 min_period = min_timer_period_us * 1000LL;
if (apic->lapic_timer.period < min_period) {
pr_info_ratelimited(
"kvm: vcpu %i: requested %lld ns "
"lapic timer period limited to %lld ns\n",
apic->vcpu->vcpu_id,
apic->lapic_timer.period, min_period);
apic->lapic_timer.period = min_period;
}
}
hrtimer_start(&apic->lapic_timer.timer,
ktime_add_ns(now, apic->lapic_timer.period),
HRTIMER_MODE_ABS);
apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
PRIx64 ", "
"timer initial count 0x%x, period %lldns, "
"expire @ 0x%016" PRIx64 ".\n", __func__,
APIC_BUS_CYCLE_NS, ktime_to_ns(now),
kvm_apic_get_reg(apic, APIC_TMICT),
apic->lapic_timer.period,
ktime_to_ns(ktime_add_ns(now,
apic->lapic_timer.period)));
} else if (apic_lvtt_tscdeadline(apic)) {
/* lapic timer in tsc deadline mode */
u64 guest_tsc, tscdeadline = apic->lapic_timer.tscdeadline;
u64 ns = 0;
struct kvm_vcpu *vcpu = apic->vcpu;
unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
unsigned long flags;
if (unlikely(!tscdeadline || !this_tsc_khz))
return;
local_irq_save(flags);
now = apic->lapic_timer.timer.base->get_time();
guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu, native_read_tsc());
if (likely(tscdeadline > guest_tsc)) {
ns = (tscdeadline - guest_tsc) * 1000000ULL;
do_div(ns, this_tsc_khz);
}
hrtimer_start(&apic->lapic_timer.timer,
ktime_add_ns(now, ns), HRTIMER_MODE_ABS);
local_irq_restore(flags);
}
}
static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
{
int nmi_wd_enabled = apic_lvt_nmi_mode(kvm_apic_get_reg(apic, APIC_LVT0));
if (apic_lvt_nmi_mode(lvt0_val)) {
if (!nmi_wd_enabled) {
apic_debug("Receive NMI setting on APIC_LVT0 "
"for cpu %d\n", apic->vcpu->vcpu_id);
apic->vcpu->kvm->arch.vapics_in_nmi_mode++;
}
} else if (nmi_wd_enabled)
apic->vcpu->kvm->arch.vapics_in_nmi_mode--;
}
static int apic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
{
int ret = 0;
trace_kvm_apic_write(reg, val);
switch (reg) {
case APIC_ID: /* Local APIC ID */
if (!apic_x2apic_mode(apic))
kvm_apic_set_id(apic, val >> 24);
else
ret = 1;
break;
case APIC_TASKPRI:
report_tpr_access(apic, true);
apic_set_tpr(apic, val & 0xff);
break;
case APIC_EOI:
apic_set_eoi(apic);
break;
case APIC_LDR:
if (!apic_x2apic_mode(apic))
kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
else
ret = 1;
break;
case APIC_DFR:
if (!apic_x2apic_mode(apic)) {
apic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
recalculate_apic_map(apic->vcpu->kvm);
} else
ret = 1;
break;
case APIC_SPIV: {
u32 mask = 0x3ff;
if (kvm_apic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
mask |= APIC_SPIV_DIRECTED_EOI;
apic_set_spiv(apic, val & mask);
if (!(val & APIC_SPIV_APIC_ENABLED)) {
int i;
u32 lvt_val;
for (i = 0; i < APIC_LVT_NUM; i++) {
lvt_val = kvm_apic_get_reg(apic,
APIC_LVTT + 0x10 * i);
apic_set_reg(apic, APIC_LVTT + 0x10 * i,
lvt_val | APIC_LVT_MASKED);
}
atomic_set(&apic->lapic_timer.pending, 0);
}
break;
}
case APIC_ICR:
/* No delay here, so we always clear the pending bit */
apic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
apic_send_ipi(apic);
break;
case APIC_ICR2:
if (!apic_x2apic_mode(apic))
val &= 0xff000000;
apic_set_reg(apic, APIC_ICR2, val);
break;
case APIC_LVT0:
apic_manage_nmi_watchdog(apic, val);
case APIC_LVTTHMR:
case APIC_LVTPC:
case APIC_LVT1:
case APIC_LVTERR:
/* TODO: Check vector */
if (!kvm_apic_sw_enabled(apic))
val |= APIC_LVT_MASKED;
val &= apic_lvt_mask[(reg - APIC_LVTT) >> 4];
apic_set_reg(apic, reg, val);
break;
case APIC_LVTT:
if ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) !=
(val & apic->lapic_timer.timer_mode_mask))
hrtimer_cancel(&apic->lapic_timer.timer);
if (!kvm_apic_sw_enabled(apic))
val |= APIC_LVT_MASKED;
val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
apic_set_reg(apic, APIC_LVTT, val);
break;
case APIC_TMICT:
if (apic_lvtt_tscdeadline(apic))
break;
hrtimer_cancel(&apic->lapic_timer.timer);
apic_set_reg(apic, APIC_TMICT, val);
start_apic_timer(apic);
break;
case APIC_TDCR:
if (val & 4)
apic_debug("KVM_WRITE:TDCR %x\n", val);
apic_set_reg(apic, APIC_TDCR, val);
update_divide_count(apic);
break;
case APIC_ESR:
if (apic_x2apic_mode(apic) && val != 0) {
apic_debug("KVM_WRITE:ESR not zero %x\n", val);
ret = 1;
}
break;
case APIC_SELF_IPI:
if (apic_x2apic_mode(apic)) {
apic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
} else
ret = 1;
break;
default:
ret = 1;
break;
}
if (ret)
apic_debug("Local APIC Write to read-only register %x\n", reg);
return ret;
}
static int apic_mmio_write(struct kvm_io_device *this,
gpa_t address, int len, const void *data)
{
struct kvm_lapic *apic = to_lapic(this);
unsigned int offset = address - apic->base_address;
u32 val;
if (!apic_mmio_in_range(apic, address))
return -EOPNOTSUPP;
/*
* APIC register must be aligned on 128-bits boundary.
* 32/64/128 bits registers must be accessed thru 32 bits.
* Refer SDM 8.4.1
*/
if (len != 4 || (offset & 0xf)) {
/* Don't shout loud, $infamous_os would cause only noise. */
apic_debug("apic write: bad size=%d %lx\n", len, (long)address);
return 0;
}
val = *(u32*)data;
/* too common printing */
if (offset != APIC_EOI)
apic_debug("%s: offset 0x%x with length 0x%x, and value is "
"0x%x\n", __func__, offset, len, val);
apic_reg_write(apic, offset & 0xff0, val);
return 0;
}
void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
{
if (kvm_vcpu_has_lapic(vcpu))
apic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
}
EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
/* emulate APIC access in a trap manner */
void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
{
u32 val = 0;
/* hw has done the conditional check and inst decode */
offset &= 0xff0;
apic_reg_read(vcpu->arch.apic, offset, 4, &val);
/* TODO: optimize to just emulate side effect w/o one more write */
apic_reg_write(vcpu->arch.apic, offset, val);
}
EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
void kvm_free_lapic(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!vcpu->arch.apic)
return;
hrtimer_cancel(&apic->lapic_timer.timer);
if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
static_key_slow_dec_deferred(&apic_hw_disabled);
if (!(kvm_apic_get_reg(apic, APIC_SPIV) & APIC_SPIV_APIC_ENABLED))
static_key_slow_dec_deferred(&apic_sw_disabled);
if (apic->regs)
free_page((unsigned long)apic->regs);
kfree(apic);
}
/*
*----------------------------------------------------------------------
* LAPIC interface
*----------------------------------------------------------------------
*/
u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu) || apic_lvtt_oneshot(apic) ||
apic_lvtt_period(apic))
return 0;
return apic->lapic_timer.tscdeadline;
}
void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu) || apic_lvtt_oneshot(apic) ||
apic_lvtt_period(apic))
return;
hrtimer_cancel(&apic->lapic_timer.timer);
apic->lapic_timer.tscdeadline = data;
start_apic_timer(apic);
}
void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu))
return;
apic_set_tpr(apic, ((cr8 & 0x0f) << 4)
| (kvm_apic_get_reg(apic, APIC_TASKPRI) & 4));
}
u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
{
u64 tpr;
if (!kvm_vcpu_has_lapic(vcpu))
return 0;
tpr = (u64) kvm_apic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
return (tpr & 0xf0) >> 4;
}
void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
{
u64 old_value = vcpu->arch.apic_base;
struct kvm_lapic *apic = vcpu->arch.apic;
if (!apic) {
value |= MSR_IA32_APICBASE_BSP;
vcpu->arch.apic_base = value;
return;
}
/* update jump label if enable bit changes */
if ((vcpu->arch.apic_base ^ value) & MSR_IA32_APICBASE_ENABLE) {
if (value & MSR_IA32_APICBASE_ENABLE)
static_key_slow_dec_deferred(&apic_hw_disabled);
else
static_key_slow_inc(&apic_hw_disabled.key);
recalculate_apic_map(vcpu->kvm);
}
if (!kvm_vcpu_is_bsp(apic->vcpu))
value &= ~MSR_IA32_APICBASE_BSP;
vcpu->arch.apic_base = value;
if ((old_value ^ value) & X2APIC_ENABLE) {
if (value & X2APIC_ENABLE) {
u32 id = kvm_apic_id(apic);
u32 ldr = ((id >> 4) << 16) | (1 << (id & 0xf));
kvm_apic_set_ldr(apic, ldr);
kvm_x86_ops->set_virtual_x2apic_mode(vcpu, true);
} else
kvm_x86_ops->set_virtual_x2apic_mode(vcpu, false);
}
apic->base_address = apic->vcpu->arch.apic_base &
MSR_IA32_APICBASE_BASE;
/* with FSB delivery interrupt, we can restart APIC functionality */
apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
"0x%lx.\n", apic->vcpu->arch.apic_base, apic->base_address);
}
void kvm_lapic_reset(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic;
int i;
apic_debug("%s\n", __func__);
ASSERT(vcpu);
apic = vcpu->arch.apic;
ASSERT(apic != NULL);
/* Stop the timer in case it's a reset to an active apic */
hrtimer_cancel(&apic->lapic_timer.timer);
kvm_apic_set_id(apic, vcpu->vcpu_id);
kvm_apic_set_version(apic->vcpu);
for (i = 0; i < APIC_LVT_NUM; i++)
apic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
apic_set_reg(apic, APIC_LVT0,
SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
apic_set_reg(apic, APIC_DFR, 0xffffffffU);
apic_set_spiv(apic, 0xff);
apic_set_reg(apic, APIC_TASKPRI, 0);
kvm_apic_set_ldr(apic, 0);
apic_set_reg(apic, APIC_ESR, 0);
apic_set_reg(apic, APIC_ICR, 0);
apic_set_reg(apic, APIC_ICR2, 0);
apic_set_reg(apic, APIC_TDCR, 0);
apic_set_reg(apic, APIC_TMICT, 0);
for (i = 0; i < 8; i++) {
apic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
apic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
apic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
}
apic->irr_pending = kvm_apic_vid_enabled(vcpu->kvm);
apic->isr_count = kvm_apic_vid_enabled(vcpu->kvm);
apic->highest_isr_cache = -1;
update_divide_count(apic);
atomic_set(&apic->lapic_timer.pending, 0);
if (kvm_vcpu_is_bsp(vcpu))
kvm_lapic_set_base(vcpu,
vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
vcpu->arch.pv_eoi.msr_val = 0;
apic_update_ppr(apic);
vcpu->arch.apic_arb_prio = 0;
vcpu->arch.apic_attention = 0;
apic_debug(KERN_INFO "%s: vcpu=%p, id=%d, base_msr="
"0x%016" PRIx64 ", base_address=0x%0lx.\n", __func__,
vcpu, kvm_apic_id(apic),
vcpu->arch.apic_base, apic->base_address);
}
/*
*----------------------------------------------------------------------
* timer interface
*----------------------------------------------------------------------
*/
static bool lapic_is_periodic(struct kvm_lapic *apic)
{
return apic_lvtt_period(apic);
}
int apic_has_pending_timer(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (kvm_vcpu_has_lapic(vcpu) && apic_enabled(apic) &&
apic_lvt_enabled(apic, APIC_LVTT))
return atomic_read(&apic->lapic_timer.pending);
return 0;
}
int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
{
u32 reg = kvm_apic_get_reg(apic, lvt_type);
int vector, mode, trig_mode;
if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
vector = reg & APIC_VECTOR_MASK;
mode = reg & APIC_MODE_MASK;
trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
NULL);
}
return 0;
}
void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (apic)
kvm_apic_local_deliver(apic, APIC_LVT0);
}
static const struct kvm_io_device_ops apic_mmio_ops = {
.read = apic_mmio_read,
.write = apic_mmio_write,
};
static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
{
struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
struct kvm_vcpu *vcpu = apic->vcpu;
wait_queue_head_t *q = &vcpu->wq;
/*
* There is a race window between reading and incrementing, but we do
* not care about potentially losing timer events in the !reinject
* case anyway. Note: KVM_REQ_PENDING_TIMER is implicitly checked
* in vcpu_enter_guest.
*/
if (!atomic_read(&ktimer->pending)) {
atomic_inc(&ktimer->pending);
/* FIXME: this code should not know anything about vcpus */
kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
}
if (waitqueue_active(q))
wake_up_interruptible(q);
if (lapic_is_periodic(apic)) {
hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
return HRTIMER_RESTART;
} else
return HRTIMER_NORESTART;
}
int kvm_create_lapic(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic;
ASSERT(vcpu != NULL);
apic_debug("apic_init %d\n", vcpu->vcpu_id);
apic = kzalloc(sizeof(*apic), GFP_KERNEL);
if (!apic)
goto nomem;
vcpu->arch.apic = apic;
apic->regs = (void *)get_zeroed_page(GFP_KERNEL);
if (!apic->regs) {
printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
vcpu->vcpu_id);
goto nomem_free_apic;
}
apic->vcpu = vcpu;
hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
HRTIMER_MODE_ABS);
apic->lapic_timer.timer.function = apic_timer_fn;
/*
* APIC is created enabled. This will prevent kvm_lapic_set_base from
* thinking that APIC satet has changed.
*/
vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
kvm_lapic_set_base(vcpu,
APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE);
static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
kvm_lapic_reset(vcpu);
kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
return 0;
nomem_free_apic:
kfree(apic);
nomem:
return -ENOMEM;
}
int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int highest_irr;
if (!kvm_vcpu_has_lapic(vcpu) || !apic_enabled(apic))
return -1;
apic_update_ppr(apic);
highest_irr = apic_find_highest_irr(apic);
if ((highest_irr == -1) ||
((highest_irr & 0xF0) <= kvm_apic_get_reg(apic, APIC_PROCPRI)))
return -1;
return highest_irr;
}
int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
{
u32 lvt0 = kvm_apic_get_reg(vcpu->arch.apic, APIC_LVT0);
int r = 0;
if (!kvm_apic_hw_enabled(vcpu->arch.apic))
r = 1;
if ((lvt0 & APIC_LVT_MASKED) == 0 &&
GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
r = 1;
return r;
}
void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu))
return;
if (atomic_read(&apic->lapic_timer.pending) > 0) {
kvm_apic_local_deliver(apic, APIC_LVTT);
atomic_set(&apic->lapic_timer.pending, 0);
}
}
int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
{
int vector = kvm_apic_has_interrupt(vcpu);
struct kvm_lapic *apic = vcpu->arch.apic;
if (vector == -1)
return -1;
apic_set_isr(vector, apic);
apic_update_ppr(apic);
apic_clear_irr(vector, apic);
return vector;
}
void kvm_apic_post_state_restore(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
struct kvm_lapic *apic = vcpu->arch.apic;
kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
/* set SPIV separately to get count of SW disabled APICs right */
apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
/* call kvm_apic_set_id() to put apic into apic_map */
kvm_apic_set_id(apic, kvm_apic_id(apic));
kvm_apic_set_version(vcpu);
apic_update_ppr(apic);
hrtimer_cancel(&apic->lapic_timer.timer);
update_divide_count(apic);
start_apic_timer(apic);
apic->irr_pending = true;
apic->isr_count = kvm_apic_vid_enabled(vcpu->kvm) ?
1 : count_vectors(apic->regs + APIC_ISR);
apic->highest_isr_cache = -1;
kvm_x86_ops->hwapic_isr_update(vcpu->kvm, apic_find_highest_isr(apic));
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_rtc_eoi_tracking_restore_one(vcpu);
}
void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
{
struct hrtimer *timer;
if (!kvm_vcpu_has_lapic(vcpu))
return;
timer = &vcpu->arch.apic->lapic_timer.timer;
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
/*
* apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
*
* Detect whether guest triggered PV EOI since the
* last entry. If yes, set EOI on guests's behalf.
* Clear PV EOI in guest memory in any case.
*/
static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
struct kvm_lapic *apic)
{
bool pending;
int vector;
/*
* PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
* and KVM_PV_EOI_ENABLED in guest memory as follows:
*
* KVM_APIC_PV_EOI_PENDING is unset:
* -> host disabled PV EOI.
* KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
* -> host enabled PV EOI, guest did not execute EOI yet.
* KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
* -> host enabled PV EOI, guest executed EOI.
*/
BUG_ON(!pv_eoi_enabled(vcpu));
pending = pv_eoi_get_pending(vcpu);
/*
* Clear pending bit in any case: it will be set again on vmentry.
* While this might not be ideal from performance point of view,
* this makes sure pv eoi is only enabled when we know it's safe.
*/
pv_eoi_clr_pending(vcpu);
if (pending)
return;
vector = apic_set_eoi(apic);
trace_kvm_pv_eoi(apic, vector);
}
void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
{
u32 data;
if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
sizeof(u32));
apic_set_tpr(vcpu->arch.apic, data & 0xff);
}
/*
* apic_sync_pv_eoi_to_guest - called before vmentry
*
* Detect whether it's safe to enable PV EOI and
* if yes do so.
*/
static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
struct kvm_lapic *apic)
{
if (!pv_eoi_enabled(vcpu) ||
/* IRR set or many bits in ISR: could be nested. */
apic->irr_pending ||
/* Cache not set: could be safe but we don't bother. */
apic->highest_isr_cache == -1 ||
/* Need EOI to update ioapic. */
kvm_ioapic_handles_vector(vcpu->kvm, apic->highest_isr_cache)) {
/*
* PV EOI was disabled by apic_sync_pv_eoi_from_guest
* so we need not do anything here.
*/
return;
}
pv_eoi_set_pending(apic->vcpu);
}
void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
{
u32 data, tpr;
int max_irr, max_isr;
struct kvm_lapic *apic = vcpu->arch.apic;
apic_sync_pv_eoi_to_guest(vcpu, apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI) & 0xff;
max_irr = apic_find_highest_irr(apic);
if (max_irr < 0)
max_irr = 0;
max_isr = apic_find_highest_isr(apic);
if (max_isr < 0)
max_isr = 0;
data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
sizeof(u32));
}
int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
{
if (vapic_addr) {
if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
&vcpu->arch.apic->vapic_cache,
vapic_addr, sizeof(u32)))
return -EINVAL;
__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
} else {
__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
}
vcpu->arch.apic->vapic_addr = vapic_addr;
return 0;
}
int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
u32 reg = (msr - APIC_BASE_MSR) << 4;
if (!irqchip_in_kernel(vcpu->kvm) || !apic_x2apic_mode(apic))
return 1;
/* if this is ICR write vector before command */
if (msr == 0x830)
apic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
return apic_reg_write(apic, reg, (u32)data);
}
int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
if (!irqchip_in_kernel(vcpu->kvm) || !apic_x2apic_mode(apic))
return 1;
if (apic_reg_read(apic, reg, 4, &low))
return 1;
if (msr == 0x830)
apic_reg_read(apic, APIC_ICR2, 4, &high);
*data = (((u64)high) << 32) | low;
return 0;
}
int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu))
return 1;
/* if this is ICR write vector before command */
if (reg == APIC_ICR)
apic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
return apic_reg_write(apic, reg, (u32)data);
}
int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
u32 low, high = 0;
if (!kvm_vcpu_has_lapic(vcpu))
return 1;
if (apic_reg_read(apic, reg, 4, &low))
return 1;
if (reg == APIC_ICR)
apic_reg_read(apic, APIC_ICR2, 4, &high);
*data = (((u64)high) << 32) | low;
return 0;
}
int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data)
{
u64 addr = data & ~KVM_MSR_ENABLED;
if (!IS_ALIGNED(addr, 4))
return 1;
vcpu->arch.pv_eoi.msr_val = data;
if (!pv_eoi_enabled(vcpu))
return 0;
return kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_eoi.data,
addr, sizeof(u8));
}
void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
unsigned int sipi_vector;
unsigned long pe;
if (!kvm_vcpu_has_lapic(vcpu) || !apic->pending_events)
return;
pe = xchg(&apic->pending_events, 0);
if (test_bit(KVM_APIC_INIT, &pe)) {
kvm_lapic_reset(vcpu);
kvm_vcpu_reset(vcpu);
if (kvm_vcpu_is_bsp(apic->vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
}
if (test_bit(KVM_APIC_SIPI, &pe) &&
vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
/* evaluate pending_events before reading the vector */
smp_rmb();
sipi_vector = apic->sipi_vector;
pr_debug("vcpu %d received sipi with vector # %x\n",
vcpu->vcpu_id, sipi_vector);
kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
}
void kvm_lapic_init(void)
{
/* do not patch jump label more than once per second */
jump_label_rate_limit(&apic_hw_disabled, HZ);
jump_label_rate_limit(&apic_sw_disabled, HZ);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5794_0 |
crossvul-cpp_data_bad_4789_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M SSSSS L %
% MM MM SS L %
% M M M SSS L %
% M M SS L %
% M M SSSSS LLLLL %
% %
% %
% Execute Magick Scripting Language Scripts. %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% William Radcliffe %
% December 2001 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/colormap.h"
#include "magick/color-private.h"
#include "magick/composite.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/display.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/effect.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/fx.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/quantum-private.h"
#include "magick/registry.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/shear.h"
#include "magick/signature.h"
#include "magick/statistic.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/transform.h"
#include "magick/threshold.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_XML_DELEGATE)
# if defined(MAGICKCORE_WINDOWS_SUPPORT)
# if !defined(__MINGW32__) && !defined(__MINGW64__)
# include <win32config.h>
# endif
# endif
# include <libxml/parser.h>
# include <libxml/xmlmemory.h>
# include <libxml/parserInternals.h>
# include <libxml/xmlerror.h>
#endif
/*
Define Declatations.
*/
#define ThrowMSLException(severity,tag,reason) \
(void) ThrowMagickException(msl_info->exception,GetMagickModule(),severity, \
tag,"`%s'",reason);
/*
Typedef declaractions.
*/
typedef struct _MSLGroupInfo
{
size_t
numImages; /* how many images are in this group */
} MSLGroupInfo;
typedef struct _MSLInfo
{
ExceptionInfo
*exception;
ssize_t
n,
number_groups;
ImageInfo
**image_info;
DrawInfo
**draw_info;
Image
**attributes,
**image;
char
*content;
MSLGroupInfo
*group_info;
#if defined(MAGICKCORE_XML_DELEGATE)
xmlParserCtxtPtr
parser;
xmlDocPtr
document;
#endif
} MSLInfo;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_XML_DELEGATE)
static MagickBooleanType
WriteMSLImage(const ImageInfo *,Image *);
static MagickBooleanType
SetMSLAttributes(MSLInfo *,const char *,const char *);
#endif
#if defined(MAGICKCORE_XML_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMSLImage() reads a Magick Scripting Language file and returns it.
% It allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMSLImage method is:
%
% Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static inline Image *GetImageCache(const ImageInfo *image_info,const char *path,
ExceptionInfo *exception)
{
char
key[MaxTextExtent];
ExceptionInfo
*sans_exception;
Image
*image;
ImageInfo
*read_info;
(void) FormatLocaleString(key,MaxTextExtent,"cache:%s",path);
sans_exception=AcquireExceptionInfo();
image=(Image *) GetImageRegistry(ImageRegistryType,key,sans_exception);
sans_exception=DestroyExceptionInfo(sans_exception);
if (image != (Image *) NULL)
return(image);
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->filename,path,MaxTextExtent);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
(void) SetImageRegistry(ImageRegistryType,key,image,exception);
return(image);
}
static int IsPathDirectory(const char *path)
{
MagickBooleanType
status;
struct stat
attributes;
if ((path == (const char *) NULL) || (*path == '\0'))
return(MagickFalse);
status=GetPathAttributes(path,&attributes);
if (status == MagickFalse)
return(-1);
if (S_ISDIR(attributes.st_mode) == 0)
return(0);
return(1);
}
static int MSLIsStandalone(void *context)
{
MSLInfo
*msl_info;
/*
Is this document tagged standalone?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.MSLIsStandalone()");
msl_info=(MSLInfo *) context;
return(msl_info->document->standalone == 1);
}
static int MSLHasInternalSubset(void *context)
{
MSLInfo
*msl_info;
/*
Does this document has an internal subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.MSLHasInternalSubset()");
msl_info=(MSLInfo *) context;
return(msl_info->document->intSubset != NULL);
}
static int MSLHasExternalSubset(void *context)
{
MSLInfo
*msl_info;
/*
Does this document has an external subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.MSLHasExternalSubset()");
msl_info=(MSLInfo *) context;
return(msl_info->document->extSubset != NULL);
}
static void MSLInternalSubset(void *context,const xmlChar *name,
const xmlChar *external_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
/*
Does this document has an internal subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.internalSubset(%s %s %s)",name,
(external_id != (const xmlChar *) NULL ? (const char *) external_id : " "),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : " "));
msl_info=(MSLInfo *) context;
(void) xmlCreateIntSubset(msl_info->document,name,external_id,system_id);
}
static xmlParserInputPtr MSLResolveEntity(void *context,
const xmlChar *public_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
xmlParserInputPtr
stream;
/*
Special entity resolver, better left to the parser, it has more
context than the application layer. The default behaviour is to
not resolve the entities, in that case the ENTITY_REF nodes are
built in the structure (and the parameter values).
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.resolveEntity(%s, %s)",
(public_id != (const xmlChar *) NULL ? (const char *) public_id : "none"),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"));
msl_info=(MSLInfo *) context;
stream=xmlLoadExternalEntity((const char *) system_id,(const char *)
public_id,msl_info->parser);
return(stream);
}
static xmlEntityPtr MSLGetEntity(void *context,const xmlChar *name)
{
MSLInfo
*msl_info;
/*
Get an entity by name.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.MSLGetEntity(%s)",(const char *) name);
msl_info=(MSLInfo *) context;
return(xmlGetDocEntity(msl_info->document,name));
}
static xmlEntityPtr MSLGetParameterEntity(void *context,const xmlChar *name)
{
MSLInfo
*msl_info;
/*
Get a parameter entity by name.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.getParameterEntity(%s)",(const char *) name);
msl_info=(MSLInfo *) context;
return(xmlGetParameterEntity(msl_info->document,name));
}
static void MSLEntityDeclaration(void *context,const xmlChar *name,int type,
const xmlChar *public_id,const xmlChar *system_id,xmlChar *content)
{
MSLInfo
*msl_info;
/*
An entity definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.entityDecl(%s, %d, %s, %s, %s)",name,type,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none",
content);
msl_info=(MSLInfo *) context;
if (msl_info->parser->inSubset == 1)
(void) xmlAddDocEntity(msl_info->document,name,type,public_id,system_id,
content);
else
if (msl_info->parser->inSubset == 2)
(void) xmlAddDtdEntity(msl_info->document,name,type,public_id,system_id,
content);
}
static void MSLAttributeDeclaration(void *context,const xmlChar *element,
const xmlChar *name,int type,int value,const xmlChar *default_value,
xmlEnumerationPtr tree)
{
MSLInfo
*msl_info;
xmlChar
*fullname,
*prefix;
xmlParserCtxtPtr
parser;
/*
An attribute definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.attributeDecl(%s, %s, %d, %d, %s, ...)\n",element,name,type,value,
default_value);
msl_info=(MSLInfo *) context;
fullname=(xmlChar *) NULL;
prefix=(xmlChar *) NULL;
parser=msl_info->parser;
fullname=(xmlChar *) xmlSplitQName(parser,name,&prefix);
if (parser->inSubset == 1)
(void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->intSubset,
element,fullname,prefix,(xmlAttributeType) type,
(xmlAttributeDefault) value,default_value,tree);
else
if (parser->inSubset == 2)
(void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->extSubset,
element,fullname,prefix,(xmlAttributeType) type,
(xmlAttributeDefault) value,default_value,tree);
if (prefix != (xmlChar *) NULL)
xmlFree(prefix);
if (fullname != (xmlChar *) NULL)
xmlFree(fullname);
}
static void MSLElementDeclaration(void *context,const xmlChar *name,int type,
xmlElementContentPtr content)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
An element definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.elementDecl(%s, %d, ...)",name,type);
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
if (parser->inSubset == 1)
(void) xmlAddElementDecl(&parser->vctxt,msl_info->document->intSubset,
name,(xmlElementTypeVal) type,content);
else
if (parser->inSubset == 2)
(void) xmlAddElementDecl(&parser->vctxt,msl_info->document->extSubset,
name,(xmlElementTypeVal) type,content);
}
static void MSLNotationDeclaration(void *context,const xmlChar *name,
const xmlChar *public_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
What to do when a notation declaration has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.notationDecl(%s, %s, %s)",name,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none");
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
if (parser->inSubset == 1)
(void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset,
name,public_id,system_id);
else
if (parser->inSubset == 2)
(void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset,
name,public_id,system_id);
}
static void MSLUnparsedEntityDeclaration(void *context,const xmlChar *name,
const xmlChar *public_id,const xmlChar *system_id,const xmlChar *notation)
{
MSLInfo
*msl_info;
/*
What to do when an unparsed entity declaration is parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.unparsedEntityDecl(%s, %s, %s, %s)",name,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none",
notation);
msl_info=(MSLInfo *) context;
(void) xmlAddDocEntity(msl_info->document,name,
XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,public_id,system_id,notation);
}
static void MSLSetDocumentLocator(void *context,xmlSAXLocatorPtr location)
{
MSLInfo
*msl_info;
/*
Receive the document locator at startup, actually xmlDefaultSAXLocator.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.setDocumentLocator()\n");
(void) location;
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLStartDocument(void *context)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
Called when the document start being processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.startDocument()");
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
msl_info->document=xmlNewDoc(parser->version);
if (msl_info->document == (xmlDocPtr) NULL)
return;
if (parser->encoding == NULL)
msl_info->document->encoding=NULL;
else
msl_info->document->encoding=xmlStrdup(parser->encoding);
msl_info->document->standalone=parser->standalone;
}
static void MSLEndDocument(void *context)
{
MSLInfo
*msl_info;
/*
Called when the document end has been detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endDocument()");
msl_info=(MSLInfo *) context;
if (msl_info->content != (char *) NULL)
msl_info->content=DestroyString(msl_info->content);
}
static void MSLPushImage(MSLInfo *msl_info,Image *image)
{
ssize_t
n;
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(msl_info != (MSLInfo *) NULL);
msl_info->n++;
n=msl_info->n;
msl_info->image_info=(ImageInfo **) ResizeQuantumMemory(msl_info->image_info,
(n+1),sizeof(*msl_info->image_info));
msl_info->draw_info=(DrawInfo **) ResizeQuantumMemory(msl_info->draw_info,
(n+1),sizeof(*msl_info->draw_info));
msl_info->attributes=(Image **) ResizeQuantumMemory(msl_info->attributes,
(n+1),sizeof(*msl_info->attributes));
msl_info->image=(Image **) ResizeQuantumMemory(msl_info->image,(n+1),
sizeof(*msl_info->image));
if ((msl_info->image_info == (ImageInfo **) NULL) ||
(msl_info->draw_info == (DrawInfo **) NULL) ||
(msl_info->attributes == (Image **) NULL) ||
(msl_info->image == (Image **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
msl_info->image_info[n]=CloneImageInfo(msl_info->image_info[n-1]);
msl_info->draw_info[n]=CloneDrawInfo(msl_info->image_info[n-1],
msl_info->draw_info[n-1]);
if (image == (Image *) NULL)
msl_info->attributes[n]=AcquireImage(msl_info->image_info[n]);
else
msl_info->attributes[n]=CloneImage(image,0,0,MagickTrue,&image->exception);
msl_info->image[n]=(Image *) image;
if ((msl_info->image_info[n] == (ImageInfo *) NULL) ||
(msl_info->attributes[n] == (Image *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
if (msl_info->number_groups != 0)
msl_info->group_info[msl_info->number_groups-1].numImages++;
}
static void MSLPopImage(MSLInfo *msl_info)
{
if (msl_info->number_groups != 0)
return;
if (msl_info->image[msl_info->n] != (Image *) NULL)
msl_info->image[msl_info->n]=DestroyImage(msl_info->image[msl_info->n]);
msl_info->attributes[msl_info->n]=DestroyImage(
msl_info->attributes[msl_info->n]);
msl_info->image_info[msl_info->n]=DestroyImageInfo(
msl_info->image_info[msl_info->n]);
msl_info->n--;
}
static void MSLStartElement(void *context,const xmlChar *tag,
const xmlChar **attributes)
{
AffineMatrix
affine,
current;
ChannelType
channel;
char
key[MaxTextExtent],
*value;
const char
*attribute,
*keyword;
double
angle;
DrawInfo
*draw_info;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*image;
int
flags;
ssize_t
option,
j,
n,
x,
y;
MSLInfo
*msl_info;
RectangleInfo
geometry;
register ssize_t
i;
size_t
height,
width;
/*
Called when an opening tag has been processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.startElement(%s",tag);
exception=AcquireExceptionInfo();
msl_info=(MSLInfo *) context;
n=msl_info->n;
keyword=(const char *) NULL;
value=(char *) NULL;
SetGeometryInfo(&geometry_info);
(void) ResetMagickMemory(&geometry,0,sizeof(geometry));
channel=DefaultChannels;
switch (*tag)
{
case 'A':
case 'a':
{
if (LocaleCompare((const char *) tag,"add-noise") == 0)
{
Image
*noise_image;
NoiseType
noise;
/*
Add noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
noise=UniformNoise;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(keyword,"noise") == 0)
{
option=ParseCommandOption(MagickNoiseOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
noise=(NoiseType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
noise_image=AddNoiseImageChannel(msl_info->image[n],channel,noise,
&msl_info->image[n]->exception);
if (noise_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=noise_image;
break;
}
if (LocaleCompare((const char *) tag,"annotate") == 0)
{
char
text[MaxTextExtent];
/*
Annotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=tan(DegreesToRadians(fmod((double) angle,
360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=tan(DegreesToRadians(fmod((double) angle,
360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
CloneString(&draw_info->text,value);
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
(void) AnnotateImage(msl_info->image[n],draw_info);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"append") == 0)
{
Image
*append_image;
MagickBooleanType
stack;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
stack=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'S':
case 's':
{
if (LocaleCompare(keyword,"stack") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
stack=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
append_image=AppendImages(msl_info->image[n],stack,
&msl_info->image[n]->exception);
if (append_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=append_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
break;
}
case 'B':
case 'b':
{
if (LocaleCompare((const char *) tag,"blur") == 0)
{
Image
*blur_image;
/*
Blur image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
blur_image=BlurImageChannel(msl_info->image[n],channel,
geometry_info.rho,geometry_info.sigma,
&msl_info->image[n]->exception);
if (blur_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=blur_image;
break;
}
if (LocaleCompare((const char *) tag,"border") == 0)
{
Image
*border_image;
/*
Border image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
msl_info->image[n]->compose=(CompositeOperator) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->border_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
border_image=BorderImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (border_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=border_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'C':
case 'c':
{
if (LocaleCompare((const char *) tag,"colorize") == 0)
{
char
opacity[MaxTextExtent];
Image
*colorize_image;
PixelPacket
target;
/*
Add noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
target=msl_info->image[n]->background_color;
(void) CopyMagickString(opacity,"100",MaxTextExtent);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&target,
&msl_info->image[n]->exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
(void) CopyMagickString(opacity,value,MaxTextExtent);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
colorize_image=ColorizeImage(msl_info->image[n],opacity,target,
&msl_info->image[n]->exception);
if (colorize_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=colorize_image;
break;
}
if (LocaleCompare((const char *) tag, "charcoal") == 0)
{
double radius = 0.0,
sigma = 1.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/*
NOTE: charcoal can have no attributes, since we use all the defaults!
*/
if (attributes != (const xmlChar **) NULL)
{
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
radius=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
sigma = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
}
/*
charcoal image.
*/
{
Image
*newImage;
newImage=CharcoalImage(msl_info->image[n],radius,sigma,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
if (LocaleCompare((const char *) tag,"chop") == 0)
{
Image
*chop_image;
/*
Chop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
chop_image=ChopImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (chop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=chop_image;
break;
}
if (LocaleCompare((const char *) tag,"color-floodfill") == 0)
{
PaintMethod
paint_method;
MagickPixelPacket
target;
/*
Color floodfill image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
SetGeometry(msl_info->image[n],&geometry);
paint_method=FloodfillMethod;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryMagickColor(value,&target,exception);
paint_method=FillToBorderMethod;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FloodfillPaintImage(msl_info->image[n],DefaultChannels,
draw_info,&target,geometry.x,geometry.y,
paint_method == FloodfillMethod ? MagickFalse : MagickTrue);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"comment") == 0)
break;
if (LocaleCompare((const char *) tag,"composite") == 0)
{
char
composite_geometry[MaxTextExtent];
CompositeOperator
compose;
Image
*composite_image,
*rotate_image;
PixelPacket
target;
/*
Composite image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
composite_image=NewImageList();
compose=OverCompositeOp;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
compose=(CompositeOperator) option;
break;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
composite_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
break;
}
}
if (composite_image == (Image *) NULL)
break;
rotate_image=NewImageList();
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blend") == 0)
{
(void) SetImageArtifact(composite_image,
"compose:args",value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
if (LocaleCompare(keyword, "color") == 0)
{
(void) QueryColorDatabase(value,
&composite_image->background_color,exception);
break;
}
if (LocaleCompare(keyword,"compose") == 0)
break;
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
msl_info->image[n]->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
break;
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"mask") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(value,value) == 0))
{
SetImageType(composite_image,TrueColorMatteType);
(void) CompositeImage(composite_image,
CopyOpacityCompositeOp,msl_info->image[j],0,0);
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
ssize_t
opacity,
y;
register ssize_t
x;
register PixelPacket
*q;
CacheView
*composite_view;
opacity=QuantumRange-StringToLong(value);
if (compose != DissolveCompositeOp)
{
(void) SetImageOpacity(composite_image,(Quantum)
opacity);
break;
}
(void) SetImageArtifact(msl_info->image[n],
"compose:args",value);
if (composite_image->matte != MagickTrue)
(void) SetImageOpacity(composite_image,OpaqueOpacity);
composite_view=AcquireAuthenticCacheView(composite_image,
exception);
for (y=0; y < (ssize_t) composite_image->rows ; y++)
{
q=GetCacheViewAuthenticPixels(composite_view,0,y,
(ssize_t) composite_image->columns,1,exception);
for (x=0; x < (ssize_t) composite_image->columns; x++)
{
if (q->opacity == OpaqueOpacity)
q->opacity=ClampToQuantum(opacity);
q++;
}
if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse)
break;
}
composite_view=DestroyCacheView(composite_view);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
rotate_image=RotateImage(composite_image,
StringToDouble(value,(char **) NULL),exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"tile") == 0)
{
MagickBooleanType
tile;
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
tile=(MagickBooleanType) option;
(void) tile;
if (rotate_image != (Image *) NULL)
(void) SetImageArtifact(rotate_image,
"compose:outside-overlay","false");
else
(void) SetImageArtifact(composite_image,
"compose:outside-overlay","false");
image=msl_info->image[n];
height=composite_image->rows;
width=composite_image->columns;
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height)
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width)
{
if (rotate_image != (Image *) NULL)
(void) CompositeImage(image,compose,rotate_image,
x,y);
else
(void) CompositeImage(image,compose,
composite_image,x,y);
}
if (rotate_image != (Image *) NULL)
rotate_image=DestroyImage(rotate_image);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
image=msl_info->image[n];
(void) FormatLocaleString(composite_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,
(double) composite_image->rows,(double) geometry.x,(double)
geometry.y);
flags=ParseGravityGeometry(image,composite_geometry,&geometry,
exception);
if (rotate_image == (Image *) NULL)
CompositeImageChannel(image,channel,compose,composite_image,
geometry.x,geometry.y);
else
{
/*
Rotate image.
*/
geometry.x-=(ssize_t) (rotate_image->columns-
composite_image->columns)/2;
geometry.y-=(ssize_t) (rotate_image->rows-composite_image->rows)/2;
CompositeImageChannel(image,channel,compose,rotate_image,
geometry.x,geometry.y);
rotate_image=DestroyImage(rotate_image);
}
composite_image=DestroyImage(composite_image);
break;
}
if (LocaleCompare((const char *) tag,"contrast") == 0)
{
MagickBooleanType
sharpen;
/*
Contrast image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
sharpen=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sharpen") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
sharpen=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) ContrastImage(msl_info->image[n],sharpen);
break;
}
if (LocaleCompare((const char *) tag,"crop") == 0)
{
Image
*crop_image;
/*
Crop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGravityGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
crop_image=CropImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (crop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=crop_image;
break;
}
if (LocaleCompare((const char *) tag,"cycle-colormap") == 0)
{
ssize_t
display;
/*
Cycle-colormap image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
display=0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"display") == 0)
{
display=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) CycleColormapImage(msl_info->image[n],display);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'D':
case 'd':
{
if (LocaleCompare((const char *) tag,"despeckle") == 0)
{
Image
*despeckle_image;
/*
Despeckle image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
despeckle_image=DespeckleImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (despeckle_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=despeckle_image;
break;
}
if (LocaleCompare((const char *) tag,"display") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) DisplayImages(msl_info->image_info[n],msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"draw") == 0)
{
char
text[MaxTextExtent];
/*
Annotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"points") == 0)
{
if (LocaleCompare(draw_info->primitive,"path") == 0)
{
(void) ConcatenateString(&draw_info->primitive," '");
ConcatenateString(&draw_info->primitive,value);
(void) ConcatenateString(&draw_info->primitive,"'");
}
else
{
(void) ConcatenateString(&draw_info->primitive," ");
ConcatenateString(&draw_info->primitive,value);
}
break;
}
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"primitive") == 0)
{
CloneString(&draw_info->primitive,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
(void) ConcatenateString(&draw_info->primitive," '");
(void) ConcatenateString(&draw_info->primitive,value);
(void) ConcatenateString(&draw_info->primitive,"'");
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
(void) DrawImage(msl_info->image[n],draw_info);
draw_info=DestroyDrawInfo(draw_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'E':
case 'e':
{
if (LocaleCompare((const char *) tag,"edge") == 0)
{
Image
*edge_image;
/*
Edge image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
edge_image=EdgeImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (edge_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=edge_image;
break;
}
if (LocaleCompare((const char *) tag,"emboss") == 0)
{
Image
*emboss_image;
/*
Emboss image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (emboss_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=emboss_image;
break;
}
if (LocaleCompare((const char *) tag,"enhance") == 0)
{
Image
*enhance_image;
/*
Enhance image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
enhance_image=EnhanceImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (enhance_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=enhance_image;
break;
}
if (LocaleCompare((const char *) tag,"equalize") == 0)
{
/*
Equalize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) EqualizeImage(msl_info->image[n]);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'F':
case 'f':
{
if (LocaleCompare((const char *) tag, "flatten") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/* no attributes here */
/* process the image */
{
Image
*newImage;
newImage=MergeImageLayers(msl_info->image[n],FlattenLayer,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
if (LocaleCompare((const char *) tag,"flip") == 0)
{
Image
*flip_image;
/*
Flip image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
flip_image=FlipImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (flip_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=flip_image;
break;
}
if (LocaleCompare((const char *) tag,"flop") == 0)
{
Image
*flop_image;
/*
Flop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
flop_image=FlopImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (flop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=flop_image;
break;
}
if (LocaleCompare((const char *) tag,"frame") == 0)
{
FrameInfo
frame_info;
Image
*frame_image;
/*
Frame image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
(void) ResetMagickMemory(&frame_info,0,sizeof(frame_info));
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
msl_info->image[n]->compose=(CompositeOperator) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->matte_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
frame_info.width=geometry.width;
frame_info.height=geometry.height;
frame_info.outer_bevel=geometry.x;
frame_info.inner_bevel=geometry.y;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
frame_info.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"inner") == 0)
{
frame_info.inner_bevel=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"outer") == 0)
{
frame_info.outer_bevel=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
frame_info.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
frame_info.x=(ssize_t) frame_info.width;
frame_info.y=(ssize_t) frame_info.height;
frame_info.width=msl_info->image[n]->columns+2*frame_info.x;
frame_info.height=msl_info->image[n]->rows+2*frame_info.y;
frame_image=FrameImage(msl_info->image[n],&frame_info,
&msl_info->image[n]->exception);
if (frame_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=frame_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) tag,"gamma") == 0)
{
char
gamma[MaxTextExtent];
MagickPixelPacket
pixel;
/*
Gamma image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
channel=UndefinedChannel;
pixel.red=0.0;
pixel.green=0.0;
pixel.blue=0.0;
*gamma='\0';
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blue") == 0)
{
pixel.blue=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
(void) CopyMagickString(gamma,value,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"green") == 0)
{
pixel.green=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"red") == 0)
{
pixel.red=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
if (*gamma == '\0')
(void) FormatLocaleString(gamma,MaxTextExtent,"%g,%g,%g",
(double) pixel.red,(double) pixel.green,(double) pixel.blue);
switch (channel)
{
default:
{
(void) GammaImage(msl_info->image[n],gamma);
break;
}
case RedChannel:
{
(void) GammaImageChannel(msl_info->image[n],RedChannel,pixel.red);
break;
}
case GreenChannel:
{
(void) GammaImageChannel(msl_info->image[n],GreenChannel,
pixel.green);
break;
}
case BlueChannel:
{
(void) GammaImageChannel(msl_info->image[n],BlueChannel,
pixel.blue);
break;
}
}
break;
}
else if (LocaleCompare((const char *) tag,"get") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,(const char *) attributes[i]);
(void) CopyMagickString(key,value,MaxTextExtent);
switch (*keyword)
{
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
(double) msl_info->image[n]->rows);
(void) SetImageProperty(msl_info->attributes[n],key,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
(double) msl_info->image[n]->columns);
(void) SetImageProperty(msl_info->attributes[n],key,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
else if (LocaleCompare((const char *) tag, "group") == 0)
{
msl_info->number_groups++;
msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory(
msl_info->group_info,msl_info->number_groups+1UL,
sizeof(*msl_info->group_info));
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) tag,"image") == 0)
{
MSLPushImage(msl_info,(Image *) NULL);
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"color") == 0)
{
Image
*next_image;
(void) CopyMagickString(msl_info->image_info[n]->filename,
"xc:",MaxTextExtent);
(void) ConcatenateMagickString(msl_info->image_info[n]->
filename,value,MaxTextExtent);
next_image=ReadImage(msl_info->image_info[n],exception);
CatchException(exception);
if (next_image == (Image *) NULL)
continue;
if (msl_info->image[n] == (Image *) NULL)
msl_info->image[n]=next_image;
else
{
register Image
*p;
/*
Link image into image list.
*/
p=msl_info->image[n];
while (p->next != (Image *) NULL)
p=GetNextImageInList(p);
next_image->previous=p;
p->next=next_image;
}
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"implode") == 0)
{
Image
*implode_image;
/*
Implode image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"amount") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (implode_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=implode_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) tag,"label") == 0)
break;
if (LocaleCompare((const char *) tag, "level") == 0)
{
double
levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,(const char *) attributes[i]);
(void) CopyMagickString(key,value,MaxTextExtent);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"black") == 0)
{
levelBlack = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
levelGamma = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"white") == 0)
{
levelWhite = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/* process image */
{
char level[MaxTextExtent + 1];
(void) FormatLocaleString(level,MaxTextExtent,"%3.6f/%3.6f/%3.6f/",
levelBlack,levelGamma,levelWhite);
LevelImage ( msl_info->image[n], level );
break;
}
}
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) tag,"magnify") == 0)
{
Image
*magnify_image;
/*
Magnify image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
magnify_image=MagnifyImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (magnify_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=magnify_image;
break;
}
if (LocaleCompare((const char *) tag,"map") == 0)
{
Image
*affinity_image;
MagickBooleanType
dither;
QuantizeInfo
*quantize_info;
/*
Map image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
affinity_image=NewImageList();
dither=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"dither") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
dither=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
affinity_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]);
quantize_info->dither=dither;
(void) RemapImages(quantize_info,msl_info->image[n],
affinity_image);
quantize_info=DestroyQuantizeInfo(quantize_info);
affinity_image=DestroyImage(affinity_image);
break;
}
if (LocaleCompare((const char *) tag,"matte-floodfill") == 0)
{
double
opacity;
MagickPixelPacket
target;
PaintMethod
paint_method;
/*
Matte floodfill image.
*/
opacity=0.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
paint_method=FloodfillMethod;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryMagickColor(value,&target,exception);
paint_method=FillToBorderMethod;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
opacity=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
draw_info->fill.opacity=ClampToQuantum(opacity);
(void) FloodfillPaintImage(msl_info->image[n],OpacityChannel,
draw_info,&target,geometry.x,geometry.y,
paint_method == FloodfillMethod ? MagickFalse : MagickTrue);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"median-filter") == 0)
{
Image
*median_image;
/*
Median-filter image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
median_image=StatisticImage(msl_info->image[n],MedianStatistic,
(size_t) geometry_info.rho,(size_t) geometry_info.sigma,
&msl_info->image[n]->exception);
if (median_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=median_image;
break;
}
if (LocaleCompare((const char *) tag,"minify") == 0)
{
Image
*minify_image;
/*
Minify image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
minify_image=MinifyImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (minify_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=minify_image;
break;
}
if (LocaleCompare((const char *) tag,"msl") == 0 )
break;
if (LocaleCompare((const char *) tag,"modulate") == 0)
{
char
modulate[MaxTextExtent];
/*
Modulate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=100.0;
geometry_info.sigma=100.0;
geometry_info.xi=100.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blackness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"brightness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"factor") == 0)
{
flags=ParseGeometry(value,&geometry_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"hue") == 0)
{
geometry_info.xi=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(keyword,"lightness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"saturation") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"whiteness") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(modulate,MaxTextExtent,"%g,%g,%g",
geometry_info.rho,geometry_info.sigma,geometry_info.xi);
(void) ModulateImage(msl_info->image[n],modulate);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'N':
case 'n':
{
if (LocaleCompare((const char *) tag,"negate") == 0)
{
MagickBooleanType
gray;
/*
Negate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
gray=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gray") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
gray=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) NegateImageChannel(msl_info->image[n],channel,gray);
break;
}
if (LocaleCompare((const char *) tag,"normalize") == 0)
{
/*
Normalize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) NormalizeImageChannel(msl_info->image[n],channel);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'O':
case 'o':
{
if (LocaleCompare((const char *) tag,"oil-paint") == 0)
{
Image
*paint_image;
/*
Oil-paint image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (paint_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=paint_image;
break;
}
if (LocaleCompare((const char *) tag,"opaque") == 0)
{
MagickPixelPacket
fill_color,
target;
/*
Opaque image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
(void) QueryMagickColor("none",&target,exception);
(void) QueryMagickColor("none",&fill_color,exception);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryMagickColor(value,&fill_color,exception);
break;
}
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) OpaquePaintImageChannel(msl_info->image[n],channel,
&target,&fill_color,MagickFalse);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'P':
case 'p':
{
if (LocaleCompare((const char *) tag,"print") == 0)
{
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"output") == 0)
{
(void) FormatLocaleFile(stdout,"%s",value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag, "profile") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
const char
*name;
const StringInfo
*profile;
Image
*profile_image;
ImageInfo
*profile_info;
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
if (*keyword == '!')
{
/*
Remove a profile from the image.
*/
(void) ProfileImage(msl_info->image[n],keyword,
(const unsigned char *) NULL,0,MagickTrue);
continue;
}
/*
Associate a profile with the image.
*/
profile_info=CloneImageInfo(msl_info->image_info[n]);
profile=GetImageProfile(msl_info->image[n],"iptc");
if (profile != (StringInfo *) NULL)
profile_info->profile=(void *) CloneStringInfo(profile);
profile_image=GetImageCache(profile_info,keyword,exception);
profile_info=DestroyImageInfo(profile_info);
if (profile_image == (Image *) NULL)
{
char
name[MaxTextExtent],
filename[MaxTextExtent];
register char
*p;
StringInfo
*profile;
(void) CopyMagickString(filename,keyword,MaxTextExtent);
(void) CopyMagickString(name,keyword,MaxTextExtent);
for (p=filename; *p != '\0'; p++)
if ((*p == ':') && (IsPathDirectory(keyword) < 0) &&
(IsPathAccessible(keyword) == MagickFalse))
{
register char
*q;
/*
Look for profile name (e.g. name:profile).
*/
(void) CopyMagickString(name,filename,(size_t)
(p-filename+1));
for (q=filename; *q != '\0'; q++)
*q=(*++p);
break;
}
profile=FileToStringInfo(filename,~0UL,exception);
if (profile != (StringInfo *) NULL)
{
(void) ProfileImage(msl_info->image[n],name,
GetStringInfoDatum(profile),(size_t)
GetStringInfoLength(profile),MagickFalse);
profile=DestroyStringInfo(profile);
}
continue;
}
ResetImageProfileIterator(profile_image);
name=GetNextImageProfile(profile_image);
while (name != (const char *) NULL)
{
profile=GetImageProfile(profile_image,name);
if (profile != (StringInfo *) NULL)
(void) ProfileImage(msl_info->image[n],name,
GetStringInfoDatum(profile),(size_t)
GetStringInfoLength(profile),MagickFalse);
name=GetNextImageProfile(profile_image);
}
profile_image=DestroyImage(profile_image);
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'Q':
case 'q':
{
if (LocaleCompare((const char *) tag,"quantize") == 0)
{
QuantizeInfo
quantize_info;
/*
Quantize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
GetQuantizeInfo(&quantize_info);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"colors") == 0)
{
quantize_info.number_colors=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
option=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,
"UnrecognizedColorspaceType",value);
quantize_info.colorspace=(ColorspaceType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"dither") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
quantize_info.dither=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"measure") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
quantize_info.measure_error=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"treedepth") == 0)
{
quantize_info.tree_depth=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) QuantizeImage(&quantize_info,msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"query-font-metrics") == 0)
{
char
text[MaxTextExtent];
MagickBooleanType
status;
TypeMetric
metrics;
/*
Query font metrics.
*/
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
CloneString(&draw_info->text,value);
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics);
if (status != MagickFalse)
{
Image
*image;
image=msl_info->attributes[n];
FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x",
"%g",metrics.pixels_per_em.x);
FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y",
"%g",metrics.pixels_per_em.y);
FormatImageProperty(image,"msl:font-metrics.ascent","%g",
metrics.ascent);
FormatImageProperty(image,"msl:font-metrics.descent","%g",
metrics.descent);
FormatImageProperty(image,"msl:font-metrics.width","%g",
metrics.width);
FormatImageProperty(image,"msl:font-metrics.height","%g",
metrics.height);
FormatImageProperty(image,"msl:font-metrics.max_advance","%g",
metrics.max_advance);
FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g",
metrics.bounds.x1);
FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g",
metrics.bounds.y1);
FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g",
metrics.bounds.x2);
FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g",
metrics.bounds.y2);
FormatImageProperty(image,"msl:font-metrics.origin.x","%g",
metrics.origin.x);
FormatImageProperty(image,"msl:font-metrics.origin.y","%g",
metrics.origin.y);
}
draw_info=DestroyDrawInfo(draw_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'R':
case 'r':
{
if (LocaleCompare((const char *) tag,"raise") == 0)
{
MagickBooleanType
raise;
/*
Raise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
raise=MagickFalse;
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"raise") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
raise=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) RaiseImage(msl_info->image[n],&geometry,raise);
break;
}
if (LocaleCompare((const char *) tag,"read") == 0)
{
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filename") == 0)
{
Image
*image;
(void) CopyMagickString(msl_info->image_info[n]->filename,
value,MaxTextExtent);
image=ReadImage(msl_info->image_info[n],exception);
CatchException(exception);
if (image == (Image *) NULL)
continue;
AppendImageToList(&msl_info->image[n],image);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"reduce-noise") == 0)
{
Image
*paint_image;
/*
Reduce-noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic,
(size_t) geometry_info.rho,(size_t) geometry_info.sigma,
&msl_info->image[n]->exception);
if (paint_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=paint_image;
break;
}
else if (LocaleCompare((const char *) tag,"repage") == 0)
{
/* init the values */
width=msl_info->image[n]->page.width;
height=msl_info->image[n]->page.height;
x=msl_info->image[n]->page.x;
y=msl_info->image[n]->page.y;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
int
flags;
RectangleInfo
geometry;
flags=ParseAbsoluteGeometry(value,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
width=geometry.width;
height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
x+=geometry.x;
if ((flags & YValue) != 0)
y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
x=geometry.x;
if ((width == 0) && (geometry.x > 0))
width=msl_info->image[n]->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
y=geometry.y;
if ((height == 0) && (geometry.y > 0))
height=msl_info->image[n]->rows+geometry.y;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
height = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
width = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
x = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
y = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
msl_info->image[n]->page.width=width;
msl_info->image[n]->page.height=height;
msl_info->image[n]->page.x=x;
msl_info->image[n]->page.y=y;
break;
}
else if (LocaleCompare((const char *) tag,"resample") == 0)
{
double
x_resolution,
y_resolution;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
x_resolution=DefaultResolution;
y_resolution=DefaultResolution;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'b':
{
if (LocaleCompare(keyword,"blur") == 0)
{
msl_info->image[n]->blur=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
ssize_t
flags;
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma*=geometry_info.rho;
x_resolution=geometry_info.rho;
y_resolution=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x-resolution") == 0)
{
x_resolution=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y-resolution") == 0)
{
y_resolution=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
Resample image.
*/
{
double
factor;
Image
*resample_image;
factor=1.0;
if (msl_info->image[n]->units == PixelsPerCentimeterResolution)
factor=2.54;
width=(size_t) (x_resolution*msl_info->image[n]->columns/
(factor*(msl_info->image[n]->x_resolution == 0.0 ? DefaultResolution :
msl_info->image[n]->x_resolution))+0.5);
height=(size_t) (y_resolution*msl_info->image[n]->rows/
(factor*(msl_info->image[n]->y_resolution == 0.0 ? DefaultResolution :
msl_info->image[n]->y_resolution))+0.5);
resample_image=ResizeImage(msl_info->image[n],width,height,
msl_info->image[n]->filter,msl_info->image[n]->blur,
&msl_info->image[n]->exception);
if (resample_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=resample_image;
}
break;
}
if (LocaleCompare((const char *) tag,"resize") == 0)
{
double
blur;
FilterTypes
filter;
Image
*resize_image;
/*
Resize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
filter=UndefinedFilter;
blur=1.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filter") == 0)
{
option=ParseCommandOption(MagickFilterOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
filter=(FilterTypes) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"support") == 0)
{
blur=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
resize_image=ResizeImage(msl_info->image[n],geometry.width,
geometry.height,filter,blur,&msl_info->image[n]->exception);
if (resize_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=resize_image;
break;
}
if (LocaleCompare((const char *) tag,"roll") == 0)
{
Image
*roll_image;
/*
Roll image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y,
&msl_info->image[n]->exception);
if (roll_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=roll_image;
break;
}
else if (LocaleCompare((const char *) tag,"roll") == 0)
{
/* init the values */
width=msl_info->image[n]->columns;
height=msl_info->image[n]->rows;
x = y = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
(void) ParseMetaGeometry(value,&x,&y,&width,&height);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
x = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
y = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
newImage=RollImage(msl_info->image[n], x, y, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
if (LocaleCompare((const char *) tag,"rotate") == 0)
{
Image
*rotate_image;
/*
Rotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
rotate_image=RotateImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (rotate_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=rotate_image;
break;
}
else if (LocaleCompare((const char *) tag,"rotate") == 0)
{
/* init the values */
double degrees = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
degrees = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
newImage=RotateImage(msl_info->image[n], degrees, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'S':
case 's':
{
if (LocaleCompare((const char *) tag,"sample") == 0)
{
Image
*sample_image;
/*
Sample image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
sample_image=SampleImage(msl_info->image[n],geometry.width,
geometry.height,&msl_info->image[n]->exception);
if (sample_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=sample_image;
break;
}
if (LocaleCompare((const char *) tag,"scale") == 0)
{
Image
*scale_image;
/*
Scale image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
scale_image=ScaleImage(msl_info->image[n],geometry.width,
geometry.height,&msl_info->image[n]->exception);
if (scale_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=scale_image;
break;
}
if (LocaleCompare((const char *) tag,"segment") == 0)
{
ColorspaceType
colorspace;
MagickBooleanType
verbose;
/*
Segment image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=1.0;
geometry_info.sigma=1.5;
colorspace=sRGBColorspace;
verbose=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"cluster-threshold") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
option=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,
"UnrecognizedColorspaceType",value);
colorspace=(ColorspaceType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.5;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"smoothing-threshold") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SegmentImage(msl_info->image[n],colorspace,verbose,
geometry_info.rho,geometry_info.sigma);
break;
}
else if (LocaleCompare((const char *) tag, "set") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"clip-mask") == 0)
{
for (j=0; j < msl_info->n; j++)
{
const char
*property;
property=GetImageProperty(msl_info->attributes[j],"id");
if (LocaleCompare(property,value) == 0)
{
SetImageMask(msl_info->image[n],msl_info->image[j]);
break;
}
}
break;
}
if (LocaleCompare(keyword,"clip-path") == 0)
{
for (j=0; j < msl_info->n; j++)
{
const char
*property;
property=GetImageProperty(msl_info->attributes[j],"id");
if (LocaleCompare(property,value) == 0)
{
SetImageClipMask(msl_info->image[n],msl_info->image[j]);
break;
}
}
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=(ColorspaceType) ParseCommandOption(
MagickColorspaceOptions,MagickFalse,value);
if (colorspace < 0)
ThrowMSLException(OptionError,"UnrecognizedColorspace",
value);
(void) TransformImageColorspace(msl_info->image[n],
(ColorspaceType) colorspace);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
flags=ParseGeometry(value,&geometry_info);
msl_info->image[n]->x_resolution=geometry_info.rho;
msl_info->image[n]->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
msl_info->image[n]->y_resolution=
msl_info->image[n]->x_resolution;
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword, "opacity") == 0)
{
ssize_t opac = OpaqueOpacity,
len = (ssize_t) strlen( value );
if (value[len-1] == '%') {
char tmp[100];
(void) CopyMagickString(tmp,value,len);
opac = StringToLong( tmp );
opac = (int)(QuantumRange * ((float)opac/100));
} else
opac = StringToLong( value );
(void) SetImageOpacity( msl_info->image[n], (Quantum) opac );
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword, "page") == 0)
{
char
page[MaxTextExtent];
const char
*image_option;
MagickStatusType
flags;
RectangleInfo
geometry;
(void) ResetMagickMemory(&geometry,0,sizeof(geometry));
image_option=GetImageArtifact(msl_info->image[n],"page");
if (image_option != (const char *) NULL)
flags=ParseAbsoluteGeometry(image_option,&geometry);
flags=ParseAbsoluteGeometry(value,&geometry);
(void) FormatLocaleString(page,MaxTextExtent,"%.20gx%.20g",
(double) geometry.width,(double) geometry.height);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
(void) FormatLocaleString(page,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,
(double) geometry.height,(double) geometry.x,(double)
geometry.y);
(void) SetImageOption(msl_info->image_info[n],keyword,page);
msl_info->image_info[n]->page=GetPageGeometry(page);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"shade") == 0)
{
Image
*shade_image;
MagickBooleanType
gray;
/*
Shade image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
gray=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"azimuth") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"elevation") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
if (LocaleCompare(keyword,"gray") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
gray=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (shade_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shade_image;
break;
}
if (LocaleCompare((const char *) tag,"shadow") == 0)
{
Image
*shadow_image;
/*
Shear image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
geometry_info.rho=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry_info.xi=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry_info.psi=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5),(ssize_t)
ceil(geometry_info.psi-0.5),&msl_info->image[n]->exception);
if (shadow_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shadow_image;
break;
}
if (LocaleCompare((const char *) tag,"sharpen") == 0)
{
double radius = 0.0,
sigma = 1.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/*
NOTE: sharpen can have no attributes, since we use all the defaults!
*/
if (attributes != (const xmlChar **) NULL)
{
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'R':
case 'r':
{
if (LocaleCompare(keyword, "radius") == 0)
{
radius = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
sigma = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
}
/*
sharpen image.
*/
{
Image
*newImage;
newImage=SharpenImage(msl_info->image[n],radius,sigma,&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
else if (LocaleCompare((const char *) tag,"shave") == 0)
{
/* init the values */
width = height = 0;
x = y = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
(void) ParseMetaGeometry(value,&x,&y,&width,&height);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
height = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
width = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
RectangleInfo
rectInfo;
rectInfo.height = height;
rectInfo.width = width;
rectInfo.x = x;
rectInfo.y = y;
newImage=ShaveImage(msl_info->image[n], &rectInfo,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
if (LocaleCompare((const char *) tag,"shear") == 0)
{
Image
*shear_image;
/*
Shear image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->background_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shear_image=ShearImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (shear_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shear_image;
break;
}
if (LocaleCompare((const char *) tag,"signature") == 0)
{
/*
Signature image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SignatureImage(msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"solarize") == 0)
{
/*
Solarize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=QuantumRange/2.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"threshold") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SolarizeImage(msl_info->image[n],geometry_info.rho);
break;
}
if (LocaleCompare((const char *) tag,"spread") == 0)
{
Image
*spread_image;
/*
Spread image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
spread_image=SpreadImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (spread_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=spread_image;
break;
}
else if (LocaleCompare((const char *) tag,"stegano") == 0)
{
Image *
watermark = (Image*) NULL;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
{
for (j=0; j<msl_info->n;j++)
{
const char *
theAttr = GetImageProperty(msl_info->attributes[j], "id");
if (theAttr && LocaleCompare(theAttr, value) == 0)
{
watermark = msl_info->image[j];
break;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
if ( watermark != (Image*) NULL )
{
Image
*newImage;
newImage=SteganoImage(msl_info->image[n], watermark, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
} else
ThrowMSLException(OptionError,"MissingWatermarkImage",keyword);
}
else if (LocaleCompare((const char *) tag,"stereo") == 0)
{
Image *
stereoImage = (Image*) NULL;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
{
for (j=0; j<msl_info->n;j++)
{
const char *
theAttr = GetImageProperty(msl_info->attributes[j], "id");
if (theAttr && LocaleCompare(theAttr, value) == 0)
{
stereoImage = msl_info->image[j];
break;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
if ( stereoImage != (Image*) NULL )
{
Image
*newImage;
newImage=StereoImage(msl_info->image[n], stereoImage, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
} else
ThrowMSLException(OptionError,"Missing stereo image",keyword);
}
if (LocaleCompare((const char *) tag,"strip") == 0)
{
/*
Strip image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
(void) StripImage(msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"swap") == 0)
{
Image
*p,
*q,
*swap;
ssize_t
index,
swap_index;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
index=(-1);
swap_index=(-2);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"indexes") == 0)
{
flags=ParseGeometry(value,&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) == 0)
swap_index=(ssize_t) geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
/*
Swap images.
*/
p=GetImageFromList(msl_info->image[n],index);
q=GetImageFromList(msl_info->image[n],swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag);
break;
}
swap=CloneImage(p,0,0,MagickTrue,&p->exception);
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,&q->exception));
ReplaceImageInList(&q,swap);
msl_info->image[n]=GetFirstImageInList(q);
break;
}
if (LocaleCompare((const char *) tag,"swirl") == 0)
{
Image
*swirl_image;
/*
Swirl image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (swirl_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=swirl_image;
break;
}
if (LocaleCompare((const char *) tag,"sync") == 0)
{
/*
Sync image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SyncImage(msl_info->image[n]);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'T':
case 't':
{
if (LocaleCompare((const char *) tag,"map") == 0)
{
Image
*texture_image;
/*
Texture image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
texture_image=NewImageList();
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
texture_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) TextureImage(msl_info->image[n],texture_image);
texture_image=DestroyImage(texture_image);
break;
}
else if (LocaleCompare((const char *) tag,"threshold") == 0)
{
/* init the values */
double threshold = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'T':
case 't':
{
if (LocaleCompare(keyword,"threshold") == 0)
{
threshold = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
BilevelImageChannel(msl_info->image[n],
(ChannelType) ((ssize_t) (CompositeChannels &~ (ssize_t) OpacityChannel)),
threshold);
break;
}
}
else if (LocaleCompare((const char *) tag, "transparent") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"color") == 0)
{
MagickPixelPacket
target;
(void) QueryMagickColor(value,&target,exception);
(void) TransparentPaintImage(msl_info->image[n],&target,
TransparentOpacity,MagickFalse);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
else if (LocaleCompare((const char *) tag, "trim") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
/* no attributes here */
/* process the image */
{
Image
*newImage;
RectangleInfo
rectInfo;
/* all zeros on a crop == trim edges! */
rectInfo.height = rectInfo.width = 0;
rectInfo.x = rectInfo.y = 0;
newImage=CropImage(msl_info->image[n],&rectInfo, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'W':
case 'w':
{
if (LocaleCompare((const char *) tag,"write") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filename") == 0)
{
(void) CopyMagickString(msl_info->image[n]->filename,value,
MaxTextExtent);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
/* process */
{
*msl_info->image_info[n]->magick='\0';
(void) WriteImage(msl_info->image_info[n], msl_info->image[n]);
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
break;
}
}
if ( value != NULL )
value=DestroyString(value);
exception=DestroyExceptionInfo(exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," )");
}
static void MSLEndElement(void *context,const xmlChar *tag)
{
ssize_t
n;
MSLInfo
*msl_info;
/*
Called when the end of an element has been detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endElement(%s)",
tag);
msl_info=(MSLInfo *) context;
n=msl_info->n;
switch (*tag)
{
case 'C':
case 'c':
{
if (LocaleCompare((const char *) tag,"comment") == 0 )
{
(void) DeleteImageProperty(msl_info->image[n],"comment");
if (msl_info->content == (char *) NULL)
break;
StripString(msl_info->content);
(void) SetImageProperty(msl_info->image[n],"comment",
msl_info->content);
break;
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) tag, "group") == 0 )
{
if (msl_info->group_info[msl_info->number_groups-1].numImages > 0 )
{
ssize_t i = (ssize_t)
(msl_info->group_info[msl_info->number_groups-1].numImages);
while ( i-- )
{
if (msl_info->image[msl_info->n] != (Image *) NULL)
msl_info->image[msl_info->n]=DestroyImage(msl_info->image[msl_info->n]);
msl_info->attributes[msl_info->n]=DestroyImage(msl_info->attributes[msl_info->n]);
msl_info->image_info[msl_info->n]=DestroyImageInfo(msl_info->image_info[msl_info->n]);
msl_info->n--;
}
}
msl_info->number_groups--;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) tag, "image") == 0)
MSLPopImage(msl_info);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) tag,"label") == 0 )
{
(void) DeleteImageProperty(msl_info->image[n],"label");
if (msl_info->content == (char *) NULL)
break;
StripString(msl_info->content);
(void) SetImageProperty(msl_info->image[n],"label",
msl_info->content);
break;
}
break;
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) tag, "msl") == 0 )
{
/*
This our base element.
at the moment we don't do anything special
but someday we might!
*/
}
break;
}
default:
break;
}
if (msl_info->content != (char *) NULL)
msl_info->content=DestroyString(msl_info->content);
}
static void MSLCharacters(void *context,const xmlChar *c,int length)
{
MSLInfo
*msl_info;
register char
*p;
register ssize_t
i;
/*
Receiving some characters from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.characters(%s,%d)",c,length);
msl_info=(MSLInfo *) context;
if (msl_info->content != (char *) NULL)
msl_info->content=(char *) ResizeQuantumMemory(msl_info->content,
strlen(msl_info->content)+length+MaxTextExtent,
sizeof(*msl_info->content));
else
{
msl_info->content=(char *) NULL;
if (~length >= (MaxTextExtent-1))
msl_info->content=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*msl_info->content));
if (msl_info->content != (char *) NULL)
*msl_info->content='\0';
}
if (msl_info->content == (char *) NULL)
return;
p=msl_info->content+strlen(msl_info->content);
for (i=0; i < length; i++)
*p++=c[i];
*p='\0';
}
static void MSLReference(void *context,const xmlChar *name)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
Called when an entity reference is detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.reference(%s)",name);
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
if (*name == '#')
(void) xmlAddChild(parser->node,xmlNewCharRef(msl_info->document,name));
else
(void) xmlAddChild(parser->node,xmlNewReference(msl_info->document,name));
}
static void MSLIgnorableWhitespace(void *context,const xmlChar *c,int length)
{
MSLInfo
*msl_info;
/*
Receiving some ignorable whitespaces from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.ignorableWhitespace(%.30s, %d)",c,length);
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLProcessingInstructions(void *context,const xmlChar *target,
const xmlChar *data)
{
MSLInfo
*msl_info;
/*
A processing instruction has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.processingInstruction(%s, %s)",
target,data);
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLComment(void *context,const xmlChar *value)
{
MSLInfo
*msl_info;
/*
A comment has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.comment(%s)",value);
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLWarning(void *context,const char *format,...)
{
char
*message,
reason[MaxTextExtent];
MSLInfo
*msl_info;
va_list
operands;
/**
Display and format a warning messages, gives file, line, position and
extra parameters.
*/
va_start(operands,format);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.warning: ");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands);
msl_info=(MSLInfo *) context;
(void) msl_info;
#if !defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsprintf(reason,format,operands);
#else
(void) vsnprintf(reason,MaxTextExtent,format,operands);
#endif
message=GetExceptionMessage(errno);
ThrowMSLException(CoderError,reason,message);
message=DestroyString(message);
va_end(operands);
}
static void MSLError(void *context,const char *format,...)
{
char
reason[MaxTextExtent];
MSLInfo
*msl_info;
va_list
operands;
/*
Display and format a error formats, gives file, line, position and
extra parameters.
*/
va_start(operands,format);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.error: ");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands);
msl_info=(MSLInfo *) context;
(void) msl_info;
#if !defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsprintf(reason,format,operands);
#else
(void) vsnprintf(reason,MaxTextExtent,format,operands);
#endif
ThrowMSLException(DelegateFatalError,reason,"SAX error");
va_end(operands);
}
static void MSLCDataBlock(void *context,const xmlChar *value,int length)
{
MSLInfo
*msl_info;
xmlNodePtr
child;
xmlParserCtxtPtr
parser;
/*
Called when a pcdata block has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.pcdata(%s, %d)",value,length);
msl_info=(MSLInfo *) context;
(void) msl_info;
parser=msl_info->parser;
child=xmlGetLastChild(parser->node);
if ((child != (xmlNodePtr) NULL) && (child->type == XML_CDATA_SECTION_NODE))
{
xmlTextConcat(child,value,length);
return;
}
(void) xmlAddChild(parser->node,xmlNewCDataBlock(parser->myDoc,value,length));
}
static void MSLExternalSubset(void *context,const xmlChar *name,
const xmlChar *external_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
xmlParserCtxt
parser_context;
xmlParserCtxtPtr
parser;
xmlParserInputPtr
input;
/*
Does this document has an external subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.externalSubset(%s %s %s)",name,
(external_id != (const xmlChar *) NULL ? (const char *) external_id : " "),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : " "));
msl_info=(MSLInfo *) context;
(void) msl_info;
parser=msl_info->parser;
if (((external_id == NULL) && (system_id == NULL)) ||
((parser->validate == 0) || (parser->wellFormed == 0) ||
(msl_info->document == 0)))
return;
input=MSLResolveEntity(context,external_id,system_id);
if (input == NULL)
return;
(void) xmlNewDtd(msl_info->document,name,external_id,system_id);
parser_context=(*parser);
parser->inputTab=(xmlParserInputPtr *) xmlMalloc(5*sizeof(*parser->inputTab));
if (parser->inputTab == (xmlParserInputPtr *) NULL)
{
parser->errNo=XML_ERR_NO_MEMORY;
parser->input=parser_context.input;
parser->inputNr=parser_context.inputNr;
parser->inputMax=parser_context.inputMax;
parser->inputTab=parser_context.inputTab;
return;
}
parser->inputNr=0;
parser->inputMax=5;
parser->input=NULL;
xmlPushInput(parser,input);
(void) xmlSwitchEncoding(parser,xmlDetectCharEncoding(parser->input->cur,4));
if (input->filename == (char *) NULL)
input->filename=(char *) xmlStrdup(system_id);
input->line=1;
input->col=1;
input->base=parser->input->cur;
input->cur=parser->input->cur;
input->free=NULL;
xmlParseExternalSubset(parser,external_id,system_id);
while (parser->inputNr > 1)
(void) xmlPopInput(parser);
xmlFreeInputStream(parser->input);
xmlFree(parser->inputTab);
parser->input=parser_context.input;
parser->inputNr=parser_context.inputNr;
parser->inputMax=parser_context.inputMax;
parser->inputTab=parser_context.inputTab;
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info,
Image **image,ExceptionInfo *exception)
{
char
message[MaxTextExtent];
Image
*msl_image;
int
status;
ssize_t
n;
MSLInfo
msl_info;
xmlSAXHandler
sax_modules;
xmlSAXHandlerPtr
sax_handler;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(image != (Image **) NULL);
msl_image=AcquireImage(image_info);
status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
msl_image->filename);
msl_image=DestroyImageList(msl_image);
return(MagickFalse);
}
msl_image->columns=1;
msl_image->rows=1;
/*
Parse MSL file.
*/
(void) ResetMagickMemory(&msl_info,0,sizeof(msl_info));
msl_info.exception=exception;
msl_info.image_info=(ImageInfo **) AcquireMagickMemory(
sizeof(*msl_info.image_info));
msl_info.draw_info=(DrawInfo **) AcquireMagickMemory(
sizeof(*msl_info.draw_info));
/* top of the stack is the MSL file itself */
msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image));
msl_info.attributes=(Image **) AcquireMagickMemory(
sizeof(*msl_info.attributes));
msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory(
sizeof(*msl_info.group_info));
if ((msl_info.image_info == (ImageInfo **) NULL) ||
(msl_info.image == (Image **) NULL) ||
(msl_info.attributes == (Image **) NULL) ||
(msl_info.group_info == (MSLGroupInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,
"UnableToInterpretMSLImage");
*msl_info.image_info=CloneImageInfo(image_info);
*msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
*msl_info.attributes=AcquireImage(image_info);
msl_info.group_info[0].numImages=0;
/* the first slot is used to point to the MSL file image */
*msl_info.image=msl_image;
if (*image != (Image *) NULL)
MSLPushImage(&msl_info,*image);
(void) xmlSubstituteEntitiesDefault(1);
(void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules));
sax_modules.internalSubset=MSLInternalSubset;
sax_modules.isStandalone=MSLIsStandalone;
sax_modules.hasInternalSubset=MSLHasInternalSubset;
sax_modules.hasExternalSubset=MSLHasExternalSubset;
sax_modules.resolveEntity=MSLResolveEntity;
sax_modules.getEntity=MSLGetEntity;
sax_modules.entityDecl=MSLEntityDeclaration;
sax_modules.notationDecl=MSLNotationDeclaration;
sax_modules.attributeDecl=MSLAttributeDeclaration;
sax_modules.elementDecl=MSLElementDeclaration;
sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration;
sax_modules.setDocumentLocator=MSLSetDocumentLocator;
sax_modules.startDocument=MSLStartDocument;
sax_modules.endDocument=MSLEndDocument;
sax_modules.startElement=MSLStartElement;
sax_modules.endElement=MSLEndElement;
sax_modules.reference=MSLReference;
sax_modules.characters=MSLCharacters;
sax_modules.ignorableWhitespace=MSLIgnorableWhitespace;
sax_modules.processingInstruction=MSLProcessingInstructions;
sax_modules.comment=MSLComment;
sax_modules.warning=MSLWarning;
sax_modules.error=MSLError;
sax_modules.fatalError=MSLError;
sax_modules.getParameterEntity=MSLGetParameterEntity;
sax_modules.cdataBlock=MSLCDataBlock;
sax_modules.externalSubset=MSLExternalSubset;
sax_handler=(&sax_modules);
msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0,
msl_image->filename);
while (ReadBlobString(msl_image,message) != (char *) NULL)
{
n=(ssize_t) strlen(message);
if (n == 0)
continue;
status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse);
if (status != 0)
break;
(void) xmlParseChunk(msl_info.parser," ",1,MagickFalse);
if (msl_info.exception->severity >= ErrorException)
break;
}
if (msl_info.exception->severity == UndefinedException)
(void) xmlParseChunk(msl_info.parser," ",1,MagickTrue);
xmlFreeParserCtxt(msl_info.parser);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX");
msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory(
msl_info.group_info);
if (*image == (Image *) NULL)
*image=(*msl_info.image);
if ((*msl_info.image)->exception.severity != UndefinedException)
return(MagickFalse);
return(MagickTrue);
}
static Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=(Image *) NULL;
(void) ProcessMSLScript(image_info,&image,exception);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMSLImage() adds attributes for the MSL image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMSLImage method is:
%
% size_t RegisterMSLImage(void)
%
*/
ModuleExport size_t RegisterMSLImage(void)
{
MagickInfo
*entry;
#if defined(MAGICKCORE_XML_DELEGATE)
xmlInitParser();
#endif
entry=SetMagickInfo("MSL");
#if defined(MAGICKCORE_XML_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMSLImage;
entry->encoder=(EncodeImageHandler *) WriteMSLImage;
#endif
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Magick Scripting Language");
entry->module=ConstantString("MSL");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
#if defined(MAGICKCORE_XML_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t M S L A t t r i b u t e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetMSLAttributes() ...
%
% The format of the SetMSLAttributes method is:
%
% MagickBooleanType SetMSLAttributes(MSLInfo *msl_info,
% const char *keyword,const char *value)
%
% A description of each parameter follows:
%
% o msl_info: the MSL info.
%
% o keyword: the keyword.
%
% o value: the value.
%
*/
static MagickBooleanType SetMSLAttributes(MSLInfo *msl_info,const char *keyword,
const char *value)
{
Image
*attributes;
DrawInfo
*draw_info;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*image;
ImageInfo
*image_info;
int
flags;
ssize_t
n;
assert(msl_info != (MSLInfo *) NULL);
if (keyword == (const char *) NULL)
return(MagickTrue);
if (value == (const char *) NULL)
return(MagickTrue);
exception=msl_info->exception;
n=msl_info->n;
attributes=msl_info->attributes[n];
image_info=msl_info->image_info[n];
draw_info=msl_info->draw_info[n];
image=msl_info->image[n];
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"adjoin") == 0)
{
ssize_t
adjoin;
adjoin=ParseCommandOption(MagickBooleanOptions,MagickFalse,value);
if (adjoin < 0)
ThrowMSLException(OptionError,"UnrecognizedType",value);
image_info->adjoin=(MagickBooleanType) adjoin;
break;
}
if (LocaleCompare(keyword,"alpha") == 0)
{
ssize_t
alpha;
alpha=ParseCommandOption(MagickAlphaOptions,MagickFalse,value);
if (alpha < 0)
ThrowMSLException(OptionError,"UnrecognizedType",value);
if (image != (Image *) NULL)
(void) SetImageAlphaChannel(image,(AlphaChannelType) alpha);
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
ssize_t
antialias;
antialias=ParseCommandOption(MagickBooleanOptions,MagickFalse,value);
if (antialias < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",value);
image_info->antialias=(MagickBooleanType) antialias;
break;
}
if (LocaleCompare(keyword,"area-limit") == 0)
{
MagickSizeType
limit;
limit=MagickResourceInfinity;
if (LocaleCompare(value,"unlimited") != 0)
limit=(MagickSizeType) StringToDoubleInterval(value,100.0);
(void) SetMagickResourceLimit(AreaResource,limit);
break;
}
if (LocaleCompare(keyword,"attenuate") == 0)
{
(void) SetImageOption(image_info,keyword,value);
break;
}
if (LocaleCompare(keyword,"authenticate") == 0)
{
(void) CloneString(&image_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"background") == 0)
{
(void) QueryColorDatabase(value,&image_info->background_color,
exception);
break;
}
if (LocaleCompare(keyword,"bias") == 0)
{
if (image == (Image *) NULL)
break;
image->bias=StringToDoubleInterval(value,(double) QuantumRange+1.0);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
if (image == (Image *) NULL)
break;
flags=ParseGeometry(value,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryColorDatabase(value,&image_info->border_color,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
(void) CloneString(&image_info->density,value);
(void) CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,exception);
(void) SetImageOption(image_info,keyword,value);
break;
}
if (LocaleCompare(keyword,"filename") == 0)
{
(void) CopyMagickString(image_info->filename,value,MaxTextExtent);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gravity") == 0)
{
ssize_t
gravity;
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value);
if (gravity < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",value);
(void) SetImageOption(image_info,keyword,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) SetImageProperty(attributes,keyword,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"magick") == 0)
{
(void) CopyMagickString(image_info->magick,value,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"mattecolor") == 0)
{
(void) QueryColorDatabase(value,&image_info->matte_color,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
image_info->pointsize=StringToDouble(value,(char **) NULL);
draw_info->pointsize=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image_info->quality=StringToLong(value);
if (image == (Image *) NULL)
break;
image->quality=StringToLong(value);
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"size") == 0)
{
(void) CloneString(&image_info->size,value);
break;
}
if (LocaleCompare(keyword,"stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,exception);
(void) SetImageOption(image_info,keyword,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
return(MagickTrue);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMSLImage() removes format registrations made by the
% MSL module from the list of supported formats.
%
% The format of the UnregisterMSLImage method is:
%
% UnregisterMSLImage(void)
%
*/
ModuleExport void UnregisterMSLImage(void)
{
(void) UnregisterMagickInfo("MSL");
#if defined(MAGICKCORE_XML_DELEGATE)
xmlCleanupParser();
#endif
}
#if defined(MAGICKCORE_XML_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMSLImage() writes an image to a file in MVG image format.
%
% The format of the WriteMSLImage method is:
%
% MagickBooleanType WriteMSLImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteMSLImage(const ImageInfo *image_info,Image *image)
{
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
(void) ReferenceImage(image);
(void) ProcessMSLScript(image_info,&image,&image->exception);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4789_1 |
crossvul-cpp_data_good_4783_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT IIIII FFFFF FFFFF %
% T I F F %
% T I FFF FFF %
% T I F F %
% T IIIII F F %
% %
% %
% Read/Write TIFF Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
#ifdef __VMS
#define JPEG_SUPPORT 1
#endif
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/profile.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread_.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
# if defined(MAGICKCORE_HAVE_TIFFCONF_H)
# include "tiffconf.h"
# endif
# include "tiff.h"
# include "tiffio.h"
# if !defined(COMPRESSION_ADOBE_DEFLATE)
# define COMPRESSION_ADOBE_DEFLATE 8
# endif
# if !defined(PREDICTOR_HORIZONTAL)
# define PREDICTOR_HORIZONTAL 2
# endif
# if !defined(TIFFTAG_COPYRIGHT)
# define TIFFTAG_COPYRIGHT 33432
# endif
# if !defined(TIFFTAG_OPIIMAGEID)
# define TIFFTAG_OPIIMAGEID 32781
# endif
#include "psd-private.h"
/*
Typedef declarations.
*/
typedef enum
{
ReadSingleSampleMethod,
ReadRGBAMethod,
ReadCMYKAMethod,
ReadYCCKMethod,
ReadStripMethod,
ReadTileMethod,
ReadGenericMethod
} TIFFMethodType;
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
typedef struct _ExifInfo
{
unsigned int
tag,
type,
variable_length;
const char
*property;
} ExifInfo;
static const ExifInfo
exif_info[] = {
{ EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
{ EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
{ EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
{ EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
{ EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
{ EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
{ EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
{ EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
{ EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
{ EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
{ EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
{ EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
{ EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
{ EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
{ EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
{ EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
{ EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
{ EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
{ 0, 0, 0, (char *) NULL }
};
#endif
#endif /* MAGICKCORE_TIFF_DELEGATE */
/*
Global declarations.
*/
static MagickThreadKey
tiff_exception;
static SemaphoreInfo
*tiff_semaphore = (SemaphoreInfo *) NULL;
static TIFFErrorHandler
error_handler,
warning_handler;
static volatile MagickBooleanType
instantiate_key = MagickFalse;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_TIFF_DELEGATE)
static Image *
ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
static MagickBooleanType
WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTIFF() returns MagickTrue if the image format type, identified by the
% magick string, is TIFF.
%
% The format of the IsTIFF method is:
%
% MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadGROUP4Image method is:
%
% Image *ReadGROUP4Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline size_t WriteLSBLong(FILE *file,const size_t value)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
return(fwrite(buffer,1,4,file));
}
static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(long) image->resolution.x);
length=WriteLSBLong(file,1);
status=MagickTrue;
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
if (fputc(c,file) != c)
status=MagickFalse;
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent);
}
(void) RelinquishUniqueFileResource(filename);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
% memory necessary for the new Image structure and returns a pointer to the
% new image.
%
% The format of the ReadTIFFImage method is:
%
% Image *ReadTIFFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline unsigned char ClampYCC(double value)
{
value=255.0-value;
if (value < 0.0)
return((unsigned char)0);
if (value > 255.0)
return((unsigned char)255);
return((unsigned char)(value));
}
static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(image,q)+0.5;
if (a > 1.0)
a-=1.0;
b=QuantumScale*GetPixelb(image,q)+0.5;
if (b > 1.0)
b-=1.0;
SetPixela(image,QuantumRange*a,q);
SetPixelb(image,QuantumRange*b,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType ReadProfile(Image *image,const char *name,
const unsigned char *datum,ssize_t length,ExceptionInfo *exception)
{
MagickBooleanType
status;
StringInfo
*profile;
if (length < 4)
return(MagickFalse);
profile=BlobToStringInfo(datum,(size_t) length);
if (profile == (StringInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=SetImageProfile(image,name,profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
return(MagickTrue);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int TIFFCloseBlob(thandle_t image)
{
(void) CloseBlob((Image *) image);
return(0);
}
static void TIFFErrors(const char *module,const char *format,va_list error)
{
char
message[MagickPathExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MagickPathExtent,format,error);
#else
(void) vsprintf(message,format,error);
#endif
(void) ConcatenateMagickString(message,".",MagickPathExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",module);
}
static toff_t TIFFGetBlobSize(thandle_t image)
{
return((toff_t) GetBlobSize((Image *) image));
}
static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping,
ExceptionInfo *exception)
{
uint32
length;
unsigned char
*profile;
length=0;
if (ping == MagickFalse)
{
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"icc",profile,(ssize_t) length,exception);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
(void) ReadProfile(image,"iptc",profile,4L*length,exception);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,
exception);
}
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
}
static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
{
char
message[MagickPathExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
(void) SetImageProperty(image,"tiff:artist",text,exception);
if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
(void) SetImageProperty(image,"tiff:copyright",text,exception);
if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
(void) SetImageProperty(image,"tiff:timestamp",text,exception);
if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
(void) SetImageProperty(image,"tiff:document",text,exception);
if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
(void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
(void) SetImageProperty(image,"comment",text,exception);
if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
(void) SetImageProperty(image,"tiff:make",text,exception);
if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
(void) SetImageProperty(image,"tiff:model",text,exception);
if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
(void) SetImageProperty(image,"label",text,exception);
if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
(void) SetImageProperty(image,"tiff:software",text,exception);
if (TIFFGetField(tiff,33423,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
}
if (TIFFGetField(tiff,36867,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
break;
}
default:
break;
}
if (TIFFGetField(tiff,37706,&length,&tietz) == 1)
{
(void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message,exception);
}
}
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
ExceptionInfo *exception)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
char
value[MagickPathExtent];
register ssize_t
i;
tdir_t
directory;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
offset;
void
*sans;
/*
Read EXIF properties.
*/
offset=0;
if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
return;
directory=TIFFCurrentDirectory(tiff);
if (TIFFReadEXIFDirectory(tiff,offset) != 1)
{
TIFFSetDirectory(tiff,directory);
return;
}
sans=NULL;
for (i=0; exif_info[i].tag != 0; i++)
{
*value='\0';
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
char
*ascii;
ascii=(char *) NULL;
if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) &&
(ascii != (char *) NULL) && (*ascii != '\0'))
(void) CopyMagickString(value,ascii,MagickPathExtent);
break;
}
case TIFF_SHORT:
{
if (exif_info[i].variable_length == 0)
{
uint16
shorty;
shorty=0;
if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%d",shorty);
}
else
{
int
tiff_status;
uint16
*shorty;
uint16
shorty_num;
tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
&sans,&sans);
if (tiff_status == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%d",
shorty_num != 0 ? shorty[0] : 0);
}
break;
}
case TIFF_LONG:
{
uint32
longy;
longy=0;
if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%d",longy);
break;
}
#if defined(TIFF_VERSION_BIG)
case TIFF_LONG8:
{
uint64
long8y;
long8y=0;
if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
((MagickOffsetType) long8y));
break;
}
#endif
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
case TIFF_FLOAT:
{
float
floaty;
floaty=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%g",(double)
floaty);
break;
}
case TIFF_DOUBLE:
{
double
doubley;
doubley=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%g",doubley);
break;
}
default:
break;
}
if (*value != '\0')
(void) SetImageProperty(image,exif_info[i].property,value,exception);
}
TIFFSetDirectory(tiff,directory);
#else
(void) tiff;
(void) image;
#endif
}
static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
{
*base=(tdata_t *) GetBlobStreamData((Image *) image);
if (*base != (tdata_t *) NULL)
*size=(toff_t) GetBlobSize((Image *) image);
if (*base != (tdata_t *) NULL)
return(1);
return(0);
}
static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
tsample_t sample,ssize_t row,tdata_t scanline)
{
int32
status;
(void) bits_per_sample;
status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
return(status);
}
static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
{
return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
}
static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
{
(void) image;
(void) base;
(void) size;
}
static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MagickPathExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MagickPathExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
(void) ConcatenateMagickString(message,".",MagickPathExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
**value;
unsigned char
buffer[BUFFER_SIZE+32];
unsigned short
length;
/* only support 8 bit for now */
if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
(samples_per_pixel != 4))
return(ReadGenericMethod);
/* Search for Adobe APP14 JPEG Marker */
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType) (value[0]);
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
(void) SeekBlob(image,position,SEEK_SET);
return(method);
}
static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
const StringInfo
*layer_info;
Image
*layers;
PSDInfo
info;
register ssize_t
i;
if (GetImageListLength(image) != 1)
return;
if ((image_info->number_scenes == 1) && (image_info->scene == 0))
return;
option=GetImageOption(image_info,"tiff:ignore-layers");
if (option != (const char * ) NULL)
return;
layer_info=GetImageProfile(image,"tiff:37724");
if (layer_info == (const StringInfo *) NULL)
return;
for (i=0; i < (ssize_t) layer_info->length-8; i++)
{
if (LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
continue;
i+=4;
if ((LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
break;
}
i+=4;
if (i >= (ssize_t) (layer_info->length-8))
return;
layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
(void) DeleteImageProfile(layers,"tiff:37724");
AttachBlob(layers->blob,layer_info->datum,layer_info->length);
SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
info.version=1;
info.columns=layers->columns;
info.rows=layers->rows;
info.channels=(unsigned short) layers->number_channels;
/* Setting the mode to a value that won't change the colorspace */
info.mode=10;
ReadPSDLayers(layers,image_info,&info,MagickFalse,exception);
DeleteImageFromList(&layers);
if (layers != (Image *) NULL)
{
SetImageArtifact(image,"tiff:has-layers","true");
AppendImageToList(&image,layers);
while (layers != (Image *) NULL)
{
SetImageArtifact(layers,"tiff:has-layers","true");
DetachBlob(layers->blob);
layers=GetNextImageInList(layers);
}
}
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point",
exception);
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black",
exception);
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white",
exception);
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette",exception);
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB",exception);
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)",
exception);
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception);
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK",exception);
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated",exception);
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown",exception);
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric",
exception));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb",exception);
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb",exception);
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace,exception);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace,exception);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace,exception);
TIFFGetProfiles(tiff,image,image_info->ping,exception);
TIFFGetProperties(tiff,image,exception);
option=GetImageOption(image_info,"tiff:exif-properties");
if (IsStringFalse(option) == MagickFalse) /* enabled by default */
TIFFGetEXIFProperties(tiff,image,exception);
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->resolution.x=x_resolution;
image->resolution.y=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);
image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MagickPathExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
&horizontal,&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MagickPathExtent,
"%dx%d",horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor,exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
TIFFClose(tiff);
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified",exception);
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->alpha_trait=BlendPixelTrait;
}
else
for (i=0; i < extra_samples; i++)
{
image->alpha_trait=BlendPixelTrait;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated",
exception);
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated",
exception);
}
}
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors,exception) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
value=(unsigned short) image->scene;
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
if (image->alpha_trait == UndefinedPixelTrait)
image->depth=GetImageDepth(image,exception);
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
goto next_tiff_frame;
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MagickPathExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MagickPathExtent,"%u",
(unsigned int) rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
}
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
if (image->alpha_trait != UndefinedPixelTrait)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)),q);
SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)),q);
SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)),q);
SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);
q+=GetPixelChannels(image);
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"ImageIsNotTiled");
}
(void) SetImageStorageClass(image,DirectClass,exception);
number_pixels=(MagickSizeType) columns*rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
tile_pixels=(uint32 *) AcquireQuantumMemory(columns,
rows*sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
register ssize_t
x;
register Quantum
*magick_restrict q,
*magick_restrict tile;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
x);
for (row=rows_remaining; row > 0; row--)
{
if (image->alpha_trait != UndefinedPixelTrait)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)),q);
p++;
q+=GetPixelChannels(image);
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
p++;
q+=GetPixelChannels(image);
}
p+=columns-columns_remaining;
q-=GetPixelChannels(image)*(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(uint32));
if (pixel_info == (MemoryInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
(uint32) image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
q+=GetPixelChannels(image)*(image->columns-1);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)),q);
p--;
q-=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image=DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTIFFImage() adds properties for the TIFF image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterTIFFImage method is:
%
% size_t RegisterTIFFImage(void)
%
*/
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
static TIFFExtendProc
tag_extender = (TIFFExtendProc) NULL;
static void TIFFIgnoreTags(TIFF *tiff)
{
char
*q;
const char
*p,
*tags;
Image
*image;
register ssize_t
i;
size_t
count;
TIFFFieldInfo
*ignore;
if (TIFFGetReadProc(tiff) != TIFFReadBlob)
return;
image=(Image *)TIFFClientdata(tiff);
tags=GetImageArtifact(image,"tiff:ignore-tags");
if (tags == (const char *) NULL)
return;
count=0;
p=tags;
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
(void) strtol(p,&q,10);
if (p == q)
return;
p=q;
count++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
if (count == 0)
return;
i=0;
p=tags;
ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
/* This also sets field_bit to 0 (FIELD_IGNORE) */
ResetMagickMemory(ignore,0,count*sizeof(*ignore));
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
p=q;
i++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
(void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
}
static void TIFFTagExtender(TIFF *tiff)
{
static const TIFFFieldInfo
TIFFExtensions[] =
{
{ 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "PhotoshopLayerData" },
{ 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "Microscope" }
};
TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
sizeof(*TIFFExtensions));
if (tag_extender != (TIFFExtendProc) NULL)
(*tag_extender)(tiff);
TIFFIgnoreTags(tiff);
}
#endif
ModuleExport size_t RegisterTIFFImage(void)
{
#define TIFFDescription "Tagged Image File Format"
char
version[MagickPathExtent];
MagickInfo
*entry;
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key == MagickFalse)
{
if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
error_handler=TIFFSetErrorHandler(TIFFErrors);
warning_handler=TIFFSetWarningHandler(TIFFWarnings);
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
tag_extender=TIFFSetTagExtender(TIFFTagExtender);
#endif
instantiate_key=MagickTrue;
}
UnlockSemaphoreInfo(tiff_semaphore);
*version='\0';
#if defined(TIFF_VERSION)
(void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION);
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
{
const char
*p;
register ssize_t
i;
p=TIFFGetVersion();
for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++)
version[i]=(*p++);
version[i]='\0';
}
#endif
entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
#endif
entry->flags|=CoderRawSupportFlag;
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->flags^=CoderUseExtensionFlag;
entry->format_type=ImplicitFormatType;
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WritePTIFImage;
#endif
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderUseExtensionFlag;
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription);
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags|=CoderStealthFlag;
entry->flags^=CoderUseExtensionFlag;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription);
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->magick=(IsImageFormatHandler *) IsTIFF;
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderUseExtensionFlag;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)");
#if defined(TIFF_VERSION_BIG)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->flags^=CoderUseExtensionFlag;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTIFFImage() removes format registrations made by the TIFF module
% from the list of supported formats.
%
% The format of the UnregisterTIFFImage method is:
%
% UnregisterTIFFImage(void)
%
*/
ModuleExport void UnregisterTIFFImage(void)
{
(void) UnregisterMagickInfo("TIFF64");
(void) UnregisterMagickInfo("TIFF");
(void) UnregisterMagickInfo("TIF");
(void) UnregisterMagickInfo("PTIF");
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key != MagickFalse)
{
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
(void) TIFFSetTagExtender(tag_extender);
#endif
if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) TIFFSetWarningHandler(warning_handler);
(void) TIFFSetErrorHandler(error_handler);
instantiate_key=MagickFalse;
}
UnlockSemaphoreInfo(tiff_semaphore);
RelinquishSemaphoreInfo(&tiff_semaphore);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
%
% The format of the WriteGROUP4Image method is:
%
% MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
% Image *image,ExceptionInfo *)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*huffman_image;
ImageInfo
*write_info;
int
unique_file;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count;
TIFF
*tiff;
toff_t
*byte_count,
strip_size;
unsigned char
*buffer;
/*
Write image as CCITT Group4 TIFF image to a temporary file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
huffman_image=CloneImage(image,0,0,MagickTrue,exception);
if (huffman_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
huffman_image->endian=MSBEndian;
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
filename);
return(MagickFalse);
}
(void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s",
filename);
(void) SetImageType(huffman_image,BilevelType,exception);
write_info=CloneImageInfo((ImageInfo *) NULL);
SetImageInfoFile(write_info,file);
(void) SetImageType(image,BilevelType,exception);
(void) SetImageDepth(image,1,exception);
write_info->compression=Group4Compression;
write_info->type=BilevelType;
(void) SetImageOption(write_info,"quantum:polarity","min-is-white");
status=WriteTIFFImage(write_info,huffman_image,exception);
(void) fflush(file);
write_info=DestroyImageInfo(write_info);
if (status == MagickFalse)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
tiff=TIFFOpen(filename,"rb");
if (tiff == (TIFF *) NULL)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
return(MagickFalse);
}
/*
Allocate raw strip buffer.
*/
if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
strip_size=byte_count[0];
for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
if (byte_count[i] > strip_size)
strip_size=byte_count[i];
buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image_info->filename);
}
/*
Compress runlength encoded to 2D Huffman pixels.
*/
for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
{
count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
if (WriteBlob(image,(size_t) count,buffer) != count)
status=MagickFalse;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
(void) CloseBlob(image);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P T I F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
% format.
%
% The format of the WritePTIFImage method is:
%
% MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception);
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution=next->resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2;
resolution.y/=2;
pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
if (pyramid_image == (Image *) NULL)
break;
pyramid_image->resolution=resolution;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
AppendImageToList(&images,pyramid_image);
}
}
images=GetFirstImageInList(images);
/*
Write pyramid-encoded TIFF image.
*/
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
(void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent);
(void) CopyMagickString(images->magick,"TIFF",MagickPathExtent);
status=WriteTIFFImage(write_info,images,exception);
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W r i t e T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTIFFImage() writes an image in the Tagged image file format.
%
% The format of the WriteTIFFImage method is:
%
% MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _TIFFInfo
{
RectangleInfo
tile_geometry;
unsigned char
*scanline,
*scanlines,
*pixels;
} TIFFInfo;
static void DestroyTIFFInfo(TIFFInfo *tiff_info)
{
assert(tiff_info != (TIFFInfo *) NULL);
if (tiff_info->scanlines != (unsigned char *) NULL)
tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
tiff_info->scanlines);
if (tiff_info->pixels != (unsigned char *) NULL)
tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
tiff_info->pixels);
}
static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(image,q)-0.5;
if (a < 0.0)
a+=1.0;
b=QuantumScale*GetPixelb(image,q)-0.5;
if (b < 0.0)
b+=1.0;
SetPixela(image,QuantumRange*a,q);
SetPixelb(image,QuantumRange*b,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
TIFF *tiff,TIFFInfo *tiff_info)
{
const char
*option;
MagickStatusType
flags;
uint32
tile_columns,
tile_rows;
assert(tiff_info != (TIFFInfo *) NULL);
(void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
option=GetImageOption(image_info,"tiff:tile-geometry");
if (option == (const char *) NULL)
return(MagickTrue);
flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
if ((flags & HeightValue) == 0)
tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
tile_columns=(uint32) tiff_info->tile_geometry.width;
tile_rows=(uint32) tiff_info->tile_geometry.height;
TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
(void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
(void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
tiff_info->tile_geometry.width=tile_columns;
tiff_info->tile_geometry.height=tile_rows;
tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
if ((tiff_info->scanlines == (unsigned char *) NULL) ||
(tiff_info->pixels == (unsigned char *) NULL))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
return(MagickTrue);
}
static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
tsample_t sample,Image *image)
{
int32
status;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
number_tiles,
tile_width;
ssize_t
bytes_per_pixel,
j,
k,
l;
if (TIFFIsTiled(tiff) == 0)
return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
/*
Fill scanlines to tile height.
*/
i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
(void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
(size_t) TIFFScanlineSize(tiff));
if (((size_t) (row % tiff_info->tile_geometry.height) !=
(tiff_info->tile_geometry.height-1)) &&
(row != (ssize_t) (image->rows-1)))
return(0);
/*
Write tile to TIFF image.
*/
status=0;
bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
number_tiles=(image->columns+tiff_info->tile_geometry.width)/
tiff_info->tile_geometry.width;
for (i=0; i < (ssize_t) number_tiles; i++)
{
tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
for (k=0; k < (ssize_t) tile_width; k++)
{
if (bytes_per_pixel == 0)
{
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)/8);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
*q++=(*p++);
continue;
}
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)*bytes_per_pixel);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
for (l=0; l < bytes_per_pixel; l++)
*q++=(*p++);
}
if ((i*tiff_info->tile_geometry.width) != image->columns)
status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
tiff_info->tile_geometry.width),(uint32) ((row/
tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
sample);
if (status < 0)
break;
}
return(status);
}
static void TIFFSetProfiles(TIFF *tiff,Image *image)
{
const char
*name;
const StringInfo
*profile;
if (image->profiles == (void *) NULL)
return;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (GetStringInfoLength(profile) == 0)
{
name=GetNextImageProfile(image);
continue;
}
#if defined(TIFFTAG_XMLPACKET)
if (LocaleCompare(name,"xmp") == 0)
(void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
#if defined(TIFFTAG_ICCPROFILE)
if (LocaleCompare(name,"icc") == 0)
(void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"iptc") == 0)
{
size_t
length;
StringInfo
*iptc_profile;
iptc_profile=CloneStringInfo(profile);
length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
0x03);
SetStringInfoLength(iptc_profile,length);
if (TIFFIsByteSwapped(tiff))
TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
(unsigned long) (length/4));
(void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
iptc_profile=DestroyStringInfo(iptc_profile);
}
#if defined(TIFFTAG_PHOTOSHOP)
if (LocaleCompare(name,"8bim") == 0)
(void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
GetStringInfoLength(profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"tiff:37724") == 0)
(void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
if (LocaleCompare(name,"tiff:34118") == 0)
(void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
ExceptionInfo *exception)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
const char
*value;
register ssize_t
i;
uint32
offset;
/*
Write EXIF properties.
*/
offset=0;
(void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
for (i=0; exif_info[i].tag != 0; i++)
{
value=GetImageProperty(image,exif_info[i].property,exception);
if (value == (const char *) NULL)
continue;
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
(void) TIFFSetField(tiff,exif_info[i].tag,value);
break;
}
case TIFF_SHORT:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_LONG:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
{
float
field;
field=StringToDouble(value,(char **) NULL);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
default:
break;
}
}
/* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
#else
(void) tiff;
(void) image;
#endif
}
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
length;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
scene=0;
debug=IsEventLogging();
(void) debug;
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type,exception);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType,exception);
(void) SetImageDepth(image,1,exception);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass,exception);
(void) SetImageDepth(image,8,exception);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
compression=NoCompression;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
compression=NoCompression;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass,exception);
(void) SetImageDepth(image,8,exception);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorAlphaType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) &&
(image->alpha_trait == UndefinedPixelTrait))
SetImageMonochrome(image,exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->alpha_trait != UndefinedPixelTrait)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor",exception);
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
if (image->colorspace == YCbCrColorspace)
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"TIFF: negative image positions unsupported","%s",image->filename);
if ((image->page.x > 0) && (image->resolution.x > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->resolution.x);
}
if ((image->page.y > 0) && (image->resolution.y > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->resolution.y);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image,exception);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image,exception);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) length;
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RedQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GreenQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
BlueQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->alpha_trait != UndefinedPixelTrait)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4783_0 |
crossvul-cpp_data_good_1560_0 | /*
* Copyright (c) 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <tcpdump-stdinc.h>
#include "interface.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = "[|wb]";
/* XXX need to add byte-swapping macros! */
/* XXX - you mean like the ones in "extract.h"? */
/*
* Largest packet size. Everything should fit within this space.
* For instance, multiline objects are sent piecewise.
*/
#define MAXFRAMESIZE 1024
/*
* Multiple drawing ops can be sent in one packet. Each one starts on a
* an even multiple of DOP_ALIGN bytes, which must be a power of two.
*/
#define DOP_ALIGN 4
#define DOP_ROUNDUP(x) ((((int)(x)) + (DOP_ALIGN - 1)) & ~(DOP_ALIGN - 1))
#define DOP_NEXT(d)\
((struct dophdr *)((u_char *)(d) + \
DOP_ROUNDUP(EXTRACT_16BITS(&(d)->dh_len) + sizeof(*(d)))))
/*
* Format of the whiteboard packet header.
* The transport level header.
*/
struct pkt_hdr {
uint32_t ph_src; /* site id of source */
uint32_t ph_ts; /* time stamp (for skew computation) */
uint16_t ph_version; /* version number */
u_char ph_type; /* message type */
u_char ph_flags; /* message flags */
};
/* Packet types */
#define PT_DRAWOP 0 /* drawing operation */
#define PT_ID 1 /* announcement packet */
#define PT_RREQ 2 /* repair request */
#define PT_RREP 3 /* repair reply */
#define PT_KILL 4 /* terminate participation */
#define PT_PREQ 5 /* page vector request */
#define PT_PREP 7 /* page vector reply */
#ifdef PF_USER
#undef PF_USER /* {Digital,Tru64} UNIX define this, alas */
#endif
/* flags */
#define PF_USER 0x01 /* hint that packet has interactive data */
#define PF_VIS 0x02 /* only visible ops wanted */
struct PageID {
uint32_t p_sid; /* session id of initiator */
uint32_t p_uid; /* page number */
};
struct dophdr {
uint32_t dh_ts; /* sender's timestamp */
uint16_t dh_len; /* body length */
u_char dh_flags;
u_char dh_type; /* body type */
/* body follows */
};
/*
* Drawing op sub-types.
*/
#define DT_RECT 2
#define DT_LINE 3
#define DT_ML 4
#define DT_DEL 5
#define DT_XFORM 6
#define DT_ELL 7
#define DT_CHAR 8
#define DT_STR 9
#define DT_NOP 10
#define DT_PSCODE 11
#define DT_PSCOMP 12
#define DT_REF 13
#define DT_SKIP 14
#define DT_HOLE 15
#define DT_MAXTYPE 15
/*
* A drawing operation.
*/
struct pkt_dop {
struct PageID pd_page; /* page that operations apply to */
uint32_t pd_sseq; /* start sequence number */
uint32_t pd_eseq; /* end sequence number */
/* drawing ops follow */
};
/*
* A repair request.
*/
struct pkt_rreq {
uint32_t pr_id; /* source id of drawops to be repaired */
struct PageID pr_page; /* page of drawops */
uint32_t pr_sseq; /* start seqno */
uint32_t pr_eseq; /* end seqno */
};
/*
* A repair reply.
*/
struct pkt_rrep {
uint32_t pr_id; /* original site id of ops */
struct pkt_dop pr_dop;
/* drawing ops follow */
};
struct id_off {
uint32_t id;
uint32_t off;
};
struct pgstate {
uint32_t slot;
struct PageID page;
uint16_t nid;
uint16_t rsvd;
/* seqptr's */
};
/*
* An announcement packet.
*/
struct pkt_id {
uint32_t pi_mslot;
struct PageID pi_mpage; /* current page */
struct pgstate pi_ps;
/* seqptr's */
/* null-terminated site name */
};
struct pkt_preq {
struct PageID pp_page;
uint32_t pp_low;
uint32_t pp_high;
};
struct pkt_prep {
uint32_t pp_n; /* size of pageid array */
/* pgstate's follow */
};
static int
wb_id(netdissect_options *ndo,
const struct pkt_id *id, u_int len)
{
int i;
const char *cp;
const struct id_off *io;
char c;
int nid;
ND_PRINT((ndo, " wb-id:"));
if (len < sizeof(*id) || !ND_TTEST(*id))
return (-1);
len -= sizeof(*id);
ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ",
EXTRACT_32BITS(&id->pi_ps.slot),
ipaddr_string(ndo, &id->pi_ps.page.p_sid),
EXTRACT_32BITS(&id->pi_ps.page.p_uid),
EXTRACT_32BITS(&id->pi_mslot),
ipaddr_string(ndo, &id->pi_mpage.p_sid),
EXTRACT_32BITS(&id->pi_mpage.p_uid)));
nid = EXTRACT_16BITS(&id->pi_ps.nid);
len -= sizeof(*io) * nid;
io = (struct id_off *)(id + 1);
cp = (char *)(io + nid);
if (ND_TTEST2(cp, len)) {
ND_PRINT((ndo, "\""));
fn_print(ndo, (u_char *)cp, (u_char *)cp + len);
ND_PRINT((ndo, "\""));
}
c = '<';
for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) {
ND_PRINT((ndo, "%c%s:%u",
c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off)));
c = ',';
}
if (i >= nid) {
ND_PRINT((ndo, ">"));
return (0);
}
return (-1);
}
static int
wb_rreq(netdissect_options *ndo,
const struct pkt_rreq *rreq, u_int len)
{
ND_PRINT((ndo, " wb-rreq:"));
if (len < sizeof(*rreq) || !ND_TTEST(*rreq))
return (-1);
ND_PRINT((ndo, " please repair %s %s:%u<%u:%u>",
ipaddr_string(ndo, &rreq->pr_id),
ipaddr_string(ndo, &rreq->pr_page.p_sid),
EXTRACT_32BITS(&rreq->pr_page.p_uid),
EXTRACT_32BITS(&rreq->pr_sseq),
EXTRACT_32BITS(&rreq->pr_eseq)));
return (0);
}
static int
wb_preq(netdissect_options *ndo,
const struct pkt_preq *preq, u_int len)
{
ND_PRINT((ndo, " wb-preq:"));
if (len < sizeof(*preq) || !ND_TTEST(*preq))
return (-1);
ND_PRINT((ndo, " need %u/%s:%u",
EXTRACT_32BITS(&preq->pp_low),
ipaddr_string(ndo, &preq->pp_page.p_sid),
EXTRACT_32BITS(&preq->pp_page.p_uid)));
return (0);
}
static int
wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
}
static const char *dopstr[] = {
"dop-0!",
"dop-1!",
"RECT",
"LINE",
"ML",
"DEL",
"XFORM",
"ELL",
"CHAR",
"STR",
"NOP",
"PSCODE",
"PSCOMP",
"REF",
"SKIP",
"HOLE",
};
static int
wb_dops(netdissect_options *ndo, const struct pkt_dop *dop,
uint32_t ss, uint32_t es)
{
const struct dophdr *dh = (const struct dophdr *)((const u_char *)dop + sizeof(*dop));
ND_PRINT((ndo, " <"));
for ( ; ss <= es; ++ss) {
int t;
if (!ND_TTEST(*dh)) {
ND_PRINT((ndo, "%s", tstr));
break;
}
t = dh->dh_type;
if (t > DT_MAXTYPE)
ND_PRINT((ndo, " dop-%d!", t));
else {
ND_PRINT((ndo, " %s", dopstr[t]));
if (t == DT_SKIP || t == DT_HOLE) {
uint32_t ts = EXTRACT_32BITS(&dh->dh_ts);
ND_PRINT((ndo, "%d", ts - ss + 1));
if (ss > ts || ts > es) {
ND_PRINT((ndo, "[|]"));
if (ts < ss)
return (0);
}
ss = ts;
}
}
dh = DOP_NEXT(dh);
}
ND_PRINT((ndo, " >"));
return (0);
}
static int
wb_rrep(netdissect_options *ndo,
const struct pkt_rrep *rrep, u_int len)
{
const struct pkt_dop *dop = &rrep->pr_dop;
ND_PRINT((ndo, " wb-rrep:"));
if (len < sizeof(*rrep) || !ND_TTEST(*rrep))
return (-1);
len -= sizeof(*rrep);
ND_PRINT((ndo, " for %s %s:%u<%u:%u>",
ipaddr_string(ndo, &rrep->pr_id),
ipaddr_string(ndo, &dop->pd_page.p_sid),
EXTRACT_32BITS(&dop->pd_page.p_uid),
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
if (ndo->ndo_vflag)
return (wb_dops(ndo, dop,
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
return (0);
}
static int
wb_drawop(netdissect_options *ndo,
const struct pkt_dop *dop, u_int len)
{
ND_PRINT((ndo, " wb-dop:"));
if (len < sizeof(*dop) || !ND_TTEST(*dop))
return (-1);
len -= sizeof(*dop);
ND_PRINT((ndo, " %s:%u<%u:%u>",
ipaddr_string(ndo, &dop->pd_page.p_sid),
EXTRACT_32BITS(&dop->pd_page.p_uid),
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
if (ndo->ndo_vflag)
return (wb_dops(ndo, dop,
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
return (0);
}
/*
* Print whiteboard multicast packets.
*/
void
wb_print(netdissect_options *ndo,
register const void *hdr, register u_int len)
{
register const struct pkt_hdr *ph;
ph = (const struct pkt_hdr *)hdr;
if (len < sizeof(*ph) || !ND_TTEST(*ph)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
len -= sizeof(*ph);
if (ph->ph_flags)
ND_PRINT((ndo, "*"));
switch (ph->ph_type) {
case PT_KILL:
ND_PRINT((ndo, " wb-kill"));
return;
case PT_ID:
if (wb_id(ndo, (struct pkt_id *)(ph + 1), len) >= 0)
return;
break;
case PT_RREQ:
if (wb_rreq(ndo, (struct pkt_rreq *)(ph + 1), len) >= 0)
return;
break;
case PT_RREP:
if (wb_rrep(ndo, (struct pkt_rrep *)(ph + 1), len) >= 0)
return;
break;
case PT_DRAWOP:
if (wb_drawop(ndo, (struct pkt_dop *)(ph + 1), len) >= 0)
return;
break;
case PT_PREQ:
if (wb_preq(ndo, (struct pkt_preq *)(ph + 1), len) >= 0)
return;
break;
case PT_PREP:
if (wb_prep(ndo, (struct pkt_prep *)(ph + 1), len) >= 0)
return;
break;
default:
ND_PRINT((ndo, " wb-%d!", ph->ph_type));
return;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1560_0 |
crossvul-cpp_data_good_2891_8 | /* procfs files for key database enumeration
*
* Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/errno.h>
#include "internal.h"
static int proc_keys_open(struct inode *inode, struct file *file);
static void *proc_keys_start(struct seq_file *p, loff_t *_pos);
static void *proc_keys_next(struct seq_file *p, void *v, loff_t *_pos);
static void proc_keys_stop(struct seq_file *p, void *v);
static int proc_keys_show(struct seq_file *m, void *v);
static const struct seq_operations proc_keys_ops = {
.start = proc_keys_start,
.next = proc_keys_next,
.stop = proc_keys_stop,
.show = proc_keys_show,
};
static const struct file_operations proc_keys_fops = {
.open = proc_keys_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int proc_key_users_open(struct inode *inode, struct file *file);
static void *proc_key_users_start(struct seq_file *p, loff_t *_pos);
static void *proc_key_users_next(struct seq_file *p, void *v, loff_t *_pos);
static void proc_key_users_stop(struct seq_file *p, void *v);
static int proc_key_users_show(struct seq_file *m, void *v);
static const struct seq_operations proc_key_users_ops = {
.start = proc_key_users_start,
.next = proc_key_users_next,
.stop = proc_key_users_stop,
.show = proc_key_users_show,
};
static const struct file_operations proc_key_users_fops = {
.open = proc_key_users_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
/*
* Declare the /proc files.
*/
static int __init key_proc_init(void)
{
struct proc_dir_entry *p;
p = proc_create("keys", 0, NULL, &proc_keys_fops);
if (!p)
panic("Cannot create /proc/keys\n");
p = proc_create("key-users", 0, NULL, &proc_key_users_fops);
if (!p)
panic("Cannot create /proc/key-users\n");
return 0;
}
__initcall(key_proc_init);
/*
* Implement "/proc/keys" to provide a list of the keys on the system that
* grant View permission to the caller.
*/
static struct rb_node *key_serial_next(struct seq_file *p, struct rb_node *n)
{
struct user_namespace *user_ns = seq_user_ns(p);
n = rb_next(n);
while (n) {
struct key *key = rb_entry(n, struct key, serial_node);
if (kuid_has_mapping(user_ns, key->user->uid))
break;
n = rb_next(n);
}
return n;
}
static int proc_keys_open(struct inode *inode, struct file *file)
{
return seq_open(file, &proc_keys_ops);
}
static struct key *find_ge_key(struct seq_file *p, key_serial_t id)
{
struct user_namespace *user_ns = seq_user_ns(p);
struct rb_node *n = key_serial_tree.rb_node;
struct key *minkey = NULL;
while (n) {
struct key *key = rb_entry(n, struct key, serial_node);
if (id < key->serial) {
if (!minkey || minkey->serial > key->serial)
minkey = key;
n = n->rb_left;
} else if (id > key->serial) {
n = n->rb_right;
} else {
minkey = key;
break;
}
key = NULL;
}
if (!minkey)
return NULL;
for (;;) {
if (kuid_has_mapping(user_ns, minkey->user->uid))
return minkey;
n = rb_next(&minkey->serial_node);
if (!n)
return NULL;
minkey = rb_entry(n, struct key, serial_node);
}
}
static void *proc_keys_start(struct seq_file *p, loff_t *_pos)
__acquires(key_serial_lock)
{
key_serial_t pos = *_pos;
struct key *key;
spin_lock(&key_serial_lock);
if (*_pos > INT_MAX)
return NULL;
key = find_ge_key(p, pos);
if (!key)
return NULL;
*_pos = key->serial;
return &key->serial_node;
}
static inline key_serial_t key_node_serial(struct rb_node *n)
{
struct key *key = rb_entry(n, struct key, serial_node);
return key->serial;
}
static void *proc_keys_next(struct seq_file *p, void *v, loff_t *_pos)
{
struct rb_node *n;
n = key_serial_next(p, v);
if (n)
*_pos = key_node_serial(n);
return n;
}
static void proc_keys_stop(struct seq_file *p, void *v)
__releases(key_serial_lock)
{
spin_unlock(&key_serial_lock);
}
static int proc_keys_show(struct seq_file *m, void *v)
{
struct rb_node *_p = v;
struct key *key = rb_entry(_p, struct key, serial_node);
struct timespec now;
unsigned long timo;
key_ref_t key_ref, skey_ref;
char xbuf[16];
short state;
int rc;
struct keyring_search_context ctx = {
.index_key.type = key->type,
.index_key.description = key->description,
.cred = m->file->f_cred,
.match_data.cmp = lookup_user_key_possessed,
.match_data.raw_data = key,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
key_ref = make_key_ref(key, 0);
/* determine if the key is possessed by this process (a test we can
* skip if the key does not indicate the possessor can view it
*/
if (key->perm & KEY_POS_VIEW) {
skey_ref = search_my_process_keyrings(&ctx);
if (!IS_ERR(skey_ref)) {
key_ref_put(skey_ref);
key_ref = make_key_ref(key, 1);
}
}
/* check whether the current task is allowed to view the key */
rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
if (rc < 0)
return 0;
now = current_kernel_time();
rcu_read_lock();
/* come up with a suitable timeout value */
if (key->expiry == 0) {
memcpy(xbuf, "perm", 5);
} else if (now.tv_sec >= key->expiry) {
memcpy(xbuf, "expd", 5);
} else {
timo = key->expiry - now.tv_sec;
if (timo < 60)
sprintf(xbuf, "%lus", timo);
else if (timo < 60*60)
sprintf(xbuf, "%lum", timo / 60);
else if (timo < 60*60*24)
sprintf(xbuf, "%luh", timo / (60*60));
else if (timo < 60*60*24*7)
sprintf(xbuf, "%lud", timo / (60*60*24));
else
sprintf(xbuf, "%luw", timo / (60*60*24*7));
}
state = key_read_state(key);
#define showflag(KEY, LETTER, FLAG) \
(test_bit(FLAG, &(KEY)->flags) ? LETTER : '-')
seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ",
key->serial,
state != KEY_IS_UNINSTANTIATED ? 'I' : '-',
showflag(key, 'R', KEY_FLAG_REVOKED),
showflag(key, 'D', KEY_FLAG_DEAD),
showflag(key, 'Q', KEY_FLAG_IN_QUOTA),
showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT),
state < 0 ? 'N' : '-',
showflag(key, 'i', KEY_FLAG_INVALIDATED),
refcount_read(&key->usage),
xbuf,
key->perm,
from_kuid_munged(seq_user_ns(m), key->uid),
from_kgid_munged(seq_user_ns(m), key->gid),
key->type->name);
#undef showflag
if (key->type->describe)
key->type->describe(key, m);
seq_putc(m, '\n');
rcu_read_unlock();
return 0;
}
static struct rb_node *__key_user_next(struct user_namespace *user_ns, struct rb_node *n)
{
while (n) {
struct key_user *user = rb_entry(n, struct key_user, node);
if (kuid_has_mapping(user_ns, user->uid))
break;
n = rb_next(n);
}
return n;
}
static struct rb_node *key_user_next(struct user_namespace *user_ns, struct rb_node *n)
{
return __key_user_next(user_ns, rb_next(n));
}
static struct rb_node *key_user_first(struct user_namespace *user_ns, struct rb_root *r)
{
struct rb_node *n = rb_first(r);
return __key_user_next(user_ns, n);
}
/*
* Implement "/proc/key-users" to provides a list of the key users and their
* quotas.
*/
static int proc_key_users_open(struct inode *inode, struct file *file)
{
return seq_open(file, &proc_key_users_ops);
}
static void *proc_key_users_start(struct seq_file *p, loff_t *_pos)
__acquires(key_user_lock)
{
struct rb_node *_p;
loff_t pos = *_pos;
spin_lock(&key_user_lock);
_p = key_user_first(seq_user_ns(p), &key_user_tree);
while (pos > 0 && _p) {
pos--;
_p = key_user_next(seq_user_ns(p), _p);
}
return _p;
}
static void *proc_key_users_next(struct seq_file *p, void *v, loff_t *_pos)
{
(*_pos)++;
return key_user_next(seq_user_ns(p), (struct rb_node *)v);
}
static void proc_key_users_stop(struct seq_file *p, void *v)
__releases(key_user_lock)
{
spin_unlock(&key_user_lock);
}
static int proc_key_users_show(struct seq_file *m, void *v)
{
struct rb_node *_p = v;
struct key_user *user = rb_entry(_p, struct key_user, node);
unsigned maxkeys = uid_eq(user->uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxkeys : key_quota_maxkeys;
unsigned maxbytes = uid_eq(user->uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxbytes : key_quota_maxbytes;
seq_printf(m, "%5u: %5d %d/%d %d/%d %d/%d\n",
from_kuid_munged(seq_user_ns(m), user->uid),
refcount_read(&user->usage),
atomic_read(&user->nkeys),
atomic_read(&user->nikeys),
user->qnkeys,
maxkeys,
user->qnbytes,
maxbytes);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_8 |
crossvul-cpp_data_bad_5315_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO FFFFF IIIII L EEEEE %
% P P R R O O F I L E %
% PPPP RRRR O O FFF I L EEE %
% P R R O O F I L E %
% P R R OOO F IIIII LLLLL EEEEE %
% %
% %
% MagickCore Image Profile Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/colorspace-private.h"
#include "magick/configure.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/hashmap.h"
#include "magick/image.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/option-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/splay-tree.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H)
#include <wchar.h>
#include <lcms/lcms2.h>
#else
#include <wchar.h>
#include "lcms2.h"
#endif
#endif
/*
Forward declarations
*/
static MagickBooleanType
SetImageProfileInternal(Image *,const char *,const StringInfo *,
const MagickBooleanType);
static void
WriteTo8BimProfile(Image *,const char*,const StringInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProfiles() clones one or more image profiles.
%
% The format of the CloneImageProfiles method is:
%
% MagickBooleanType CloneImageProfiles(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProfiles(Image *image,
const Image *clone_image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clone_image != (const Image *) NULL);
assert(clone_image->signature == MagickSignature);
image->color_profile.length=clone_image->color_profile.length;
image->color_profile.info=clone_image->color_profile.info;
image->iptc_profile.length=clone_image->iptc_profile.length;
image->iptc_profile.info=clone_image->iptc_profile.info;
if (clone_image->profiles != (void *) NULL)
{
if (image->profiles != (void *) NULL)
DestroyImageProfiles(image);
image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles,
(void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProfile() deletes a profile from the image by its name.
%
% The format of the DeleteImageProfile method is:
%
% MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return(MagickFalse);
if (LocaleCompare(name,"icc") == 0)
{
/*
Continue to support deprecated color profile for now.
*/
image->color_profile.length=0;
image->color_profile.info=(unsigned char *) NULL;
}
if (LocaleCompare(name,"iptc") == 0)
{
/*
Continue to support deprecated IPTC profile for now.
*/
image->iptc_profile.length=0;
image->iptc_profile.info=(unsigned char *) NULL;
}
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProfiles() releases memory associated with an image profile map.
%
% The format of the DestroyProfiles method is:
%
% void DestroyImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProfiles(Image *image)
{
if (image->profiles != (SplayTreeInfo *) NULL)
image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProfile() gets a profile associated with an image by name.
%
% The format of the GetImageProfile method is:
%
% const StringInfo *GetImageProfile(const Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport const StringInfo *GetImageProfile(const Image *image,
const char *name)
{
const StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProfile() gets the next profile name for an image.
%
% The format of the GetNextImageProfile method is:
%
% char *GetNextImageProfile(const Image *image)
%
% A description of each parameter follows:
%
% o hash_info: the hash info.
%
*/
MagickExport char *GetNextImageProfile(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((char *) NULL);
return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P r o f i l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProfileImage() associates, applies, or removes an ICM, IPTC, or generic
% profile with / to / from an image. If the profile is NULL, it is removed
% from the image otherwise added or applied. Use a name of '*' and a profile
% of NULL to remove all profiles from the image.
%
% ICC and ICM profiles are handled as follows: If the image does not have
% an associated color profile, the one you provide is associated with the
% image and the image pixels are not transformed. Otherwise, the colorspace
% transform defined by the existing and new profile are applied to the image
% pixels and the new profile is associated with the image.
%
% The format of the ProfileImage method is:
%
% MagickBooleanType ProfileImage(Image *image,const char *name,
% const void *datum,const size_t length,const MagickBooleanType clone)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: Name of profile to add or remove: ICC, IPTC, or generic profile.
%
% o datum: the profile data.
%
% o length: the length of the profile.
%
% o clone: should be MagickFalse.
%
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
static unsigned short **DestroyPixelThreadSet(unsigned short **pixels)
{
register ssize_t
i;
assert(pixels != (unsigned short **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (unsigned short *) NULL)
pixels[i]=(unsigned short *) RelinquishMagickMemory(pixels[i]);
pixels=(unsigned short **) RelinquishMagickMemory(pixels);
return(pixels);
}
static unsigned short **AcquirePixelThreadSet(const size_t columns,
const size_t channels)
{
register ssize_t
i;
unsigned short
**pixels;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(unsigned short **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (unsigned short **) NULL)
return((unsigned short **) NULL);
(void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(unsigned short *) AcquireQuantumMemory(columns,channels*
sizeof(**pixels));
if (pixels[i] == (unsigned short *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform)
{
register ssize_t
i;
assert(transform != (cmsHTRANSFORM *) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (transform[i] != (cmsHTRANSFORM) NULL)
cmsDeleteTransform(transform[i]);
transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform);
return(transform);
}
static cmsHTRANSFORM *AcquireTransformThreadSet(Image *image,
const cmsHPROFILE source_profile,const cmsUInt32Number source_type,
const cmsHPROFILE target_profile,const cmsUInt32Number target_type,
const int intent,const cmsUInt32Number flags)
{
cmsHTRANSFORM
*transform;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads,
sizeof(*transform));
if (transform == (cmsHTRANSFORM *) NULL)
return((cmsHTRANSFORM *) NULL);
(void) ResetMagickMemory(transform,0,number_threads*sizeof(*transform));
for (i=0; i < (ssize_t) number_threads; i++)
{
transform[i]=cmsCreateTransformTHR((cmsContext) image,source_profile,
source_type,target_profile,target_type,intent,flags);
if (transform[i] == (cmsHTRANSFORM) NULL)
return(DestroyTransformThreadSet(transform));
}
return(transform);
}
#endif
#if defined(MAGICKCORE_LCMS_DELEGATE)
static void LCMSExceptionHandler(cmsContext context,cmsUInt32Number severity,
const char *message)
{
Image
*image;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s",
severity,message != (char *) NULL ? message : "no message");
image=(Image *) context;
if (image != (Image *) NULL)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ImageWarning,"UnableToTransformColorspace","`%s'",image->filename);
}
#endif
static MagickBooleanType SetsRGBImageProfile(Image *image)
{
static unsigned char
sRGBProfile[] =
{
0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00,
0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a,
0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99,
0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67,
0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70,
0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c,
0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24,
0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14,
0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24,
0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14,
0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14,
0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14,
0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14,
0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14,
0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36,
0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76,
0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77,
0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39,
0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c,
0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31,
0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75,
0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77,
0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20,
0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66,
0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d,
0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20,
0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57,
0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65,
0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20,
0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e,
0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61,
0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43,
0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c,
0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2,
0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d,
0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0,
0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87,
0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4,
0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19,
0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54,
0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90,
0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb,
0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d,
0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59,
0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1,
0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14,
0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84,
0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00,
0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a,
0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20,
0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4,
0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77,
0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37,
0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07,
0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5,
0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2,
0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf,
0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc,
0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9,
0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26,
0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64,
0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3,
0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13,
0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84,
0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06,
0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b,
0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41,
0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa,
0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5,
0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3,
0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94,
0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98,
0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf,
0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda,
0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18,
0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b,
0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1,
0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c,
0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb,
0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f,
0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37,
0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05,
0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8,
0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0,
0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee,
0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12,
0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b,
0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a,
0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00,
0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c,
0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f,
0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8,
0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78,
0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f,
0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d,
0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43,
0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60,
0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95,
0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1,
0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46,
0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2,
0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57,
0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04,
0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca,
0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8,
0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f,
0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf,
0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8,
0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a,
0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75,
0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea,
0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79,
0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21,
0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3,
0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf,
0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5,
0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6,
0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1,
0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36,
0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96,
0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11,
0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7,
0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57,
0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
};
StringInfo
*profile;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (GetImageProfile(image,"icc") != (const StringInfo *) NULL)
return(MagickFalse);
profile=AcquireStringInfo(sizeof(sRGBProfile));
SetStringInfoDatum(profile,sRGBProfile);
status=SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
return(status);
}
MagickExport MagickBooleanType ProfileImage(Image *image,const char *name,
const void *datum,const size_t length,
const MagickBooleanType magick_unused(clone))
{
#define ProfileImageTag "Profile/Image"
#define ThrowProfileException(severity,tag,context) \
{ \
if (source_profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(source_profile); \
if (target_profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(target_profile); \
ThrowBinaryException(severity,tag,context); \
}
MagickBooleanType
status;
StringInfo
*profile;
magick_unreferenced(clone);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(name != (const char *) NULL);
if ((datum == (const void *) NULL) || (length == 0))
{
char
*next;
/*
Delete image profile(s).
*/
ResetImageProfileIterator(image);
for (next=GetNextImageProfile(image); next != (const char *) NULL; )
{
if (IsOptionMember(next,name) != MagickFalse)
{
(void) DeleteImageProfile(image,next);
ResetImageProfileIterator(image);
}
next=GetNextImageProfile(image);
}
return(MagickTrue);
}
/*
Add a ICC, IPTC, or generic profile to the image.
*/
status=MagickTrue;
profile=AcquireStringInfo((size_t) length);
SetStringInfoDatum(profile,(unsigned char *) datum);
if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0))
status=SetImageProfile(image,name,profile);
else
{
const StringInfo
*icc_profile;
icc_profile=GetImageProfile(image,"icc");
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
const char
*value;
value=GetImageProperty(image,"exif:ColorSpace");
(void) value;
if (LocaleCompare(value,"1") != 0)
(void) SetsRGBImageProfile(image);
value=GetImageProperty(image,"exif:InteroperabilityIndex");
if (LocaleCompare(value,"R98.") != 0)
(void) SetsRGBImageProfile(image);
/* Future.
value=GetImageProperty(image,"exif:InteroperabilityIndex");
if (LocaleCompare(value,"R03.") != 0)
(void) SetAdobeRGB1998ImageProfile(image);
*/
icc_profile=GetImageProfile(image,"icc");
}
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
profile=DestroyStringInfo(profile);
return(MagickTrue);
}
#if !defined(MAGICKCORE_LCMS_DELEGATE)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (LCMS)",
image->filename);
#else
{
cmsHPROFILE
source_profile;
/*
Transform pixel colors as defined by the color profiles.
*/
cmsSetLogErrorHandler(LCMSExceptionHandler);
source_profile=cmsOpenProfileFromMemTHR((cmsContext) image,
GetStringInfoDatum(profile),(cmsUInt32Number)
GetStringInfoLength(profile));
if (source_profile == (cmsHPROFILE) NULL)
ThrowBinaryException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) &&
(icc_profile == (StringInfo *) NULL))
status=SetImageProfile(image,name,profile);
else
{
CacheView
*image_view;
ColorspaceType
source_colorspace,
target_colorspace;
cmsColorSpaceSignature
signature;
cmsHPROFILE
target_profile;
cmsHTRANSFORM
*magick_restrict transform;
cmsUInt32Number
flags,
source_type,
target_type;
ExceptionInfo
*exception;
int
intent;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
source_channels,
target_channels;
ssize_t
y;
unsigned short
**magick_restrict source_pixels,
**magick_restrict target_pixels;
exception=(&image->exception);
target_profile=(cmsHPROFILE) NULL;
if (icc_profile != (StringInfo *) NULL)
{
target_profile=source_profile;
source_profile=cmsOpenProfileFromMemTHR((cmsContext) image,
GetStringInfoDatum(icc_profile),(cmsUInt32Number)
GetStringInfoLength(icc_profile));
if (source_profile == (cmsHPROFILE) NULL)
ThrowProfileException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
switch (cmsGetColorSpace(source_profile))
{
case cmsSigCmykData:
{
source_colorspace=CMYKColorspace;
source_type=(cmsUInt32Number) TYPE_CMYK_16;
source_channels=4;
break;
}
case cmsSigGrayData:
{
source_colorspace=GRAYColorspace;
source_type=(cmsUInt32Number) TYPE_GRAY_16;
source_channels=1;
break;
}
case cmsSigLabData:
{
source_colorspace=LabColorspace;
source_type=(cmsUInt32Number) TYPE_Lab_16;
source_channels=3;
break;
}
case cmsSigLuvData:
{
source_colorspace=YUVColorspace;
source_type=(cmsUInt32Number) TYPE_YUV_16;
source_channels=3;
break;
}
case cmsSigRgbData:
{
source_colorspace=sRGBColorspace;
source_type=(cmsUInt32Number) TYPE_RGB_16;
source_channels=3;
break;
}
case cmsSigXYZData:
{
source_colorspace=XYZColorspace;
source_type=(cmsUInt32Number) TYPE_XYZ_16;
source_channels=3;
break;
}
case cmsSigYCbCrData:
{
source_colorspace=YCbCrColorspace;
source_type=(cmsUInt32Number) TYPE_YCbCr_16;
source_channels=3;
break;
}
default:
{
source_colorspace=UndefinedColorspace;
source_type=(cmsUInt32Number) TYPE_RGB_16;
source_channels=3;
break;
}
}
signature=cmsGetPCS(source_profile);
if (target_profile != (cmsHPROFILE) NULL)
signature=cmsGetColorSpace(target_profile);
switch (signature)
{
case cmsSigCmykData:
{
target_colorspace=CMYKColorspace;
target_type=(cmsUInt32Number) TYPE_CMYK_16;
target_channels=4;
break;
}
case cmsSigLabData:
{
target_colorspace=LabColorspace;
target_type=(cmsUInt32Number) TYPE_Lab_16;
target_channels=3;
break;
}
case cmsSigGrayData:
{
target_colorspace=GRAYColorspace;
target_type=(cmsUInt32Number) TYPE_GRAY_16;
target_channels=1;
break;
}
case cmsSigLuvData:
{
target_colorspace=YUVColorspace;
target_type=(cmsUInt32Number) TYPE_YUV_16;
target_channels=3;
break;
}
case cmsSigRgbData:
{
target_colorspace=sRGBColorspace;
target_type=(cmsUInt32Number) TYPE_RGB_16;
target_channels=3;
break;
}
case cmsSigXYZData:
{
target_colorspace=XYZColorspace;
target_type=(cmsUInt32Number) TYPE_XYZ_16;
target_channels=3;
break;
}
case cmsSigYCbCrData:
{
target_colorspace=YCbCrColorspace;
target_type=(cmsUInt32Number) TYPE_YCbCr_16;
target_channels=3;
break;
}
default:
{
target_colorspace=UndefinedColorspace;
target_type=(cmsUInt32Number) TYPE_RGB_16;
target_channels=3;
break;
}
}
if ((source_colorspace == UndefinedColorspace) ||
(target_colorspace == UndefinedColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == GRAYColorspace) &&
(SetImageGray(image,exception) == MagickFalse))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == CMYKColorspace) &&
(image->colorspace != CMYKColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == XYZColorspace) &&
(image->colorspace != XYZColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == YCbCrColorspace) &&
(image->colorspace != YCbCrColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace != CMYKColorspace) &&
(source_colorspace != GRAYColorspace) &&
(source_colorspace != LabColorspace) &&
(source_colorspace != XYZColorspace) &&
(source_colorspace != YCbCrColorspace) &&
(IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
switch (image->rendering_intent)
{
case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break;
case PerceptualIntent: intent=INTENT_PERCEPTUAL; break;
case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break;
case SaturationIntent: intent=INTENT_SATURATION; break;
default: intent=INTENT_PERCEPTUAL; break;
}
flags=cmsFLAGS_HIGHRESPRECALC;
#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION)
if (image->black_point_compensation != MagickFalse)
flags|=cmsFLAGS_BLACKPOINTCOMPENSATION;
#endif
transform=AcquireTransformThreadSet(image,source_profile,
source_type,target_profile,target_type,intent,flags);
if (transform == (cmsHTRANSFORM *) NULL)
ThrowProfileException(ImageError,"UnableToCreateColorTransform",
name);
/*
Transform image as dictated by the source & target image profiles.
*/
source_pixels=AcquirePixelThreadSet(image->columns,source_channels);
target_pixels=AcquirePixelThreadSet(image->columns,target_channels);
if ((source_pixels == (unsigned short **) NULL) ||
(target_pixels == (unsigned short **) NULL))
{
transform=DestroyTransformThreadSet(transform);
ThrowProfileException(ResourceLimitError,
"MemoryAllocationFailed",image->filename);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
target_pixels=DestroyPixelThreadSet(target_pixels);
source_pixels=DestroyPixelThreadSet(source_pixels);
transform=DestroyTransformThreadSet(transform);
if (source_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(source_profile);
if (target_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_profile);
return(MagickFalse);
}
if (target_colorspace == CMYKColorspace)
(void) SetImageColorspace(image,target_colorspace);
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
register unsigned short
*p;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
p=source_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
*p++=ScaleQuantumToShort(GetPixelRed(q));
if (source_channels > 1)
{
*p++=ScaleQuantumToShort(GetPixelGreen(q));
*p++=ScaleQuantumToShort(GetPixelBlue(q));
}
if (source_channels > 3)
*p++=ScaleQuantumToShort(GetPixelIndex(indexes+x));
q++;
}
cmsDoTransform(transform[id],source_pixels[id],target_pixels[id],
(unsigned int) image->columns);
p=target_pixels[id];
q-=image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum(*p));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
p++;
if (target_channels > 1)
{
SetPixelGreen(q,ScaleShortToQuantum(*p));
p++;
SetPixelBlue(q,ScaleShortToQuantum(*p));
p++;
}
if (target_channels > 3)
{
SetPixelIndex(indexes+x,ScaleShortToQuantum(*p));
p++;
}
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ProfileImage)
#endif
proceed=SetImageProgress(image,ProfileImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) SetImageColorspace(image,target_colorspace);
switch (signature)
{
case cmsSigRgbData:
{
image->type=image->matte == MagickFalse ? TrueColorType :
TrueColorMatteType;
break;
}
case cmsSigCmykData:
{
image->type=image->matte == MagickFalse ? ColorSeparationType :
ColorSeparationMatteType;
break;
}
case cmsSigGrayData:
{
image->type=image->matte == MagickFalse ? GrayscaleType :
GrayscaleMatteType;
break;
}
default:
break;
}
target_pixels=DestroyPixelThreadSet(target_pixels);
source_pixels=DestroyPixelThreadSet(source_pixels);
transform=DestroyTransformThreadSet(transform);
if (cmsGetDeviceClass(source_profile) != cmsSigLinkClass)
status=SetImageProfile(image,name,profile);
if (target_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_profile);
}
(void) cmsCloseProfile(source_profile);
}
#endif
}
profile=DestroyStringInfo(profile);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProfile() removes a named profile from the image and returns its
% value.
%
% The format of the RemoveImageProfile method is:
%
% void *RemoveImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name)
{
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
if (LocaleCompare(name,"icc") == 0)
{
/*
Continue to support deprecated color profile for now.
*/
image->color_profile.length=0;
image->color_profile.info=(unsigned char *) NULL;
}
if (LocaleCompare(name,"iptc") == 0)
{
/*
Continue to support deprecated IPTC profile for now.
*/
image->iptc_profile.length=0;
image->iptc_profile.info=(unsigned char *) NULL;
}
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t P r o f i l e I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImageProfileIterator() resets the image profile iterator. Use it in
% conjunction with GetNextImageProfile() to iterate over all the profiles
% associated with an image.
%
% The format of the ResetImageProfileIterator method is:
%
% ResetImageProfileIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImageProfileIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProfile() adds a named profile to the image. If a profile with the
% same name already exists, it is replaced. This method differs from the
% ProfileImage() method in that it does not apply CMS color profiles.
%
% The format of the SetImageProfile method is:
%
% MagickBooleanType SetImageProfile(Image *image,const char *name,
% const StringInfo *profile)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name, for example icc, exif, and 8bim (8bim is the
% Photoshop wrapper for iptc profiles).
%
% o profile: A StringInfo structure that contains the named profile.
%
*/
static void *DestroyProfile(void *profile)
{
return((void *) DestroyStringInfo((StringInfo *) profile));
}
static inline const unsigned char *ReadResourceByte(const unsigned char *p,
unsigned char *quantum)
{
*quantum=(*p++);
return(p);
}
static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(size_t) (*p++ << 24);
*quantum|=(size_t) (*p++ << 16);
*quantum|=(size_t) (*p++ << 8);
*quantum|=(size_t) (*p++ << 0);
return(p);
}
static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++ << 8);
*quantum|=(unsigned short) (*p++ << 0);
return(p);
}
static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) (quantum >> 24);
buffer[1]=(unsigned char) (quantum >> 16);
buffer[2]=(unsigned char) (quantum >> 8);
buffer[3]=(unsigned char) quantum;
(void) CopyMagickMemory(p,buffer,4);
}
static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((p > (datum+length-count)) || (count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
(void) WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int) profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
static void GetProfilesFromResourceBlock(Image *image,
const StringInfo *resource_block)
{
const unsigned char
*datum;
register const unsigned char
*p;
size_t
length;
ssize_t
count;
StringInfo
*profile;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id;
datum=GetStringInfoDatum(resource_block);
length=GetStringInfoLength(resource_block);
for (p=datum; p < (datum+length-16); )
{
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((p > (datum+length-count)) || (count > (ssize_t) length) ||
(count < 0))
break;
switch (id)
{
case 0x03ed:
{
unsigned int
resolution;
unsigned short
units;
/*
Resolution.
*/
p=ReadResourceLong(p,&resolution);
image->x_resolution=((double) resolution)/65536.0;
p=ReadResourceShort(p,&units)+2;
p=ReadResourceLong(p,&resolution)+4;
image->y_resolution=((double) resolution)/65536.0;
/*
Values are always stored as pixels per inch.
*/
if ((ResolutionType) units != PixelsPerCentimeterResolution)
image->units=PixelsPerInchResolution;
else
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution/=2.54;
image->y_resolution/=2.54;
}
break;
}
case 0x0404:
{
/*
IPTC Profile
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"iptc",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x040c:
{
/*
Thumbnail.
*/
p+=count;
break;
}
case 0x040f:
{
/*
ICC Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"icc",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0422:
{
/*
EXIF Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"exif",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0424:
{
/*
XMP Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"xmp",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType SetImageProfileInternal(Image *image,const char *name,
const StringInfo *profile,const MagickBooleanType recursive)
{
char
key[MaxTextExtent],
property[MaxTextExtent];
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
DestroyProfile);
(void) CopyMagickString(key,name,MaxTextExtent);
LocaleLower(key);
status=AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString(key),CloneStringInfo(profile));
if ((status != MagickFalse) &&
((LocaleCompare(name,"icc") == 0) || (LocaleCompare(name,"icm") == 0)))
{
const StringInfo
*icc_profile;
/*
Continue to support deprecated color profile member.
*/
icc_profile=GetImageProfile(image,name);
if (icc_profile != (const StringInfo *) NULL)
{
image->color_profile.length=GetStringInfoLength(icc_profile);
image->color_profile.info=GetStringInfoDatum(icc_profile);
}
}
if ((status != MagickFalse) &&
((LocaleCompare(name,"iptc") == 0) || (LocaleCompare(name,"8bim") == 0)))
{
const StringInfo
*iptc_profile;
/*
Continue to support deprecated IPTC profile member.
*/
iptc_profile=GetImageProfile(image,name);
if (iptc_profile != (const StringInfo *) NULL)
{
image->iptc_profile.length=GetStringInfoLength(iptc_profile);
image->iptc_profile.info=GetStringInfoDatum(iptc_profile);
}
}
if (status != MagickFalse)
{
if (LocaleCompare(name,"8bim") == 0)
GetProfilesFromResourceBlock(image,profile);
else if (recursive == MagickFalse)
WriteTo8BimProfile(image,name,profile);
}
/*
Inject profile into image properties.
*/
(void) FormatLocaleString(property,MaxTextExtent,"%s:*",name);
(void) GetImageProperty(image,property);
return(status);
}
MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name,
const StringInfo *profile)
{
return(SetImageProfileInternal(image,name,profile,MagickFalse));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageProfiles() synchronizes image properties with the image profiles.
% Currently we only support updating the EXIF resolution and orientation.
%
% The format of the SyncImageProfiles method is:
%
% MagickBooleanType SyncImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static inline int ReadProfileByte(unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline unsigned short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
return((unsigned short) (value & 0xffff));
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
return((unsigned short) (value & 0xffff));
}
static inline unsigned int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
return((unsigned int) (value & 0xffffffff));
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
return((unsigned int) (value & 0xffffffff));
}
static inline unsigned int ReadProfileMSBLong(unsigned char **p,size_t *length)
{
unsigned int
value;
if (*length < 4)
return(0);
value=ReadProfileLong(MSBEndian,*p);
(*length)-=4;
*p+=4;
return(value);
}
static inline unsigned short ReadProfileMSBShort(unsigned char **p,
size_t *length)
{
unsigned short
value;
if (*length < 2)
return(0);
value=ReadProfileShort(MSBEndian,*p);
(*length)-=2;
*p+=2;
return(value);
}
static inline void WriteProfileLong(const EndianType endian,
const size_t value,unsigned char *p)
{
unsigned char
buffer[4];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
(void) CopyMagickMemory(p,buffer,4);
return;
}
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
(void) CopyMagickMemory(p,buffer,4);
}
static void WriteProfileShort(const EndianType endian,
const unsigned short value,unsigned char *p)
{
unsigned char
buffer[2];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
(void) CopyMagickMemory(p,buffer,2);
return;
}
buffer[0]=(unsigned char) (value >> 8);
buffer[1]=(unsigned char) value;
(void) CopyMagickMemory(p,buffer,2);
}
static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile)
{
size_t
length;
ssize_t
count;
unsigned char
*p;
unsigned short
id;
length=GetStringInfoLength(profile);
p=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadProfileByte(&p,&length) != 0x38)
continue;
if (ReadProfileByte(&p,&length) != 0x42)
continue;
if (ReadProfileByte(&p,&length) != 0x49)
continue;
if (ReadProfileByte(&p,&length) != 0x4D)
continue;
if (length < 7)
return(MagickFalse);
id=ReadProfileMSBShort(&p,&length);
count=(ssize_t) ReadProfileByte(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
p+=count;
if ((*p & 0x01) == 0)
(void) ReadProfileByte(&p,&length);
count=(ssize_t) ReadProfileMSBLong(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
if ((id == 0x3ED) && (count == 16))
{
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->x_resolution*2.54*
65536.0),p);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->x_resolution*
65536.0),p);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4);
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->y_resolution*2.54*
65536.0),p+8);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->y_resolution*
65536.0),p+8);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12);
}
p+=count;
length-=count;
}
return(MagickTrue);
}
static MagickBooleanType SyncExifProfile(Image *image, StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
SplayTreeInfo
*exif_resources;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ((int) ReadProfileLong(endian,exif+4));
if ((offset < 0) || ((size_t) offset >= length))
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
components,
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format-1) >= EXIF_NUM_FORMATS)
break;
components=(ssize_t) ((int) ReadProfileLong(endian,q+4));
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
ssize_t
offset;
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ((int) ReadProfileLong(endian,q+8));
if ((ssize_t) (offset+number_bytes) < offset)
continue; /* prevent overflow */
if ((size_t) (offset+number_bytes) > length)
continue;
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->x_resolution+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->y_resolution+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
ssize_t
offset;
offset=(ssize_t) ((int) ReadProfileLong(endian,p));
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ((int) ReadProfileLong(endian,directory+2+(12*
number_entries)));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageProfiles(Image *image)
{
MagickBooleanType
status;
StringInfo
*profile;
status=MagickTrue;
profile=(StringInfo *) GetImageProfile(image,"8BIM");
if (profile != (StringInfo *) NULL)
if (Sync8BimProfile(image,profile) == MagickFalse)
status=MagickFalse;
profile=(StringInfo *) GetImageProfile(image,"EXIF");
if (profile != (StringInfo *) NULL)
if (SyncExifProfile(image,profile) == MagickFalse)
status=MagickFalse;
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5315_0 |
crossvul-cpp_data_good_5523_1 | /*
* Copyright 1999-2006, Gisle Aas.
*
* This library is free software; you can redistribute it and/or
* modify it under the same terms as Perl itself.
*/
#ifndef EXTERN
#define EXTERN extern
#endif
EXTERN SV*
sv_lower(pTHX_ SV* sv)
{
STRLEN len;
char *s = SvPV_force(sv, len);
for (; len--; s++)
*s = toLOWER(*s);
return sv;
}
EXTERN int
strnEQx(const char* s1, const char* s2, STRLEN n, int ignore_case)
{
while (n--) {
if (ignore_case) {
if (toLOWER(*s1) != toLOWER(*s2))
return 0;
}
else {
if (*s1 != *s2)
return 0;
}
s1++;
s2++;
}
return 1;
}
static void
grow_gap(pTHX_ SV* sv, STRLEN grow, char** t, char** s, char** e)
{
/*
SvPVX ---> AAAAAA...BBBBBB
^ ^ ^
t s e
*/
STRLEN t_offset = *t - SvPVX(sv);
STRLEN s_offset = *s - SvPVX(sv);
STRLEN e_offset = *e - SvPVX(sv);
SvGROW(sv, e_offset + grow + 1);
*t = SvPVX(sv) + t_offset;
*s = SvPVX(sv) + s_offset;
*e = SvPVX(sv) + e_offset;
Move(*s, *s+grow, *e - *s, char);
*s += grow;
*e += grow;
}
EXTERN SV*
decode_entities(pTHX_ SV* sv, HV* entity2char, bool expand_prefix)
{
STRLEN len;
char *s = SvPV_force(sv, len);
char *t = s;
char *end = s + len;
char *ent_start;
char *repl;
STRLEN repl_len;
#ifdef UNICODE_HTML_PARSER
char buf[UTF8_MAXLEN];
int repl_utf8;
int high_surrogate = 0;
#else
char buf[1];
#endif
#if defined(__GNUC__) && defined(UNICODE_HTML_PARSER)
/* gcc -Wall reports this variable as possibly used uninitialized */
repl_utf8 = 0;
#endif
while (s < end) {
assert(t <= s);
if ((*t++ = *s++) != '&')
continue;
ent_start = s;
repl = 0;
if (s < end && *s == '#') {
UV num = 0;
UV prev = 0;
int ok = 0;
s++;
if (s < end && (*s == 'x' || *s == 'X')) {
s++;
while (s < end) {
char *tmp = strchr(PL_hexdigit, *s);
if (!tmp)
break;
num = num << 4 | ((tmp - PL_hexdigit) & 15);
if (prev && num <= prev) {
/* overflow */
ok = 0;
break;
}
prev = num;
s++;
ok = 1;
}
}
else {
while (s < end && isDIGIT(*s)) {
num = num * 10 + (*s - '0');
if (prev && num < prev) {
/* overflow */
ok = 0;
break;
}
prev = num;
s++;
ok = 1;
}
}
if (ok) {
#ifdef UNICODE_HTML_PARSER
if (!SvUTF8(sv) && num <= 255) {
buf[0] = (char) num;
repl = buf;
repl_len = 1;
repl_utf8 = 0;
}
else {
char *tmp;
if ((num & 0xFFFFFC00) == 0xDC00) { /* low-surrogate */
if (high_surrogate != 0) {
t -= 3; /* Back up past 0xFFFD */
num = ((high_surrogate - 0xD800) << 10) +
(num - 0xDC00) + 0x10000;
high_surrogate = 0;
} else {
num = 0xFFFD;
}
}
else if ((num & 0xFFFFFC00) == 0xD800) { /* high-surrogate */
high_surrogate = num;
num = 0xFFFD;
}
else {
high_surrogate = 0;
/* otherwise invalid? */
if ((num >= 0xFDD0 && num <= 0xFDEF) ||
((num & 0xFFFE) == 0xFFFE) ||
num > 0x10FFFF)
{
num = 0xFFFD;
}
}
tmp = (char*)uvuni_to_utf8((U8*)buf, num);
repl = buf;
repl_len = tmp - buf;
repl_utf8 = 1;
}
#else
if (num <= 255) {
buf[0] = (char) num & 0xFF;
repl = buf;
repl_len = 1;
}
#endif
}
}
else {
char *ent_name = s;
while (s < end && isALNUM(*s))
s++;
if (ent_name != s && entity2char) {
SV** svp;
if ( (svp = hv_fetch(entity2char, ent_name, s - ent_name, 0)) ||
(*s == ';' && (svp = hv_fetch(entity2char, ent_name, s - ent_name + 1, 0)))
)
{
repl = SvPV(*svp, repl_len);
#ifdef UNICODE_HTML_PARSER
repl_utf8 = SvUTF8(*svp);
#endif
}
else if (expand_prefix) {
char *ss = s - 1;
while (ss > ent_name) {
svp = hv_fetch(entity2char, ent_name, ss - ent_name, 0);
if (svp) {
repl = SvPV(*svp, repl_len);
#ifdef UNICODE_HTML_PARSER
repl_utf8 = SvUTF8(*svp);
#endif
s = ss;
break;
}
ss--;
}
}
}
#ifdef UNICODE_HTML_PARSER
high_surrogate = 0;
#endif
}
if (repl) {
char *repl_allocated = 0;
if (s < end && *s == ';')
s++;
t--; /* '&' already copied, undo it */
#ifdef UNICODE_HTML_PARSER
if (*s != '&') {
high_surrogate = 0;
}
if (!SvUTF8(sv) && repl_utf8) {
/* need to upgrade sv before we continue */
STRLEN before_gap_len = t - SvPVX(sv);
char *before_gap = (char*)bytes_to_utf8((U8*)SvPVX(sv), &before_gap_len);
STRLEN after_gap_len = end - s;
char *after_gap = (char*)bytes_to_utf8((U8*)s, &after_gap_len);
sv_setpvn(sv, before_gap, before_gap_len);
sv_catpvn(sv, after_gap, after_gap_len);
SvUTF8_on(sv);
Safefree(before_gap);
Safefree(after_gap);
s = t = SvPVX(sv) + before_gap_len;
end = SvPVX(sv) + before_gap_len + after_gap_len;
}
else if (SvUTF8(sv) && !repl_utf8) {
repl = (char*)bytes_to_utf8((U8*)repl, &repl_len);
repl_allocated = repl;
}
#endif
if (t + repl_len > s) {
/* need to grow the string */
grow_gap(aTHX_ sv, repl_len - (s - t), &t, &s, &end);
}
/* copy replacement string into string */
while (repl_len--)
*t++ = *repl++;
if (repl_allocated)
Safefree(repl_allocated);
}
else {
while (ent_start < s)
*t++ = *ent_start++;
}
}
*t = '\0';
SvCUR_set(sv, t - SvPVX(sv));
return sv;
}
#ifdef UNICODE_HTML_PARSER
static bool
has_hibit(char *s, char *e)
{
while (s < e) {
U8 ch = *s++;
if (!UTF8_IS_INVARIANT(ch)) {
return 1;
}
}
return 0;
}
EXTERN bool
probably_utf8_chunk(pTHX_ char *s, STRLEN len)
{
char *e = s + len;
STRLEN clen;
/* ignore partial utf8 char at end of buffer */
while (s < e && UTF8_IS_CONTINUATION((U8)*(e - 1)))
e--;
if (s < e && UTF8_IS_START((U8)*(e - 1)))
e--;
clen = len - (e - s);
if (clen && UTF8SKIP(e) == clen) {
/* all promised continuation bytes are present */
e = s + len;
}
if (!has_hibit(s, e))
return 0;
return is_utf8_string((U8*)s, e - s);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5523_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.