<commit_before>/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "modsecurity/audit_log.h"

#include <stddef.h>
#include <stdio.h>
#include <ctype.h>

#include <fstream>

#include "modsecurity/rule_message.h"
#include "src/audit_log/writer/https.h"
#include "src/audit_log/writer/parallel.h"
#include "src/audit_log/writer/serial.h"
#include "src/audit_log/writer/writer.h"
#include "src/utils/regex.h"

#define PARTS_CONSTAINS(a, c) \
    if (new_parts.find(toupper(a)) != std::string::npos \
        || new_parts.find(tolower(a)) != std::string::npos) { \
          parts = parts | c; \
    }

#define PARTS_CONSTAINS_REM(a, c) \
    if (new_parts.find(toupper(a)) != std::string::npos \
        || new_parts.find(tolower(a)) != std::string::npos) { \
          parts = parts & ~c; \
    }

#define AL_MERGE_STRING_CONF(a, c) \
    if (a.empty() == false) { \
        c = a; \
    }

namespace modsecurity {
namespace audit_log {

AuditLog::AuditLog()
    : m_path1(""),
    m_path2(""),
    m_storage_dir(""),
    m_format(NotSetAuditLogFormat),
    m_parts(-1),
    m_filePermission(-1),
    m_directoryPermission(-1),
    m_status(NotSetLogStatus),
    m_type(NotSetAuditLogType),
    m_relevant(""),
    m_writer(NULL) { }

AuditLog::~AuditLog() {
    if (m_writer) {
        delete m_writer;
        m_writer = NULL;
    }
}

bool AuditLog::setStorageDirMode(int permission) {
    this->m_directoryPermission = permission;
    return true;
}

bool AuditLog::setFileMode(int permission) {
    this->m_filePermission = permission;
    return true;
}

int AuditLog::getFilePermission() const {
    if (m_filePermission == -1) {
        return m_defaultFilePermission;
    }

    return m_filePermission;
}

int AuditLog::getDirectoryPermission() const {
    if (m_directoryPermission == -1) {
        return m_defaultDirectoryPermission;
    }

    return m_directoryPermission;
}

bool AuditLog::setStatus(AuditLogStatus status) {
    this->m_status = status;
    return true;
}

bool AuditLog::setRelevantStatus(const std::basic_string<char>& status) {
    this->m_relevant = std::string(status);
    return true;
}

bool AuditLog::setStorageDir(const std::basic_string<char>& path) {
    this->m_storage_dir = path;
    return true;
}

bool AuditLog::setFilePath1(const std::basic_string<char>& path) {
    this->m_path1 = path;
    return true;
}

bool AuditLog::setFilePath2(const std::basic_string<char>& path) {
    this->m_path2 = path;
    return true;
}

bool AuditLog::setFormat(AuditLogFormat fmt) {
    this->m_format = fmt;
    return true;
}

int AuditLog::addParts(int parts, const std::string& new_parts) {
    PARTS_CONSTAINS('A', AAuditLogPart)
    PARTS_CONSTAINS('B', BAuditLogPart)
    PARTS_CONSTAINS('C', CAuditLogPart)
    PARTS_CONSTAINS('D', DAuditLogPart)
    PARTS_CONSTAINS('E', EAuditLogPart)
    PARTS_CONSTAINS('F', FAuditLogPart)
    PARTS_CONSTAINS('G', GAuditLogPart)
    PARTS_CONSTAINS('H', HAuditLogPart)
    PARTS_CONSTAINS('I', IAuditLogPart)
    PARTS_CONSTAINS('J', JAuditLogPart)
    PARTS_CONSTAINS('K', KAuditLogPart)
    PARTS_CONSTAINS('Z', ZAuditLogPart)

    return parts;
}

int AuditLog::removeParts(int parts, const std::string& new_parts) {
    PARTS_CONSTAINS_REM('A', AAuditLogPart)
    PARTS_CONSTAINS_REM('B', BAuditLogPart)
    PARTS_CONSTAINS_REM('C', CAuditLogPart)
    PARTS_CONSTAINS_REM('D', DAuditLogPart)
    PARTS_CONSTAINS_REM('E', EAuditLogPart)
    PARTS_CONSTAINS_REM('F', FAuditLogPart)
    PARTS_CONSTAINS_REM('G', GAuditLogPart)
    PARTS_CONSTAINS_REM('H', HAuditLogPart)
    PARTS_CONSTAINS_REM('I', IAuditLogPart)
    PARTS_CONSTAINS_REM('J', JAuditLogPart)
    PARTS_CONSTAINS_REM('K', KAuditLogPart)
    PARTS_CONSTAINS_REM('Z', ZAuditLogPart)

    return parts;
}

bool AuditLog::setParts(const std::basic_string<char>& new_parts) {
    int parts = 0;

    PARTS_CONSTAINS('A', AAuditLogPart)
    PARTS_CONSTAINS('B', BAuditLogPart)
    PARTS_CONSTAINS('C', CAuditLogPart)
    PARTS_CONSTAINS('D', DAuditLogPart)
    PARTS_CONSTAINS('E', EAuditLogPart)
    PARTS_CONSTAINS('F', FAuditLogPart)
    PARTS_CONSTAINS('G', GAuditLogPart)
    PARTS_CONSTAINS('H', HAuditLogPart)
    PARTS_CONSTAINS('I', IAuditLogPart)
    PARTS_CONSTAINS('J', JAuditLogPart)
    PARTS_CONSTAINS('K', KAuditLogPart)
    PARTS_CONSTAINS('Z', ZAuditLogPart)

    m_parts = parts;
    return true;
}

int AuditLog::getParts() const {
    if (m_parts == -1) {
        return m_defaultParts;
    }

    return m_parts;
}

bool AuditLog::setType(AuditLogType audit_type) {
    this->m_type = audit_type;
    return true;
}

bool AuditLog::init(std::string *error) {
    audit_log::writer::Writer *tmp_writer;

    if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
        if (m_writer) {
            delete m_writer;
            m_writer = NULL;
        }
        return true;
    }

    if (m_type == ParallelAuditLogType) {
        tmp_writer = new audit_log::writer::Parallel(this);
    } else if (m_type == HttpsAuditLogType) {
        tmp_writer = new audit_log::writer::Https(this);
    } else {
        /*
         * if (m_type == SerialAuditLogType
         * || m_type == NotSetAuditLogType)
         *
         */
        tmp_writer = new audit_log::writer::Serial(this);
    }

    if (tmp_writer == NULL) {
        error->assign("Writer memory alloc failed!");
        return false;
    }

    if (tmp_writer->init(error) == false) {
        delete tmp_writer;
        return false;
    }

    /* Sanity check */
    if (m_status == RelevantOnlyAuditLogStatus) {
        if (m_relevant.empty()) {
            /*
             error->assign("m_relevant cannot be null while status is set to " \
                "RelevantOnly");
             return false;
             */
            // FIXME: this should be a warning. There is not point to
            // have the logs on relevant only if nothing is relevant.
            //
            // Not returning an error to keep the compatibility with v2.
        }
    }

    if (m_writer) {
        delete m_writer;
    }

    m_writer = tmp_writer;

    return true;
}

bool AuditLog::isRelevant(int status) {
    std::string sstatus = std::to_string(status);

    if (m_relevant.empty()) {
        return false;
    }

    if (sstatus.empty()) {
        return true;
    }

    return Utils::regex_search(sstatus,
        Utils::Regex(m_relevant)) != 0;
}

bool AuditLog::saveIfRelevant(Transaction *transaction) {
    return saveIfRelevant(transaction, -1);
}

bool AuditLog::saveIfRelevant(Transaction *transaction, int parts) {
    bool saveAnyway = false;
    if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
        ms_dbg_a(transaction, 5, "Audit log engine was not set.");
        return true;
    }

    for (RuleMessage &i : transaction->m_rulesMessages) {
        if (i.m_noAuditLog == false) {
            saveAnyway = true;
            break;
        }
    }

    if ((m_status == RelevantOnlyAuditLogStatus
        && this->isRelevant(transaction->m_httpCodeReturned) == false)
        && saveAnyway == false) {
        ms_dbg_a(transaction, 9, "Return code `" +
            std::to_string(transaction->m_httpCodeReturned) + "'" \
            " is not interesting to audit logs, relevant code(s): `" +
            m_relevant + "'.");

        return false;
    }

    if (parts == -1) {
        parts = m_parts;
    }
    ms_dbg_a(transaction, 5, "Saving this request as part " \
            "of the audit logs.");
    if (m_writer == NULL) {
        ms_dbg_a(transaction, 1, "Internal error, audit log writer is null");
    } else {
        std::string error;
        bool a = m_writer->write(transaction, parts, &error);
        if (a == false) {
            ms_dbg_a(transaction, 1, "Cannot save the audit log: " + error);
            return false;
        }
    }

    return true;
}

bool AuditLog::close() {
    return true;
}

bool AuditLog::merge(AuditLog *from, std::string *error) {
    AL_MERGE_STRING_CONF(from->m_path1, m_path1);
    AL_MERGE_STRING_CONF(from->m_path2, m_path2);
    AL_MERGE_STRING_CONF(from->m_storage_dir, m_storage_dir);
    AL_MERGE_STRING_CONF(from->m_relevant, m_relevant);

    if (from->m_filePermission != -1) {
        m_filePermission = from->m_filePermission;
    }

    if (from->m_directoryPermission != -1) {
        m_directoryPermission = from->m_directoryPermission;
    }

    if (from->m_type != NotSetAuditLogType) {
        m_type = from->m_type;
    }

    if (from->m_status != NotSetLogStatus) {
        m_status = from->m_status;
    }

    if (from->m_parts != -1) {
        m_parts = from->m_parts;
    }

    if (from->m_format != NotSetAuditLogFormat) {
        m_format = from->m_format;
    }

    return init(error);
}

}  // namespace audit_log
}  // namespace modsecurity
<commit_msg>Remove old commented-out re: audit log, relevant<commit_after>/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "modsecurity/audit_log.h"

#include <stddef.h>
#include <stdio.h>
#include <ctype.h>

#include <fstream>

#include "modsecurity/rule_message.h"
#include "src/audit_log/writer/https.h"
#include "src/audit_log/writer/parallel.h"
#include "src/audit_log/writer/serial.h"
#include "src/audit_log/writer/writer.h"
#include "src/utils/regex.h"

#define PARTS_CONSTAINS(a, c) \
    if (new_parts.find(toupper(a)) != std::string::npos \
        || new_parts.find(tolower(a)) != std::string::npos) { \
          parts = parts | c; \
    }

#define PARTS_CONSTAINS_REM(a, c) \
    if (new_parts.find(toupper(a)) != std::string::npos \
        || new_parts.find(tolower(a)) != std::string::npos) { \
          parts = parts & ~c; \
    }

#define AL_MERGE_STRING_CONF(a, c) \
    if (a.empty() == false) { \
        c = a; \
    }

namespace modsecurity {
namespace audit_log {

AuditLog::AuditLog()
    : m_path1(""),
    m_path2(""),
    m_storage_dir(""),
    m_format(NotSetAuditLogFormat),
    m_parts(-1),
    m_filePermission(-1),
    m_directoryPermission(-1),
    m_status(NotSetLogStatus),
    m_type(NotSetAuditLogType),
    m_relevant(""),
    m_writer(NULL) { }

AuditLog::~AuditLog() {
    if (m_writer) {
        delete m_writer;
        m_writer = NULL;
    }
}

bool AuditLog::setStorageDirMode(int permission) {
    this->m_directoryPermission = permission;
    return true;
}

bool AuditLog::setFileMode(int permission) {
    this->m_filePermission = permission;
    return true;
}

int AuditLog::getFilePermission() const {
    if (m_filePermission == -1) {
        return m_defaultFilePermission;
    }

    return m_filePermission;
}

int AuditLog::getDirectoryPermission() const {
    if (m_directoryPermission == -1) {
        return m_defaultDirectoryPermission;
    }

    return m_directoryPermission;
}

bool AuditLog::setStatus(AuditLogStatus status) {
    this->m_status = status;
    return true;
}

bool AuditLog::setRelevantStatus(const std::basic_string<char>& status) {
    this->m_relevant = std::string(status);
    return true;
}

bool AuditLog::setStorageDir(const std::basic_string<char>& path) {
    this->m_storage_dir = path;
    return true;
}

bool AuditLog::setFilePath1(const std::basic_string<char>& path) {
    this->m_path1 = path;
    return true;
}

bool AuditLog::setFilePath2(const std::basic_string<char>& path) {
    this->m_path2 = path;
    return true;
}

bool AuditLog::setFormat(AuditLogFormat fmt) {
    this->m_format = fmt;
    return true;
}

int AuditLog::addParts(int parts, const std::string& new_parts) {
    PARTS_CONSTAINS('A', AAuditLogPart)
    PARTS_CONSTAINS('B', BAuditLogPart)
    PARTS_CONSTAINS('C', CAuditLogPart)
    PARTS_CONSTAINS('D', DAuditLogPart)
    PARTS_CONSTAINS('E', EAuditLogPart)
    PARTS_CONSTAINS('F', FAuditLogPart)
    PARTS_CONSTAINS('G', GAuditLogPart)
    PARTS_CONSTAINS('H', HAuditLogPart)
    PARTS_CONSTAINS('I', IAuditLogPart)
    PARTS_CONSTAINS('J', JAuditLogPart)
    PARTS_CONSTAINS('K', KAuditLogPart)
    PARTS_CONSTAINS('Z', ZAuditLogPart)

    return parts;
}

int AuditLog::removeParts(int parts, const std::string& new_parts) {
    PARTS_CONSTAINS_REM('A', AAuditLogPart)
    PARTS_CONSTAINS_REM('B', BAuditLogPart)
    PARTS_CONSTAINS_REM('C', CAuditLogPart)
    PARTS_CONSTAINS_REM('D', DAuditLogPart)
    PARTS_CONSTAINS_REM('E', EAuditLogPart)
    PARTS_CONSTAINS_REM('F', FAuditLogPart)
    PARTS_CONSTAINS_REM('G', GAuditLogPart)
    PARTS_CONSTAINS_REM('H', HAuditLogPart)
    PARTS_CONSTAINS_REM('I', IAuditLogPart)
    PARTS_CONSTAINS_REM('J', JAuditLogPart)
    PARTS_CONSTAINS_REM('K', KAuditLogPart)
    PARTS_CONSTAINS_REM('Z', ZAuditLogPart)

    return parts;
}

bool AuditLog::setParts(const std::basic_string<char>& new_parts) {
    int parts = 0;

    PARTS_CONSTAINS('A', AAuditLogPart)
    PARTS_CONSTAINS('B', BAuditLogPart)
    PARTS_CONSTAINS('C', CAuditLogPart)
    PARTS_CONSTAINS('D', DAuditLogPart)
    PARTS_CONSTAINS('E', EAuditLogPart)
    PARTS_CONSTAINS('F', FAuditLogPart)
    PARTS_CONSTAINS('G', GAuditLogPart)
    PARTS_CONSTAINS('H', HAuditLogPart)
    PARTS_CONSTAINS('I', IAuditLogPart)
    PARTS_CONSTAINS('J', JAuditLogPart)
    PARTS_CONSTAINS('K', KAuditLogPart)
    PARTS_CONSTAINS('Z', ZAuditLogPart)

    m_parts = parts;
    return true;
}

int AuditLog::getParts() const {
    if (m_parts == -1) {
        return m_defaultParts;
    }

    return m_parts;
}

bool AuditLog::setType(AuditLogType audit_type) {
    this->m_type = audit_type;
    return true;
}

bool AuditLog::init(std::string *error) {
    audit_log::writer::Writer *tmp_writer;

    if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
        if (m_writer) {
            delete m_writer;
            m_writer = NULL;
        }
        return true;
    }

    if (m_type == ParallelAuditLogType) {
        tmp_writer = new audit_log::writer::Parallel(this);
    } else if (m_type == HttpsAuditLogType) {
        tmp_writer = new audit_log::writer::Https(this);
    } else {
        /*
         * if (m_type == SerialAuditLogType
         * || m_type == NotSetAuditLogType)
         *
         */
        tmp_writer = new audit_log::writer::Serial(this);
    }

    if (tmp_writer == NULL) {
        error->assign("Writer memory alloc failed!");
        return false;
    }

    if (tmp_writer->init(error) == false) {
        delete tmp_writer;
        return false;
    }

    if (m_writer) {
        delete m_writer;
    }

    m_writer = tmp_writer;

    return true;
}

bool AuditLog::isRelevant(int status) {
    std::string sstatus = std::to_string(status);

    if (m_relevant.empty()) {
        return false;
    }

    if (sstatus.empty()) {
        return true;
    }

    return Utils::regex_search(sstatus,
        Utils::Regex(m_relevant)) != 0;
}

bool AuditLog::saveIfRelevant(Transaction *transaction) {
    return saveIfRelevant(transaction, -1);
}

bool AuditLog::saveIfRelevant(Transaction *transaction, int parts) {
    bool saveAnyway = false;
    if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
        ms_dbg_a(transaction, 5, "Audit log engine was not set.");
        return true;
    }

    for (RuleMessage &i : transaction->m_rulesMessages) {
        if (i.m_noAuditLog == false) {
            saveAnyway = true;
            break;
        }
    }

    if ((m_status == RelevantOnlyAuditLogStatus
        && this->isRelevant(transaction->m_httpCodeReturned) == false)
        && saveAnyway == false) {
        ms_dbg_a(transaction, 9, "Return code `" +
            std::to_string(transaction->m_httpCodeReturned) + "'" \
            " is not interesting to audit logs, relevant code(s): `" +
            m_relevant + "'.");

        return false;
    }

    if (parts == -1) {
        parts = m_parts;
    }
    ms_dbg_a(transaction, 5, "Saving this request as part " \
            "of the audit logs.");
    if (m_writer == NULL) {
        ms_dbg_a(transaction, 1, "Internal error, audit log writer is null");
    } else {
        std::string error;
        bool a = m_writer->write(transaction, parts, &error);
        if (a == false) {
            ms_dbg_a(transaction, 1, "Cannot save the audit log: " + error);
            return false;
        }
    }

    return true;
}

bool AuditLog::close() {
    return true;
}

bool AuditLog::merge(AuditLog *from, std::string *error) {
    AL_MERGE_STRING_CONF(from->m_path1, m_path1);
    AL_MERGE_STRING_CONF(from->m_path2, m_path2);
    AL_MERGE_STRING_CONF(from->m_storage_dir, m_storage_dir);
    AL_MERGE_STRING_CONF(from->m_relevant, m_relevant);

    if (from->m_filePermission != -1) {
        m_filePermission = from->m_filePermission;
    }

    if (from->m_directoryPermission != -1) {
        m_directoryPermission = from->m_directoryPermission;
    }

    if (from->m_type != NotSetAuditLogType) {
        m_type = from->m_type;
    }

    if (from->m_status != NotSetLogStatus) {
        m_status = from->m_status;
    }

    if (from->m_parts != -1) {
        m_parts = from->m_parts;
    }

    if (from->m_format != NotSetAuditLogFormat) {
        m_format = from->m_format;
    }

    return init(error);
}

}  // namespace audit_log
}  // namespace modsecurity
<|endoftext|>


<commit_before>#include "pch.h"
#include "axl_io_PCap.h"
#include "axl_err_Error.h"

namespace axl {
namespace io {

//.............................................................................

bool
CPCap::Open (
	const char* pDevice,
	size_t SnapshotSize,
	bool IsPromiscious,
	uint_t ReadTimeout
	)
{
	Close ();

	char ErrorBuffer [PCAP_ERRBUF_SIZE];
	m_h = pcap_open_live (
		pDevice,
		SnapshotSize,
		IsPromiscious,
		ReadTimeout,
		ErrorBuffer
		);

	if (!m_h)
	{
		err::SetStringError (ErrorBuffer);
		return false;
	}

	return true;
}

bool
CPCap::SetFilter (const char* pFilter)
{
	bpf_program Program;

	int Result = pcap_compile (m_h, &Program, (char*) pFilter, true, 0);
	if (Result == -1)
	{
		char ErrorBuffer [PCAP_ERRBUF_SIZE];
		pcap_perror (m_h, ErrorBuffer);
		err::SetStringError (ErrorBuffer);
		return false;
	}

	Result = pcap_setfilter (m_h, &Program);
	pcap_freecode (&Program);
	return Result == 0;
}

bool
CPCap::SetBlockingMode (bool IsBlocking)
{
	char ErrorBuffer [PCAP_ERRBUF_SIZE];
	int Result = pcap_setnonblock (m_h, !IsBlocking, ErrorBuffer);
	if (Result == -1)
	{
		err::SetStringError (ErrorBuffer);
		return false;
	}

	return true;
}

size_t
CPCap::Read (
	void* p,
	size_t Size
	)
{
	pcap_pkthdr* pHdr;
	const uchar_t* pData;

	int Result = pcap_next_ex (m_h, &pHdr, &pData);
	if (Result == -1)
	{
		char ErrorBuffer [PCAP_ERRBUF_SIZE];
		pcap_perror (m_h, ErrorBuffer);
		err::SetStringError (ErrorBuffer);
		return -1;
	}

	if (Result != 1) // special values
		return Result;

	size_t CopySize = AXL_MIN (pHdr->caplen, Size);
	memcpy (p, pData, CopySize);
	return CopySize;
}

size_t
CPCap::Write (
	const void* p,
	size_t Size
	)
{
#if (_AXL_ENV == AXL_ENV_WIN)
	int Result = pcap_sendpacket (m_h, (const u_char*) p, (int) Size);
#else
	int Result = pcap_inject (m_h, p, (int) Size);
#endif
	if (Result == -1)
	{
		char ErrorBuffer [PCAP_ERRBUF_SIZE];
		pcap_perror (m_h, ErrorBuffer);
		err::SetStringError (ErrorBuffer);
		return -1;
	}

	return Size;
}

//.............................................................................

} // namespace io
} // namespace axl
<commit_msg>[axl.io] bugfix: pcap_perror -> pcap_geterr (i misunderstood the meaning of pcap_perror)<commit_after>#include "pch.h"
#include "axl_io_PCap.h"
#include "axl_err_Error.h"

namespace axl {
namespace io {

//.............................................................................

bool
CPCap::Open (
	const char* pDevice,
	size_t SnapshotSize,
	bool IsPromiscious,
	uint_t ReadTimeout
	)
{
	Close ();

	char ErrorBuffer [PCAP_ERRBUF_SIZE];
	m_h = pcap_open_live (
		pDevice,
		SnapshotSize,
		IsPromiscious,
		ReadTimeout,
		ErrorBuffer
		);

	if (!m_h)
	{
		err::SetStringError (ErrorBuffer);
		return false;
	}

	return true;
}

bool
CPCap::SetFilter (const char* pFilter)
{
	bpf_program Program;

	int Result = pcap_compile (m_h, &Program, (char*) pFilter, true, 0);
	if (Result == -1)
	{
		err::SetStringError (pcap_geterr (m_h));
		return false;
	}

	Result = pcap_setfilter (m_h, &Program);
	pcap_freecode (&Program);
	return Result == 0;
}

bool
CPCap::SetBlockingMode (bool IsBlocking)
{
	char ErrorBuffer [PCAP_ERRBUF_SIZE];
	int Result = pcap_setnonblock (m_h, !IsBlocking, ErrorBuffer);
	if (Result == -1)
	{
		err::SetStringError (ErrorBuffer);
		return false;
	}

	return true;
}

size_t
CPCap::Read (
	void* p,
	size_t Size
	)
{
	pcap_pkthdr* pHdr;
	const uchar_t* pData;

	int Result = pcap_next_ex (m_h, &pHdr, &pData);
	if (Result == -1)
	{
		err::SetStringError (pcap_geterr (m_h));
		return -1;
	}

	if (Result != 1) // special values
		return Result;

	size_t CopySize = AXL_MIN (pHdr->caplen, Size);
	memcpy (p, pData, CopySize);
	return CopySize;
}

size_t
CPCap::Write (
	const void* p,
	size_t Size
	)
{
#if (_AXL_ENV == AXL_ENV_WIN)
	int Result = pcap_sendpacket (m_h, (const u_char*) p, (int) Size);
#else
	int Result = pcap_inject (m_h, p, (int) Size);
#endif
	if (Result == -1)
	{
		err::SetStringError (pcap_geterr (m_h));
		return -1;
	}

	return Size;
}

//.............................................................................

} // namespace io
} // namespace axl
<|endoftext|>


<commit_before>/**
 * This file is part of Slideshow.
 * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
 *                         Pernilla Sveningsson <estel@sidvind.com>
 *
 * Slideshow is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Slideshow 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 Slideshow.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include "backend/SDLbackend.h"
#include "exception.h"

#ifdef WIN32
#	include "win32.h"
#endif

static const int sdl_flags = SDL_OPENGL | SDL_DOUBLEBUF;
static PlatformBackend* factory(void){
	return new SDLBackend;
}

void SDLBackend::register_factory(){
	PlatformBackend::register_factory("sdl", ::factory);
}

SDLBackend::SDLBackend()
	: PlatformBackend()
	, _lock(false) {

}

SDLBackend::~SDLBackend(){

}

int SDLBackend::init(const Vector2ui &resolution, bool fullscreen){
	set_resolution(resolution.width, resolution.height);

	int flags = sdl_flags;

	if ( fullscreen ){
		flags |= SDL_FULLSCREEN;
	}

	_fullscreen = fullscreen;
	SDL_Init(SDL_INIT_VIDEO);
	SDL_SetVideoMode(resolution.width, resolution.height, 0, flags);
	SDL_EnableUNICODE(1);

#ifdef WIN32
	SetConsoleOutputCP(65001);
#endif

	return 0;
}

void SDLBackend::cleanup(){
	SDL_Quit();
}

void SDLBackend::poll(bool& running){
	SDL_Event event;
		while(SDL_PollEvent(&event) ){
			switch(event.type){
				case SDL_KEYDOWN:
					if ( event.key.keysym.sym == SDLK_ESCAPE ){
						running = false;
					}

					if ( (event.key.keysym.sym == SDLK_RETURN) && (event.key.keysym.mod & KMOD_ALT)){
						_fullscreen = !_fullscreen;
						int flags = sdl_flags;

						if ( _fullscreen ){
							flags |= SDL_FULLSCREEN;
						}

						SDL_SetVideoMode(resolution().width, resolution().height, 0, flags);
					}

					break;

				case SDL_VIDEORESIZE:
					printf("video resize\n");
					set_resolution(event.resize.w, event.resize.h);
					break;

				case SDL_QUIT:
					running = false;
					break;
			}
		}
}

void SDLBackend::swap_buffers() const {
	SDL_GL_SwapBuffers();
}

void SDLBackend::lock_mouse(bool state){
	_lock = state;

	if ( _lock ){
		SDL_WarpMouse(center().x, center().y);
	}
}
<commit_msg>dies on errors<commit_after>/**
 * This file is part of Slideshow.
 * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
 *                         Pernilla Sveningsson <estel@sidvind.com>
 *
 * Slideshow is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Slideshow 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 Slideshow.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include "backend/SDLbackend.h"
#include "exception.h"

#ifdef WIN32
#	include "win32.h"
#endif

static const int sdl_flags = SDL_OPENGL | SDL_DOUBLEBUF;
static PlatformBackend* factory(void){
	return new SDLBackend;
}

void SDLBackend::register_factory(){
	PlatformBackend::register_factory("sdl", ::factory);
}

SDLBackend::SDLBackend()
	: PlatformBackend()
	, _lock(false) {

}

SDLBackend::~SDLBackend(){

}

int SDLBackend::init(const Vector2ui &resolution, bool fullscreen){
	set_resolution(resolution.width, resolution.height);

	int flags = sdl_flags;

	if ( fullscreen ){
		flags |= SDL_FULLSCREEN;
	}

	_fullscreen = fullscreen;

	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ){
		throw exception("Unable to init SDL: %s", SDL_GetError());
	}

	if ( SDL_SetVideoMode(resolution.width, resolution.height, 0, flags) == NULL ){
		throw exception("Unable to init SDL: %s", SDL_GetError());
	}

	SDL_EnableUNICODE(1);

#ifdef WIN32
	SetConsoleOutputCP(65001);
#endif

	return 0;
}

void SDLBackend::cleanup(){
	SDL_Quit();
}

void SDLBackend::poll(bool& running){
	SDL_Event event;
		while(SDL_PollEvent(&event) ){
			switch(event.type){
				case SDL_KEYDOWN:
					if ( event.key.keysym.sym == SDLK_ESCAPE ){
						running = false;
					}

					if ( (event.key.keysym.sym == SDLK_RETURN) && (event.key.keysym.mod & KMOD_ALT)){
						_fullscreen = !_fullscreen;
						int flags = sdl_flags;

						if ( _fullscreen ){
							flags |= SDL_FULLSCREEN;
						}

						SDL_SetVideoMode(resolution().width, resolution().height, 0, flags);
					}

					break;

				case SDL_VIDEORESIZE:
					printf("video resize\n");
					set_resolution(event.resize.w, event.resize.h);
					break;

				case SDL_QUIT:
					running = false;
					break;
			}
		}
}

void SDLBackend::swap_buffers() const {
	SDL_GL_SwapBuffers();
}

void SDLBackend::lock_mouse(bool state){
	_lock = state;

	if ( _lock ){
		SDL_WarpMouse(center().x, center().y);
	}
}
<|endoftext|>


<commit_before>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.pitnt(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<commit_msg>Fix spelling in Arduino 2<commit_after>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<|endoftext|>


<commit_before>
#include "common.h"

// interface header
#include "LuaServer.h"

// system headers
#include <stdio.h>
#include <ctype.h>
#include <string>
#include <vector>
using std::string;
using std::vector;

// common headers
#include "bzfsAPI.h"
#include "TextUtils.h"
#include "bzfio.h"

// bzfs headers
#include "../bzfs.h"
#include "../CmdLineOptions.h"

//local headers
#include "LuaHeader.h"
#include "BZDB.h"
#include "CallIns.h"
#include "CallOuts.h"
#include "Constants.h"
#include "FetchURL.h"
#include "MapObject.h"
#include "RawLink.h"
#include "SlashCmd.h"
#include "Double.h"

//============================================================================//
//============================================================================//

static lua_State* L = NULL;

static bool CreateLuaState(const string& script);
static string EnvExpand(const string& path);

//============================================================================//
//============================================================================//

static string directory = "./";

static bool SetupLuaDirectory(const string& fileName);

extern const string& GetLuaDirectory() { return directory; } // extern

//============================================================================//
//============================================================================//

static bool fileExists(const string& file)
{
  FILE* f = fopen(file.c_str(), "r");
  if (f == NULL) {
    return false;
  }
  fclose(f);
  return true;
}

//============================================================================//
//============================================================================//

bool LuaServer::init(const string& cmdLine)
{
  if (cmdLine.empty()) {
    return false;
  }

  bool dieHard = false;

  logDebugMessage(1, "loading LuaServer\n");

  if (L != NULL) {
    logDebugMessage(1, "LuaServer is already loaded\n");
    return false;
  }

  // dieHard check
  string scriptFile = cmdLine.c_str();
  if (scriptFile.size() > 8) {
    if (scriptFile.substr(0, 8) == "dieHard,") {
      dieHard = true;
      scriptFile = scriptFile.substr(8);
    }
  }

  // leading tilde => $HOME substitution
  if (!scriptFile.empty() && (scriptFile[0] == '~')) {
    scriptFile = "$HOME" + scriptFile.substr(1);
  }

  scriptFile = EnvExpand(scriptFile);

  if (!fileExists(scriptFile)) {
    scriptFile = string(bz_pluginBinPath()) + "/" + scriptFile;
  }
  if (!fileExists(scriptFile)) {
    logDebugMessage(1, "LuaServer: could not find the script file\n");
    if (dieHard) {
      exit(2);
    }
    return false;
  }

  SetupLuaDirectory(scriptFile);

  if (!CreateLuaState(scriptFile)) {
    if (dieHard) {
      exit(3);
    }
    return false;
  }

  return true;
}

//============================================================================//
//============================================================================//

bool LuaServer::kill()
{
  if (L == NULL) {
    return false;
  }

  CallIns::Shutdown(); // send the call-in

  RawLink::CleanUp(L);
  FetchURL::CleanUp(L);
  SlashCmd::CleanUp(L);
  MapObject::CleanUp(L);
  CallIns::CleanUp(L);

  lua_close(L);
  L = NULL;

  return true;
}

//============================================================================//
//============================================================================//

bool LuaServer::isActive()
{
  return (L != NULL);
}

//============================================================================//
//============================================================================//

lua_State* LuaServer::GetL()
{
  return L;
}

//============================================================================//
//============================================================================//

void LuaServer::recvCommand(const string& cmdLine, int playerIndex)
{
  vector<string> args = TextUtils::tokenize(cmdLine, " \t", 3);

  GameKeeper::Player* p = GameKeeper::Player::getPlayerByIndex(playerIndex);
  if (p == NULL) {
    return;
  }

  if (args[0] != "/luaserver") {
    return; // something is amiss, bail
  }

  if (args.size() < 2) {
    sendMessage(ServerPlayer, playerIndex,
                "/luaserver < status | disable | reload >");
    return;
  }

  if (args[1] == "status") {
    if (isActive()) {
      sendMessage(ServerPlayer, playerIndex, "LuaServer is enabled");
    } else {
      sendMessage(ServerPlayer, playerIndex, "LuaServer is disabled");
    }
    return;
  }

  if (args[1] == "disable") {
    if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
      sendMessage(ServerPlayer, playerIndex,
                  "You do not have permission to control LuaServer");
      return;
    }
    if (isActive()) {
      kill();
      sendMessage(ServerPlayer, playerIndex, "LuaServer has been disabled");
    } else {
      sendMessage(ServerPlayer, playerIndex, "LuaServer is not loaded");
    }
    return;
  }

  if (args[1] == "reload") {
    if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
      sendMessage(ServerPlayer, playerIndex,
                  "You do not have permission to control LuaServer");
      return;
    }
    kill();
    bool success = false;
    if (args.size() > 2) {
      success = init(args[2]);
    } else {
      success = init(clOptions->luaServer);
    }
    if (success) {
      sendMessage(ServerPlayer, playerIndex, "LuaServer reload succeeded");
    } else {
      sendMessage(ServerPlayer, playerIndex, "LuaServer reload failed");
    }
    return;
  }

  if (L != NULL) {
    CallIns::RecvCommand(cmdLine);
  }

  return;
}

//============================================================================//
//============================================================================//

static bool SetupLuaDirectory(const string& fileName)
{
  const string::size_type pos = fileName.find_last_of("/\\");
  if (pos == string::npos) {
    directory = "./";
  } else {
    directory = fileName.substr(0, pos + 1);
  }
  return true;
}

//============================================================================//
//============================================================================//

static bool CreateLuaState(const string& script)
{
  if (L != NULL) {
    return false;
  }

  L = luaL_newstate();
  luaL_openlibs(L);

  CallIns::PushEntries(L);

  lua_pushvalue(L, LUA_GLOBALSINDEX);
  LuaDouble::PushEntries(L);
  lua_pop(L, 1);

  lua_pushliteral(L, "bz");
  lua_newtable(L); {
    CallOuts::PushEntries(L);
    MapObject::PushEntries(L);
    SlashCmd::PushEntries(L);
    FetchURL::PushEntries(L);
    RawLink::PushEntries(L);
  }
  lua_rawset(L, LUA_GLOBALSINDEX);

  lua_pushliteral(L, "BZ");
  lua_newtable(L); {
    Constants::PushEntries(L);
  }
  lua_rawset(L, LUA_GLOBALSINDEX);

  lua_pushliteral(L, "bzdb");
  lua_newtable(L); {
    LuaBZDB::PushEntries(L);
  }
  lua_rawset(L, LUA_GLOBALSINDEX);

  if (luaL_dofile(L, script.c_str()) != 0) {
    logDebugMessage(1, "lua init error: %s\n", lua_tostring(L, -1));
    lua_pop(L, 1);
    return false;
  }

  return true;
}

//============================================================================//
//============================================================================//

static string EnvExpand(const string& path)
{

  string::size_type pos = path.find('$');
  if (pos == string::npos) {
    return path;
  }

  if (path[pos + 1] == '$') { // allow $$ escapes
    return path.substr(0, pos + 1) + EnvExpand(path.substr(pos + 2));
  }

  const char* b = path.c_str(); // beginning of string
  const char* s = b + pos + 1;  // start of the key name
  const char* e = s;            // end   of the key Name
  while ((*e != 0) && (isalnum(*e) || (*e == '_'))) {
    e++;
  }

  const string head = path.substr(0, pos);
  const string key  = path.substr(pos + 1, e - s);
  const string tail = path.substr(e - b);

  const char* env = getenv(key.c_str());
  const string value = (env == NULL) ? "" : env;

  return head + value + EnvExpand(tail);
}

//============================================================================//
//============================================================================//

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>* setup the LuaServer lua 'package.path' and 'package.cpath' variables<commit_after>
#include "common.h"

// interface header
#include "LuaServer.h"

// system headers
#include <stdio.h>
#include <ctype.h>
#include <string>
#include <vector>
using std::string;
using std::vector;

// common headers
#include "bzfsAPI.h"
#include "TextUtils.h"
#include "bzfio.h"

// bzfs headers
#include "../bzfs.h"
#include "../CmdLineOptions.h"

//local headers
#include "LuaHeader.h"
#include "BZDB.h"
#include "CallIns.h"
#include "CallOuts.h"
#include "Constants.h"
#include "FetchURL.h"
#include "MapObject.h"
#include "RawLink.h"
#include "SlashCmd.h"
#include "Double.h"

//============================================================================//
//============================================================================//

static lua_State* L = NULL;

static bool CreateLuaState(const string& script);
static string EnvExpand(const string& path);

//============================================================================//
//============================================================================//

static string directory = "./";

static bool SetupLuaDirectory(const string& fileName);

extern const string& GetLuaDirectory() { return directory; } // extern

//============================================================================//
//============================================================================//

static bool fileExists(const string& file)
{
  FILE* f = fopen(file.c_str(), "r");
  if (f == NULL) {
    return false;
  }
  fclose(f);
  return true;
}

//============================================================================//
//============================================================================//

bool LuaServer::init(const string& cmdLine)
{
  if (cmdLine.empty()) {
    return false;
  }

  bool dieHard = false;

  logDebugMessage(1, "loading LuaServer\n");

  if (L != NULL) {
    logDebugMessage(1, "LuaServer is already loaded\n");
    return false;
  }

  // dieHard check
  string scriptFile = cmdLine.c_str();
  if (scriptFile.size() > 8) {
    if (scriptFile.substr(0, 8) == "dieHard,") {
      dieHard = true;
      scriptFile = scriptFile.substr(8);
    }
  }

  // leading tilde => $HOME substitution
  if (!scriptFile.empty() && (scriptFile[0] == '~')) {
    scriptFile = "$HOME" + scriptFile.substr(1);
  }

  scriptFile = EnvExpand(scriptFile);

  if (!fileExists(scriptFile)) {
    scriptFile = string(bz_pluginBinPath()) + "/" + scriptFile;
  }
  if (!fileExists(scriptFile)) {
    logDebugMessage(1, "LuaServer: could not find the script file\n");
    if (dieHard) {
      exit(2);
    }
    return false;
  }

  SetupLuaDirectory(scriptFile);

  if (!CreateLuaState(scriptFile)) {
    if (dieHard) {
      exit(3);
    }
    return false;
  }

  return true;
}

//============================================================================//
//============================================================================//

bool LuaServer::kill()
{
  if (L == NULL) {
    return false;
  }

  CallIns::Shutdown(); // send the call-in

  RawLink::CleanUp(L);
  FetchURL::CleanUp(L);
  SlashCmd::CleanUp(L);
  MapObject::CleanUp(L);
  CallIns::CleanUp(L);

  lua_close(L);
  L = NULL;

  return true;
}

//============================================================================//
//============================================================================//

bool LuaServer::isActive()
{
  return (L != NULL);
}

//============================================================================//
//============================================================================//

lua_State* LuaServer::GetL()
{
  return L;
}

//============================================================================//
//============================================================================//

void LuaServer::recvCommand(const string& cmdLine, int playerIndex)
{
  vector<string> args = TextUtils::tokenize(cmdLine, " \t", 3);

  GameKeeper::Player* p = GameKeeper::Player::getPlayerByIndex(playerIndex);
  if (p == NULL) {
    return;
  }

  if (args[0] != "/luaserver") {
    return; // something is amiss, bail
  }

  if (args.size() < 2) {
    sendMessage(ServerPlayer, playerIndex,
                "/luaserver < status | disable | reload >");
    return;
  }

  if (args[1] == "status") {
    if (isActive()) {
      sendMessage(ServerPlayer, playerIndex, "LuaServer is enabled");
    } else {
      sendMessage(ServerPlayer, playerIndex, "LuaServer is disabled");
    }
    return;
  }

  if (args[1] == "disable") {
    if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
      sendMessage(ServerPlayer, playerIndex,
                  "You do not have permission to control LuaServer");
      return;
    }
    if (isActive()) {
      kill();
      sendMessage(ServerPlayer, playerIndex, "LuaServer has been disabled");
    } else {
      sendMessage(ServerPlayer, playerIndex, "LuaServer is not loaded");
    }
    return;
  }

  if (args[1] == "reload") {
    if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
      sendMessage(ServerPlayer, playerIndex,
                  "You do not have permission to control LuaServer");
      return;
    }
    kill();
    bool success = false;
    if (args.size() > 2) {
      success = init(args[2]);
    } else {
      success = init(clOptions->luaServer);
    }
    if (success) {
      sendMessage(ServerPlayer, playerIndex, "LuaServer reload succeeded");
    } else {
      sendMessage(ServerPlayer, playerIndex, "LuaServer reload failed");
    }
    return;
  }

  if (L != NULL) {
    CallIns::RecvCommand(cmdLine);
  }

  return;
}

//============================================================================//
//============================================================================//

static bool SetupLuaDirectory(const string& fileName)
{
  const string::size_type pos = fileName.find_last_of("/\\");
  if (pos == string::npos) {
    directory = "./";
  } else {
    directory = fileName.substr(0, pos + 1);
  }
  return true;
}

//============================================================================//
//============================================================================//

static bool CreateLuaState(const string& script)
{
  if (L != NULL) {
    return false;
  }

  L = luaL_newstate();
  luaL_openlibs(L);

  const string path  = directory + "?.lua";
  const string cpath = directory + "?.so;" + directory + "?.dll";
  lua_getglobal(L, "package");
  lua_pushstdstring(L, path);  lua_setfield(L, -2, "path");
  lua_pushstdstring(L, cpath); lua_setfield(L, -2, "cpath");
  lua_pop(L, 1);

  CallIns::PushEntries(L);

  lua_pushvalue(L, LUA_GLOBALSINDEX);
  LuaDouble::PushEntries(L);
  lua_pop(L, 1);

  lua_pushliteral(L, "bz");
  lua_newtable(L); {
    CallOuts::PushEntries(L);
    MapObject::PushEntries(L);
    SlashCmd::PushEntries(L);
    FetchURL::PushEntries(L);
    RawLink::PushEntries(L);
  }
  lua_rawset(L, LUA_GLOBALSINDEX);

  lua_pushliteral(L, "BZ");
  lua_newtable(L); {
    Constants::PushEntries(L);
  }
  lua_rawset(L, LUA_GLOBALSINDEX);

  lua_pushliteral(L, "bzdb");
  lua_newtable(L); {
    LuaBZDB::PushEntries(L);
  }
  lua_rawset(L, LUA_GLOBALSINDEX);

  if (luaL_dofile(L, script.c_str()) != 0) {
    logDebugMessage(1, "lua init error: %s\n", lua_tostring(L, -1));
    lua_pop(L, 1);
    return false;
  }

  return true;
}

//============================================================================//
//============================================================================//

static string EnvExpand(const string& path)
{

  string::size_type pos = path.find('$');
  if (pos == string::npos) {
    return path;
  }

  if (path[pos + 1] == '$') { // allow $$ escapes
    return path.substr(0, pos + 1) + EnvExpand(path.substr(pos + 2));
  }

  const char* b = path.c_str(); // beginning of string
  const char* s = b + pos + 1;  // start of the key name
  const char* e = s;            // end   of the key Name
  while ((*e != 0) && (isalnum(*e) || (*e == '_'))) {
    e++;
  }

  const string head = path.substr(0, pos);
  const string key  = path.substr(pos + 1, e - s);
  const string tail = path.substr(e - b);

  const char* env = getenv(key.c_str());
  const string value = (env == NULL) ? "" : env;

  return head + value + EnvExpand(tail);
}

//============================================================================//
//============================================================================//

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/**
 * @file save_restore_model_test.cpp
 * @author Neil Slagle
 *
 * Here we have tests for the SaveRestoreModel class.
 */
#include <mlpack/core/util/save_restore_utility.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

#define ARGSTR(a) a,#a

using namespace mlpack;
using namespace mlpack::util;

BOOST_AUTO_TEST_SUITE(SaveRestoreUtilityTest);

/*
 * Exhibit proper save restore utility usage of child class proper usage.
 */
class SaveRestoreTest
{
 private:
  size_t anInt;
  SaveRestoreUtility saveRestore;

 public:
  SaveRestoreTest()
  {
    saveRestore = SaveRestoreUtility();
    anInt = 0;
  }

  bool SaveModel(std::string filename)
  {
    saveRestore.SaveParameter(anInt, "anInt");
    return saveRestore.WriteFile(filename);
  }

  bool LoadModel(std::string filename)
  {
    bool success = saveRestore.ReadFile(filename);
    if (success)
      anInt = saveRestore.LoadParameter(anInt, "anInt");

    return success;
  }

  size_t AnInt() { return anInt; }
  void AnInt(size_t s) { this->anInt = s; }
};

/**
 * Perform a save and restore on basic types.
 */
BOOST_AUTO_TEST_CASE(SaveBasicTypes)
{
  bool b = false;
  char c = 67;
  unsigned u = 34;
  size_t s = 12;
  short sh = 100;
  int i = -23;
  float f = -2.34f;
  double d = 3.14159;
  std::string cc = "Hello world!";

  SaveRestoreUtility* sRM = new SaveRestoreUtility();

  sRM->SaveParameter(ARGSTR(b));
  sRM->SaveParameter(ARGSTR(c));
  sRM->SaveParameter(ARGSTR(u));
  sRM->SaveParameter(ARGSTR(s));
  sRM->SaveParameter(ARGSTR(sh));
  sRM->SaveParameter(ARGSTR(i));
  sRM->SaveParameter(ARGSTR(f));
  sRM->SaveParameter(ARGSTR(d));
  sRM->SaveParameter(ARGSTR(cc));
  sRM->WriteFile("test_basic_types.xml");

  sRM->ReadFile("test_basic_types.xml");

  bool b2 =         sRM->LoadParameter(ARGSTR(b));
  char c2 =         sRM->LoadParameter(ARGSTR(c));
  unsigned u2 =     sRM->LoadParameter(ARGSTR(u));
  size_t s2 =       sRM->LoadParameter(ARGSTR(s));
  short sh2 =       sRM->LoadParameter(ARGSTR(sh));
  int i2 =          sRM->LoadParameter(ARGSTR(i));
  float f2 =        sRM->LoadParameter(ARGSTR(f));
  double d2 =       sRM->LoadParameter(ARGSTR(d));
  std::string cc2 = sRM->LoadParameter(ARGSTR(cc));

  BOOST_REQUIRE(b == b2);
  BOOST_REQUIRE(c == c2);
  BOOST_REQUIRE(u == u2);
  BOOST_REQUIRE(s == s2);
  BOOST_REQUIRE(sh == sh2);
  BOOST_REQUIRE(i == i2);
  BOOST_REQUIRE(cc == cc2);
  BOOST_REQUIRE_CLOSE(f, f2, 1e-5);
  BOOST_REQUIRE_CLOSE(d, d2, 1e-5);

  delete sRM;
}

BOOST_AUTO_TEST_CASE(SaveRestoreStdVector)
{
  size_t numbers[] = {0,3,6,2,6};
  std::vector<size_t> vec (numbers,
                           numbers + sizeof (numbers) / sizeof (size_t));
  SaveRestoreUtility* sRM = new SaveRestoreUtility();

  sRM->SaveParameter(ARGSTR(vec));

  sRM->WriteFile("test_std_vector_type.xml");

  sRM->ReadFile("test_std_vector_type.xml");

  std::vector<size_t> loadee = sRM->LoadParameter(ARGSTR(vec));

  for (size_t index = 0; index < loadee.size(); ++index)
    BOOST_REQUIRE_EQUAL(numbers[index], loadee[index]);
}

/**
 * Test the arma::mat functionality.
 */
BOOST_AUTO_TEST_CASE(SaveArmaMat)
{
  arma::mat matrix;
  matrix <<  1.2 << 2.3 << -0.1 << arma::endr
         <<  3.5 << 2.4 << -1.2 << arma::endr
         << -0.1 << 3.4 << -7.8 << arma::endr;

  SaveRestoreUtility* sRM = new SaveRestoreUtility();

  sRM->SaveParameter(ARGSTR(matrix));

  sRM->WriteFile("test_arma_mat_type.xml");

  sRM->ReadFile("test_arma_mat_type.xml");

  arma::mat matrix2 = sRM->LoadParameter(ARGSTR(matrix));

  for (size_t row = 0; row < matrix.n_rows; ++row)
    for (size_t column = 0; column < matrix.n_cols; ++column)
      BOOST_REQUIRE_CLOSE(matrix(row,column), matrix2(row,column), 1e-5);

  delete sRM;
}

/**
 * Test SaveRestoreModel proper usage in child classes and loading from
 *   separately defined objects
 */
BOOST_AUTO_TEST_CASE(SaveRestoreModelChildClassUsage)
{
  SaveRestoreTest* saver = new SaveRestoreTest();
  SaveRestoreTest* loader = new SaveRestoreTest();
  size_t s = 1200;
  const char* filename = "anInt.xml";

  saver->AnInt(s);
  saver->SaveModel(filename);
  delete saver;

  loader->LoadModel(filename);

  BOOST_REQUIRE(loader->AnInt() == s);

  delete loader;
}

BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Fix syntax.<commit_after>/**
 * @file save_restore_model_test.cpp
 * @author Neil Slagle
 *
 * Here we have tests for the SaveRestoreModel class.
 */
#include <mlpack/core/util/save_restore_utility.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

#define ARGSTR(a) a,#a

using namespace mlpack;
using namespace mlpack::util;

BOOST_AUTO_TEST_SUITE(SaveRestoreUtilityTest);

/*
 * Exhibit proper save restore utility usage of child class proper usage.
 */
class SaveRestoreTest
{
 private:
  size_t anInt;
  SaveRestoreUtility saveRestore;

 public:
  SaveRestoreTest()
  {
    saveRestore = SaveRestoreUtility();
    anInt = 0;
  }

  bool SaveModel(std::string filename)
  {
    saveRestore.SaveParameter(anInt, "anInt");
    return saveRestore.WriteFile(filename);
  }

  bool LoadModel(std::string filename)
  {
    bool success = saveRestore.ReadFile(filename);
    if (success)
      anInt = saveRestore.LoadParameter(anInt, "anInt");

    return success;
  }

  size_t AnInt() { return anInt; }
  void AnInt(size_t s) { this->anInt = s; }
};

/**
 * Perform a save and restore on basic types.
 */
BOOST_AUTO_TEST_CASE(SaveBasicTypes)
{
  bool b = false;
  char c = 67;
  unsigned u = 34;
  size_t s = 12;
  short sh = 100;
  int i = -23;
  float f = -2.34f;
  double d = 3.14159;
  std::string cc = "Hello world!";

  SaveRestoreUtility* sRM = new SaveRestoreUtility();

  sRM->SaveParameter(ARGSTR(b));
  sRM->SaveParameter(ARGSTR(c));
  sRM->SaveParameter(ARGSTR(u));
  sRM->SaveParameter(ARGSTR(s));
  sRM->SaveParameter(ARGSTR(sh));
  sRM->SaveParameter(ARGSTR(i));
  sRM->SaveParameter(ARGSTR(f));
  sRM->SaveParameter(ARGSTR(d));
  sRM->SaveParameter(ARGSTR(cc));
  sRM->WriteFile("test_basic_types.xml");

  sRM->ReadFile("test_basic_types.xml");

  bool b2 =         sRM->LoadParameter(ARGSTR(b));
  char c2 =         sRM->LoadParameter(ARGSTR(c));
  unsigned u2 =     sRM->LoadParameter(ARGSTR(u));
  size_t s2 =       sRM->LoadParameter(ARGSTR(s));
  short sh2 =       sRM->LoadParameter(ARGSTR(sh));
  int i2 =          sRM->LoadParameter(ARGSTR(i));
  float f2 =        sRM->LoadParameter(ARGSTR(f));
  double d2 =       sRM->LoadParameter(ARGSTR(d));
  std::string cc2 = sRM->LoadParameter(ARGSTR(cc));

  BOOST_REQUIRE(b == b2);
  BOOST_REQUIRE(c == c2);
  BOOST_REQUIRE(u == u2);
  BOOST_REQUIRE(s == s2);
  BOOST_REQUIRE(sh == sh2);
  BOOST_REQUIRE(i == i2);
  BOOST_REQUIRE(cc == cc2);
  BOOST_REQUIRE_CLOSE(f, f2, 1e-5);
  BOOST_REQUIRE_CLOSE(d, d2, 1e-5);

  delete sRM;
}

BOOST_AUTO_TEST_CASE(SaveRestoreStdVector)
{
  size_t numbers[] = {0,3,6,2,6};
  std::vector<size_t> vec (numbers,
                           numbers + sizeof (numbers) / sizeof (size_t));
  SaveRestoreUtility* sRM = new SaveRestoreUtility();

  sRM->SaveParameter(ARGSTR(vec));

  sRM->WriteFile("test_std_vector_type.xml");

  sRM->ReadFile("test_std_vector_type.xml");

  std::vector<size_t> loadee = sRM->LoadParameter(ARGSTR(vec));

  for (size_t index = 0; index < loadee.size(); ++index)
    BOOST_REQUIRE_EQUAL(numbers[index], loadee[index]);
}

/**
 * Test the arma::mat functionality.
 */
BOOST_AUTO_TEST_CASE(SaveArmaMat)
{
  arma::mat matrix;
  matrix <<  1.2 << 2.3 << -0.1 << arma::endr
         <<  3.5 << 2.4 << -1.2 << arma::endr
         << -0.1 << 3.4 << -7.8 << arma::endr;

  SaveRestoreUtility* sRM = new SaveRestoreUtility();

  sRM->SaveParameter(ARGSTR(matrix));

  sRM->WriteFile("test_arma_mat_type.xml");

  sRM->ReadFile("test_arma_mat_type.xml");

  arma::mat matrix2 = sRM->LoadParameter(ARGSTR(matrix));

  for (size_t row = 0; row < matrix.n_rows; ++row)
    for (size_t column = 0; column < matrix.n_cols; ++column)
      BOOST_REQUIRE_CLOSE(matrix(row, column), matrix2(row, column), 1e-5);

  delete sRM;
}

/**
 * Test SaveRestoreModel proper usage in child classes and loading from
 *   separately defined objects
 */
BOOST_AUTO_TEST_CASE(SaveRestoreModelChildClassUsage)
{
  SaveRestoreTest* saver = new SaveRestoreTest();
  SaveRestoreTest* loader = new SaveRestoreTest();
  size_t s = 1200;
  const char* filename = "anInt.xml";

  saver->AnInt(s);
  saver->SaveModel(filename);
  delete saver;

  loader->LoadModel(filename);

  BOOST_REQUIRE(loader->AnInt() == s);

  delete loader;
}

BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>


<commit_before>/* $Id$ */

// Helper macros can be found in this file
// A set of them can be used to connect to proof and execute selectors.

TVirtualProof* connectProof(const char* proofServer)
{
  TVirtualProof* proof = TProof::Open(proofServer);

  if (!proof)
  {
    printf("ERROR: PROOF connection not established.\n");
    return 0;
  }

  // enable the new packetizer
  //proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive"));

  proof->ClearInput();

  return proof;
}

Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot)
{
  // if not proof load libraries
  if (!gProof)
  {
    TObjArray* librariesList = libraries.Tokenize(";");
    for (Int_t i=0; i<librariesList->GetEntries(); ++i)
    {
      TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i));
      if (!str)
        continue;

      printf("Loading %s...", str->String().Data());
      Int_t result = CheckLoadLibrary(str->String());
      if (result < 0)
      {
        printf("failed\n");
        //return kFALSE;
      }
      else
        printf("succeeded\n");
    }
  }
  else
  {
    if (useAliRoot > 0)
      ProofEnableAliRoot(useAliRoot);

    TObjArray* packagesList = packages.Tokenize(";");
    for (Int_t i=0; i<packagesList->GetEntries(); ++i)
    {
      TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i));
      if (!str)
        continue;

      /*if (!EnablePackageLocal(str->String()))
      {
        printf("Loading of package %s locally failed\n", str->String().Data());
        return kFALSE;
      }*/

      if (gProof->UploadPackage(Form("%s.par", str->String().Data())))
      {
        printf("Uploading of package %s failed\n", str->String().Data());
        return kFALSE;
      }

      if (gProof->EnablePackage(str->String()))
      {
        printf("Loading of package %s failed\n", str->String().Data());
        return kFALSE;
      }
    }
 }

 return kTRUE;
}

Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "")
{
  if (!gProof)
    chain->GetUserInfo()->AddAll(inputList);
  else
  {
    for (Int_t i=0; i<inputList->GetEntries(); ++i)
      gProof->AddInput(inputList->At(i));
  }

  TStopwatch timer;
  timer.Start();

  Long64_t result = -1;

  if (gProof)
    result = chain->MakeTDSet()->Process(selectorName, option);
  else
    result = chain->Process(selectorName, option);

  if (result < 0)
    printf("ERROR: Executing process failed with %d.\n", result);

  timer.Stop();
  timer.Print();

  return result;
}

void ProofEnableAliRoot(Int_t aliroot)
{
  // enables a locally deployed AliRoot in a PROOF cluster

  /* executes the following commands on each node:
     gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head")
     gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include");
     gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux"))
     gSystem->Load("libMinuit");
     gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C");
  */

  const char* location = 0;
	const char* target = "tgt_linux";

  switch (aliroot)
  {
    case 1: location = "/home/alicecaf/ALICE/aliroot-v4-04-Release"; break;
    case 2: location = "/home/alicecaf/ALICE/aliroot-head"; break;
		case 11: location = "/data1/qfiete/aliroot-head"; target = "tgt_linuxx8664gcc"; break;
    default: return;
  }

  gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE);
  gProof->AddIncludePath(Form("%s/include", location));
  gProof->AddDynamicPath(Form("%s/lib/%s", location, target));

  // load all libraries
  gProof->Exec("gSystem->Load(\"libMinuit\")");
  gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")");
}

Bool_t EnablePackageLocal(const char* package)
{
  printf("Enabling package %s locally...\n", package);

  TString currentDir(gSystem->pwd());
  if (!gSystem->cd(package))
    return kFALSE;

  gROOT->ProcessLine(".x PROOF-INF/SETUP.C");
  gSystem->cd(currentDir);

  return kTRUE;
}

Int_t CheckLoadLibrary(const char* library)
{
  // checks if a library is already loaded, if not loads the library

  if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
    return 1;

  return gSystem->Load(library);
}

void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE)
{
  // deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT
  // when localAliRoot is false ESD.par is also deployed

  TProof::Reset(proofServer);
  TVirtualProof* proof = TProof::Open(proofServer);
  proof->ClearPackages();

  if (localAliRoot)
    ProofEnableAliRoot();
  else
  {
    proof->UploadPackage("$ALICE_ROOT/ESD.par");
    proof->EnablePackage("ESD");
  }

  proof->UploadPackage("$ALICE_ROOT/PWG0base.par");
  proof->EnablePackage("PWG0base");

  proof->UploadPackage("$ALICE_ROOT/PWG0dep.par");
  proof->EnablePackage("PWG0dep");
}
<commit_msg>adding entries parameter to execute function<commit_after>/* $Id$ */

// Helper macros can be found in this file
// A set of them can be used to connect to proof and execute selectors.

TVirtualProof* connectProof(const char* proofServer)
{
  TVirtualProof* proof = TProof::Open(proofServer);

  if (!proof)
  {
    printf("ERROR: PROOF connection not established.\n");
    return 0;
  }

  // enable the new packetizer
  //proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive"));

  proof->ClearInput();

  return proof;
}

Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot)
{
  // if not proof load libraries
  if (!gProof)
  {
    TObjArray* librariesList = libraries.Tokenize(";");
    for (Int_t i=0; i<librariesList->GetEntries(); ++i)
    {
      TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i));
      if (!str)
        continue;

      printf("Loading %s...", str->String().Data());
      Int_t result = CheckLoadLibrary(str->String());
      if (result < 0)
      {
        printf("failed\n");
        //return kFALSE;
      }
      else
        printf("succeeded\n");
    }
  }
  else
  {
    if (useAliRoot > 0)
      ProofEnableAliRoot(useAliRoot);

    TObjArray* packagesList = packages.Tokenize(";");
    for (Int_t i=0; i<packagesList->GetEntries(); ++i)
    {
      TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i));
      if (!str)
        continue;

      /*if (!EnablePackageLocal(str->String()))
      {
        printf("Loading of package %s locally failed\n", str->String().Data());
        return kFALSE;
      }*/

      if (gProof->UploadPackage(Form("%s.par", str->String().Data())))
      {
        printf("Uploading of package %s failed\n", str->String().Data());
        return kFALSE;
      }

      if (gProof->EnablePackage(str->String()))
      {
        printf("Loading of package %s failed\n", str->String().Data());
        return kFALSE;
      }
    }
 }

 return kTRUE;
}

Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "", Long64_t entries = TChain::kBigNumber)
{
  if (!gProof)
    chain->GetUserInfo()->AddAll(inputList);
  else
  {
    for (Int_t i=0; i<inputList->GetEntries(); ++i)
      gProof->AddInput(inputList->At(i));
  }

  TStopwatch timer;
  timer.Start();

  Long64_t result = -1;

  if (gProof)
    result = chain->MakeTDSet()->Process(selectorName, option, entries);
  else
    result = chain->Process(selectorName, option, entries);

  if (result < 0)
    printf("ERROR: Executing process failed with %d.\n", result);

  timer.Stop();
  timer.Print();

  return result;
}

void ProofEnableAliRoot(Int_t aliroot)
{
  // enables a locally deployed AliRoot in a PROOF cluster

  /* executes the following commands on each node:
     gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head")
     gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include");
     gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux"))
     gSystem->Load("libMinuit");
     gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C");
  */

  const char* location = 0;
	const char* target = "tgt_linux";

  switch (aliroot)
  {
    case 1: location = "/home/alicecaf/ALICE/aliroot-v4-04-Release"; break;
    case 2: location = "/home/alicecaf/ALICE/aliroot-head"; break;
		case 11: location = "/data1/qfiete/aliroot-head"; target = "tgt_linuxx8664gcc"; break;
    default: return;
  }

  gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE);
  gProof->AddIncludePath(Form("%s/include", location));
  gProof->AddDynamicPath(Form("%s/lib/%s", location, target));

  // load all libraries
  gProof->Exec("gSystem->Load(\"libMinuit\")");
  gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")");
}

Bool_t EnablePackageLocal(const char* package)
{
  printf("Enabling package %s locally...\n", package);

  TString currentDir(gSystem->pwd());
  if (!gSystem->cd(package))
    return kFALSE;

  gROOT->ProcessLine(".x PROOF-INF/SETUP.C");
  gSystem->cd(currentDir);

  return kTRUE;
}

Int_t CheckLoadLibrary(const char* library)
{
  // checks if a library is already loaded, if not loads the library

  if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
    return 1;

  return gSystem->Load(library);
}

void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE)
{
  // deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT
  // when localAliRoot is false ESD.par is also deployed

  TProof::Reset(proofServer);
  TVirtualProof* proof = TProof::Open(proofServer);
  proof->ClearPackages();

  if (localAliRoot)
    ProofEnableAliRoot();
  else
  {
    proof->UploadPackage("$ALICE_ROOT/ESD.par");
    proof->EnablePackage("ESD");
  }

  proof->UploadPackage("$ALICE_ROOT/PWG0base.par");
  proof->EnablePackage("PWG0base");

  proof->UploadPackage("$ALICE_ROOT/PWG0dep.par");
  proof->EnablePackage("PWG0dep");
}
<|endoftext|>


<commit_before>// PolyHook.cpp : Defines the entry point for the console application.
//
#include <tchar.h>
#include "PolyHook.h"
#define PLH_SHOW_DEBUG_MESSAGES 1 //To print messages even in release

typedef int(__stdcall* tMessageBoxA)(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType);
tMessageBoxA oMessageBoxA;

typedef void(__stdcall* tVirtNoParams)(DWORD_PTR pThis);
tVirtNoParams oVirtNoParams;

typedef void(__stdcall* tGetCurrentThreadId)();
tGetCurrentThreadId oGetCurrentThreadID;

typedef int(__stdcall* tVEH)(int intparam);
tVEH oVEHTest;

PLH::VEHHook* VEHHook;

DWORD __stdcall hkGetCurrentThreadId()
{
	printf("Called hkGetCurrentThreadID\n");
	return 1337;
}

int __stdcall hkMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
	printf("In Hook\n");
	return oMessageBoxA(hWnd, lpText, lpCaption, uType);
}

void __stdcall hkVirtNoParams(DWORD_PTR pThis)
{
	printf("hk Virt Called\n");
	return oVirtNoParams(pThis);
}

__declspec(noinline) int __stdcall VEHTest(int param)
{
	printf("VEHFunc %d\n",param);
	return 3;
}

__declspec(noinline) int __stdcall hkVEHTest(int param)
{
	printf("hkVEH %d\n",param);
	auto ProtectionObject = VEHHook->GetProtectionObject();

	return oVEHTest(param);
}

class VirtualTest
{
public:
	virtual void NoParamVirt()
	{
		volatile int x = 0;
		printf("Called Virt\n");
	}
	virtual void BS()
	{
		volatile int y = 0;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	///X86/x64 Detour Example
	//PLH::Detour* Hook = new PLH::Detour();
	//Hook->SetupHook((BYTE*)&MessageBoxA,(BYTE*) &hkMessageBoxA); //can cast to byte* to
	//Hook->Hook();
	//oMessageBoxA = Hook->GetOriginal<tMessageBoxA>();
	//MessageBoxA(NULL, "Message", "Sample", MB_OK);
	//Hook->UnHook();
	//MessageBoxA(NULL, "Message", "Sample", MB_OK);

	///x86/x64 IAT Hook Example
	//PLH::IATHook* Hook = new PLH::IATHook();
	//Hook->SetupHook("kernel32.dll", "GetCurrentThreadId", (BYTE*)&hkGetCurrentThreadId);
	//Hook->Hook();
	//oGetCurrentThreadID = Hook->GetOriginal<tGetCurrentThreadId>();
	//printf("Thread ID:%d \n", GetCurrentThreadId());
	//Hook->UnHook();
	//printf("Real Thread ID:%d\n", GetCurrentThreadId());

	///x86/x64 VFuncDetour Example
	//VirtualTest* ClassToHook = new VirtualTest();
	//PLH::VFuncDetour* VirtHook = new PLH::VFuncDetour();
	//VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
	//VirtHook->Hook();
	//oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
	//ClassToHook->NoParamVirt();
	//VirtHook->UnHook();
	//ClassToHook->NoParamVirt();

	///x86/x64 VFuncSwap Example
	/*PLH::VFuncSwap* VirtHook = new PLH::VFuncSwap();
	VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
	VirtHook->Hook();
	oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
	ClassToHook->NoParamVirt();
	VirtHook->UnHook();
	ClassToHook->NoParamVirt();*/

	///x86/x64 VTableSwap Example
	//PLH::VTableSwap* VTableHook = new PLH::VTableSwap();
	//VTableHook->SetupHook((BYTE*)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
	//VTableHook->Hook();
	//oVirtNoParams = VTableHook->GetOriginal<tVirtNoParams>();
	//ClassToHook->NoParamVirt();
	//VTableHook->UnHook();
	//ClassToHook->NoParamVirt();

	/*!!!!IMPORTANT!!!!!: Since this demo is small it's possible for internal methods to be on the same memory page
	as the VEHTest function. If that happens the GUARD_PAGE type method will fail with an unexpected exception.
	If this method is used in larger applications this risk is increadibly small, to the point where it should not
	be worried about.
	*/
	///x86/x64 VEH Example (GUARD_PAGE and INT3_BP)
<<<<<<< HEAD
	VEHHook = new PLH::VEHHook();
	VEHHook->SetupHook((BYTE*)&VEHTest, (BYTE*)&hkVEHTest, PLH::VEHHook::VEHMethod::HARDWARE_BP);
=======
	/*VEHHook = new PLH::VEHHook();
	VEHHook->SetupHook((BYTE*)&VEHTest, (BYTE*)&hkVEHTest, PLH::VEHHook::VEHMethod::INT3_BP);
>>>>>>> refs/remotes/origin/master
	VEHHook->Hook();
	oVEHTest = VEHHook->GetOriginal<tVEH>();
	VEHTest(3);
	VEHHook->UnHook();
	VEHTest(1);
<<<<<<< HEAD
	printf("%s %s\n", (VEHHook->GetLastError().GetSeverity() == PLH::RuntimeError::Severity::NoError) ? "No Error" : "Error",
		VEHHook->GetLastError().GetString().c_str());
=======
	VEHHook->PrintError(VEHHook->GetLastError());*/
>>>>>>> refs/remotes/origin/master

	Sleep(100000);
	return 0;
}
<commit_msg>Cleaned Main<commit_after>// PolyHook.cpp : Defines the entry point for the console application.
//
#include <tchar.h>
#include "PolyHook.h"
#define PLH_SHOW_DEBUG_MESSAGES 1 //To print messages even in release

typedef int(__stdcall* tMessageBoxA)(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType);
tMessageBoxA oMessageBoxA;

typedef void(__stdcall* tVirtNoParams)(DWORD_PTR pThis);
tVirtNoParams oVirtNoParams;

typedef void(__stdcall* tGetCurrentThreadId)();
tGetCurrentThreadId oGetCurrentThreadID;

typedef int(__stdcall* tVEH)(int intparam);
tVEH oVEHTest;

PLH::VEHHook* VEHHook;

DWORD __stdcall hkGetCurrentThreadId()
{
	printf("Called hkGetCurrentThreadID\n");
	return 1337;
}

int __stdcall hkMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
	printf("In Hook\n");
	return oMessageBoxA(hWnd, lpText, lpCaption, uType);
}

void __stdcall hkVirtNoParams(DWORD_PTR pThis)
{
	printf("hk Virt Called\n");
	return oVirtNoParams(pThis);
}

__declspec(noinline) int __stdcall VEHTest(int param)
{
	printf("VEHFunc %d\n",param);
	return 3;
}

__declspec(noinline) int __stdcall hkVEHTest(int param)
{
	printf("hkVEH %d\n",param);
	auto ProtectionObject = VEHHook->GetProtectionObject();

	return oVEHTest(param);
}

class VirtualTest
{
public:
	virtual void NoParamVirt()
	{
		volatile int x = 0;
		printf("Called Virt\n");
	}
	virtual void BS()
	{
		volatile int y = 0;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	///X86/x64 Detour Example
	//PLH::Detour* Hook = new PLH::Detour();
	//Hook->SetupHook((BYTE*)&MessageBoxA,(BYTE*) &hkMessageBoxA); //can cast to byte* to
	//Hook->Hook();
	//oMessageBoxA = Hook->GetOriginal<tMessageBoxA>();
	//MessageBoxA(NULL, "Message", "Sample", MB_OK);
	//Hook->UnHook();
	//MessageBoxA(NULL, "Message", "Sample", MB_OK);

	///x86/x64 IAT Hook Example
	//PLH::IATHook* Hook = new PLH::IATHook();
	//Hook->SetupHook("kernel32.dll", "GetCurrentThreadId", (BYTE*)&hkGetCurrentThreadId);
	//Hook->Hook();
	//oGetCurrentThreadID = Hook->GetOriginal<tGetCurrentThreadId>();
	//printf("Thread ID:%d \n", GetCurrentThreadId());
	//Hook->UnHook();
	//printf("Real Thread ID:%d\n", GetCurrentThreadId());

	///x86/x64 VFuncDetour Example
	//VirtualTest* ClassToHook = new VirtualTest();
	//PLH::VFuncDetour* VirtHook = new PLH::VFuncDetour();
	//VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
	//VirtHook->Hook();
	//oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
	//ClassToHook->NoParamVirt();
	//VirtHook->UnHook();
	//ClassToHook->NoParamVirt();

	///x86/x64 VFuncSwap Example
	/*PLH::VFuncSwap* VirtHook = new PLH::VFuncSwap();
	VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
	VirtHook->Hook();
	oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
	ClassToHook->NoParamVirt();
	VirtHook->UnHook();
	ClassToHook->NoParamVirt();*/

	///x86/x64 VTableSwap Example
	//PLH::VTableSwap* VTableHook = new PLH::VTableSwap();
	//VTableHook->SetupHook((BYTE*)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
	//VTableHook->Hook();
	//oVirtNoParams = VTableHook->GetOriginal<tVirtNoParams>();
	//ClassToHook->NoParamVirt();
	//VTableHook->UnHook();
	//ClassToHook->NoParamVirt();

	/*!!!!IMPORTANT!!!!!: Since this demo is small it's possible for internal methods to be on the same memory page
	as the VEHTest function. If that happens the GUARD_PAGE type method will fail with an unexpected exception.
	If this method is used in larger applications this risk is increadibly small, to the point where it should not
	be worried about.
	*/
	///x86/x64 VEH Example (GUARD_PAGE and INT3_BP)
	/*VEHHook = new PLH::VEHHook();
	VEHHook->SetupHook((BYTE*)&VEHTest, (BYTE*)&hkVEHTest, PLH::VEHHook::VEHMethod::INT3_BP);
	VEHHook->Hook();
	oVEHTest = VEHHook->GetOriginal<tVEH>();
	VEHTest(3);
	VEHHook->UnHook();
	VEHTest(1);
	VEHHook->PrintError(VEHHook->GetLastError());*/

	Sleep(100000);
	return 0;
}
<|endoftext|>