Example #1
0
bool ExpDotWriter::postVisit(const std::shared_ptr<TypedExp> &exp)
{
    *m_os << "e_" << HostAddress(exp.get()) << " [shape=record,label=\"{";
    *m_os << "opTypedExp\\n" << HostAddress(exp.get()) << " | ";
    // Just display the C type for now
    *m_os << exp->getType()->getCtype() << " | <p1>";
    *m_os << " }\"];\n";
    *m_os << "e_" << HostAddress(exp.get()) << ":p1->e_" << HostAddress(exp->getSubExp1().get())
          << ";\n";

    return true;
}
Example #2
0
// Find the native address for the start of the main entry function.
// For Palm binaries, this is PilotMain.
Address PalmBinaryLoader::getMainEntryPoint()
{
    BinarySection *psect = m_binaryImage->getSectionByName("code1");

    if (psect == nullptr) {
        return Address::ZERO; // Failed
    }

    // Return the start of the code1 section
    SWord *startCode = reinterpret_cast<SWord *>(psect->getHostAddr().value());
    int delta        = (psect->getHostAddr() - psect->getSourceAddr()).value();

    // First try the CW first jump pattern
    const SWord *res = findPattern(startCode, sizeof(CWFirstJump) / sizeof(SWord), CWFirstJump,
                                   sizeof(CWFirstJump) / sizeof(SWord));

    if (res) {
        // We have the code warrior first jump. Get the addil operand
        const int addilOp  = static_cast<int>(Util::readDWord((startCode + 5), Endian::Big));
        SWord *startupCode = reinterpret_cast<SWord *>(
            (HostAddress(startCode) + 10 + addilOp).value());

        // Now check the next 60 SWords for the call to PilotMain
        res = findPattern(startupCode, 60, CWCallMain, sizeof(CWCallMain) / sizeof(SWord));

        if (res) {
            // Get the addil operand
            const int _addilOp = Util::readDWord((res + 5), Endian::Big);

            // That operand plus the address of that operand is PilotMain
            Address offset_loc = Address(reinterpret_cast<const Byte *>(res) -
                                         reinterpret_cast<const Byte *>(startCode) + 5);
            return offset_loc + _addilOp; // ADDRESS::host_ptr(res) + 10 + addilOp - delta;
        }
        else {
            fprintf(stderr, "Could not find call to PilotMain in CW app\n");
            return Address::ZERO;
        }
    }

    // Check for gcc call to main
    res = findPattern(startCode, 75, GccCallMain, sizeof(GccCallMain) / sizeof(SWord));

    if (res) {
        // Get the operand to the bsr
        SWord bsrOp = res[7];
        return Address((HostAddress(res) - delta).value() + 14 + bsrOp);
    }

    fprintf(stderr, "Cannot find call to PilotMain\n");
    return Address::ZERO;
}
void PlatformDomainNameAddressQuery::runBlocking() {
	//std::cout << "PlatformDomainNameResolver::doRun()" << std::endl;
	boost::asio::ip::tcp::resolver resolver(ioService);
	boost::asio::ip::tcp::resolver::query query(hostname, "5222");
	try {
		//std::cout << "PlatformDomainNameResolver::doRun(): Resolving" << std::endl;
		boost::asio::ip::tcp::resolver::iterator endpointIterator = resolver.resolve(query);
		//std::cout << "PlatformDomainNameResolver::doRun(): Resolved" << std::endl;
		if (endpointIterator == boost::asio::ip::tcp::resolver::iterator()) {
			//std::cout << "PlatformDomainNameResolver::doRun(): Error 1" << std::endl;
			emitError();
		}
		else {
			std::vector<HostAddress> results;
			for ( ; endpointIterator != boost::asio::ip::tcp::resolver::iterator(); ++endpointIterator) {
				boost::asio::ip::address address = (*endpointIterator).endpoint().address();
				results.push_back(address.is_v4() ? HostAddress(&address.to_v4().to_bytes()[0], 4) : HostAddress(&address.to_v6().to_bytes()[0], 16));
			}

			//std::cout << "PlatformDomainNameResolver::doRun(): Success" << std::endl;
			eventLoop->postEvent(
					boost::bind(boost::ref(onResult), results, boost::optional<DomainNameResolveError>()), 
					shared_from_this());
		}
	}
	catch (...) {
		//std::cout << "PlatformDomainNameResolver::doRun(): Error 2" << std::endl;
		emitError();
	}
}
boost::optional<HostAddress> NATPMPInterface::getPublicIP() {
	if (sendpublicaddressrequest(&p->natpmp) < 0) {
		SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl;
		return boost::optional<HostAddress>();
	}

	int r = 0;
	natpmpresp_t response;
	do {
	  fd_set fds;
	  struct timeval timeout;
	  FD_ZERO(&fds);
	  FD_SET(p->natpmp.s, &fds);
	  getnatpmprequesttimeout(&p->natpmp, &timeout);
	  select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
	  r = readnatpmpresponseorretry(&p->natpmp, &response);
	} while (r == NATPMP_TRYAGAIN);

	if (r == 0) {
		return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4));
	}
	else {
		SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl;
		return boost::optional<HostAddress>();
	}
}
Example #5
0
bool ExpDotWriter::postVisit(const std::shared_ptr<Unary> &exp)
{
    // First a node for this Unary object
    *m_os << "e_" << HostAddress(exp.get()).toString() << " [shape=record,label=\"{";
    // The (int) cast is to print the address, not the expression!
    *m_os << operToString(exp->getOper()) << "\\n"
          << " | ";
    *m_os << "<p1>";
    *m_os << " }\"];\n";

    // Finally an edge for the subexpression
    *m_os << "e_" << HostAddress(exp.get()) << "->e_" << HostAddress(exp->getSubExp1().get())
          << ";\n";

    return true;
}
Example #6
0
bool TUIClientApp::connectWithTUIServer(
        int mySendPortNr,
        int myReceivePortNr,
        const std::string & serverAddress,
        IEventSink * systemNotificationSink,
        bool ownership) {

    this->myReceivePortNr = myReceivePortNr;
    this->systemNotificationSink = systemNotificationSink;


    this->outHostMsgDispatcher.addDstAddress(HostAddress(serverAddress));
    this->udpSenderSocket.setMyPort(mySendPortNr);
    this->udpReceiverSocket.setMyPort(myReceivePortNr);

    this->create();

    SystemCmdMsg * msg = new SystemCmdMsg();
    msg->setPayload(SystemCmd(SystemCmd::requestConnection, static_cast<unsigned short>(this->myReceivePortNr)));
    this->outEventQueue.push(msg);

    if (ownership) {
        this->executeOutputLoop();
    }

    return true;
}
Example #7
0
bool ExpDotWriter::postVisit(const std::shared_ptr<Binary> &exp)
{
    // First a node for this Binary object
    *m_os << "e_" << HostAddress(exp.get()) << " [shape=record,label=\"{";
    *m_os << operToString(exp->getOper()) << "\\n"
          << " | ";
    *m_os << "{<p1> | <p2>}";
    *m_os << " }\"];\n";

    // Now an edge for each subexpression
    *m_os << "e_" << HostAddress(exp.get()) << ":p1->e_" << HostAddress(exp->getSubExp1().get())
          << ";\n";
    *m_os << "e_" << HostAddress(exp.get()) << ":p2->e_" << HostAddress(exp->getSubExp2().get())
          << ";\n";

    return true;
}
Example #8
0
bool ExpDotWriter::visit(const std::shared_ptr<Terminal> &exp)
{
    *m_os << "e_" << HostAddress(exp.get()).toString() << " [shape=parallelogram,label=\"";

    if (exp->getOper() == opWild) {
        // Note: value is -1, so can't index array
        *m_os << "WILD";
    }
    else {
        *m_os << operToString(exp->getOper());
    }

    *m_os << "\\n" << HostAddress(exp.get()).toString();
    *m_os << "\"];\n";

    return true;
}
Example #9
0
Socket::Socket(Port _port, bool runInit)
  : server(true),
    closeOnDelete(true),
    handle(-1),
    iaddr(HostAddress(),_port)
{
  if (!globalInit()) JGACHINE_SERROR("globalInit");
  if (runInit) init();
}
Example #10
0
bool ExpDotWriter::postVisit(const std::shared_ptr<FlagDef> &exp)
{
    *m_os << "e_" << HostAddress(exp.get()) << " [shape=record,label=\"{";
    *m_os << "opFlagDef \\n" << HostAddress(exp.get()) << "| ";
    // Display the RTL as "RTL <r1> <r2>..." vertically (curly brackets)
    *m_os << "{ RTL ";

    const size_t n = exp->getRTL()->size();
    for (size_t i = 0; i < n; i++) {
        *m_os << "| <r" << i << "> ";
    }

    *m_os << "} | <p1> }\"];\n";
    *m_os << "e_" << HostAddress(exp.get()) << ":p1->e_" << HostAddress(exp->getSubExp1().get())
          << ";\n";

    return true;
}
Example #11
0
main()
{
#ifdef WINDOWS_NT
        WSADATA wsaData;

        // Initialize the winsock library
        if (WSAStartup(0x101, &wsaData) != 0)
        {
                cout << "Error intializing Winsock library: " << WSAGetLastError() << endl;
                return 0;
        }
#endif
        
    // Retrieve the host name and host address given the host name
    try
    {
        XPCGetHostInfo HostName("aHost", NAME);
        cout << "Name: " << HostName.sGetHostName() << endl;
        cout << "Address: " << HostName.sGetHostAddress() << endl;
    }
    catch (XPCException &exceptObject)
    {
        cout << exceptObject.sGetException() << endl;
    }

    // Retrieve the host name and host address given the host address
    try
    {
            XPCGetHostInfo HostAddress("146.121.32.139", ADDRESS);
            cout << "Name: " << HostAddress.sGetHostName() << endl;
            cout << "Address: " << HostAddress.sGetHostAddress() << endl;
    }
    catch (XPCException &exceptObject)
    {
            cout << exceptObject.sGetException() << endl;
    }

#ifdef UNIX
    // Retrieve all entries from the host name database
    XPCGetHostInfo AllHosts;
    while(AllHosts.cGetNextHost())
    {
        cout << "Name: " << AllHosts.sGetHostName() << endl;
        cout << "Address: " << AllHosts.sGetHostAddress() << endl;
    }
#endif

#ifdef WINDOWS_NT
        // Close the winsock library
        if (WSACleanup() != 0)
        {
                cerr << "Error cleaning up the Winsock library: " << WSAGetLastError() << endl;
        }
#endif
}
std::vector<NetworkInterface> WindowsNetworkEnvironment::getNetworkInterfaces()  const {
	std::vector<NetworkInterface> result;

	ByteArray adapters;
	ULONG bufferSize = 0;
	ULONG ret;
	ULONG flags = GAA_FLAG_INCLUDE_ALL_INTERFACES | GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
	while ((ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, reinterpret_cast<IP_ADAPTER_ADDRESSES*>(vecptr(adapters)), &bufferSize)) == ERROR_BUFFER_OVERFLOW) {
		adapters.resize(bufferSize);
	};
	if (ret != ERROR_SUCCESS) {
		return result;
	}

	std::map<std::string,NetworkInterface> interfaces;
	for (IP_ADAPTER_ADDRESSES* adapter = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(vecptr(adapters)); adapter; adapter = adapter->Next) {
		std::string name(adapter->AdapterName);
		if (adapter->OperStatus != IfOperStatusUp) {
			continue;
		}
		for (IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; address; address = address->Next) {
			boost::optional<HostAddress> hostAddress;
			if (address->Address.lpSockaddr->sa_family == PF_INET) {
				sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(address->Address.lpSockaddr);
				hostAddress = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4);
			}
			else if (address->Address.lpSockaddr->sa_family == PF_INET6) {
				sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(address->Address.lpSockaddr);
				hostAddress = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16);
			}
			if (hostAddress) {
				std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, false))).first;
				i->second.addAddress(*hostAddress);
			}
		}
	}

	for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
		result.push_back(i->second);
	}
	return result;
}
Example #13
0
boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() {
	if (!p->isValid) {
		return boost::optional<HostAddress>();
	}
	char externalIPAddress[40];
	int ret = UPNP_GetExternalIPAddress(p->urls.controlURL, p->data.first.servicetype, externalIPAddress);
	if (ret != UPNPCOMMAND_SUCCESS) {
		return boost::optional<HostAddress>();
	}
	else {
		return HostAddress(std::string(externalIPAddress));
	}
}
Example #14
0
HostAddressPort UnixProxyProvider::getHTTPConnectProxy() const {
    HostAddressPort proxy;
#if defined(HAVE_GCONF)
    proxy = gconfProxyProvider->getHTTPConnectProxy();
    if(proxy.isValid()) {
        return proxy;
    }
#endif
    proxy = environmentProxyProvider.getHTTPConnectProxy();
    if(proxy.isValid()) {
        return proxy;
    }
    return HostAddressPort(HostAddress(), 0);
}
Example #15
0
void Connector::start() {
	SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl;
	assert(!currentConnection);
	assert(!serviceQuery);
	assert(!timer);
	queriedAllServices = false;
	if (timeoutMilliseconds > 0) {
		timer = timerFactory->createTimer(timeoutMilliseconds);
		timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this()));
	}
	if (serviceLookupPrefix) {
		serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname);
		serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1));
		serviceQuery->run();
	}
	else if (HostAddress(hostname).isValid()) {
		// hostname is already a valid address; skip name lookup.
		foundSomeDNS = true;
		addressQueryResults.push_back(HostAddress(hostname));
		tryNextAddress();
	} else {
		queryAddress(hostname);
	}
}
Example #16
0
void  Network::UdpSocket::canRead() {
 struct sockaddr_in	addr;
  socklen_t		size = sizeof(addr);
  
  memset(&addr, 0, sizeof(addr));
  _readMutex.lock();
  _reading = false;
  int ret = recvfrom(_fd, (char*)(*_readBuffer), _readBuffer->getSize(), 0, (struct sockaddr*)&addr, &size);
  _readMutex.unlock();
  if (ret == 0)
    this->close();
  else if (ret != -1 && _delegate) {
    _readBuffer->resize(ret);
    _delegate->readFinished(this, *_readBuffer, HostAddress(inet_ntoa(addr.sin_addr)), ntohs(addr.sin_port));
  }
}
void SOCKS5BytestreamProxiesManager::handleProxyFound(S5BProxyRequest::ref proxy) {
	if (proxy) {
		if (HostAddress(proxy->getStreamHost().get().host).isValid()) {
			addS5BProxy(proxy);
		}
		else {
			DomainNameAddressQuery::ref resolveRequest = resolver_->createAddressQuery(proxy->getStreamHost().get().host);
			resolveRequest->onResult.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleNameLookupResult, this, _1, _2, proxy));
			resolveRequest->run();
		}
	}
	else {
		onDiscoveredProxiesChanged();
	}
	proxyFinder_->stop();
	proxyFinder_.reset();
}
    void JingleS5BTransportMethodPayloadParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
        if (level == 0) {
            getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
            std::string mode = attributes.getAttributeValue("mode").get_value_or("tcp");
            if (mode == "tcp") {
                getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
            } else if(mode == "udp") {
                getPayloadInternal()->setMode(JingleS5BTransportPayload::UDPMode);
            } else {
                SWIFT_LOG(warning) << "Unknown S5B mode; falling back to defaul!";
                getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
            }
            getPayloadInternal()->setDstAddr(attributes.getAttributeValue("dstaddr").get_value_or(""));
        } else if (level == 1) {
            if (element == "candidate") {
                JingleS5BTransportPayload::Candidate candidate;
                candidate.cid = attributes.getAttributeValue("cid").get_value_or("");

                int port = -1;
                try {
                    port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1"));
                } catch(boost::bad_lexical_cast &) { }
                candidate.hostPort = HostAddressPort(HostAddress(attributes.getAttributeValue("host").get_value_or("")), port);
                candidate.jid = JID(attributes.getAttributeValue("jid").get_value_or(""));
                int priority = -1;
                try {
                    priority = boost::lexical_cast<int>(attributes.getAttributeValue("priority").get_value_or("-1"));
                } catch(boost::bad_lexical_cast &) { }
                candidate.priority = priority;
                candidate.type = stringToType(attributes.getAttributeValue("type").get_value_or("direct"));

                getPayloadInternal()->addCandidate(candidate);
            } else if (element == "candidate-used") {
                getPayloadInternal()->setCandidateUsed(attributes.getAttributeValue("cid").get_value_or(""));
            } else if (element == "candidate-error") {
                getPayloadInternal()->setCandidateError(true);
            } else if (element == "activated") {
                getPayloadInternal()->setActivated(attributes.getAttributeValue("cid").get_value_or(""));
            } else if (element == "proxy-error") {
                getPayloadInternal()->setProxyError(true);
            }
        }

        ++level;
    }
Example #19
0
bool ExpDotWriter::visit(const std::shared_ptr<Const> &exp)
{
    // We define a unique name for each node as "e_0x123456" if the address of "this" == 0x123456
    *m_os << "e_" << HostAddress(exp.get()) << " [shape=record,label=\"{";
    *m_os << operToString(exp->getOper()) << "\\n"
          << " | ";

    switch (exp->getOper()) {
        // Might want to distinguish this better, e.g. "(func*)myProc"
    case opFuncConst: *m_os << exp->getFuncName() << "()"; break;
    case opIntConst: *m_os << exp->getInt(); break;
    case opFltConst: *m_os << exp->getFlt(); break;
    case opStrConst: *m_os << "\\\"" << exp->getStr() << "\\\""; break;
    default: break;
    }

    *m_os << " }\"];\n";

    return true;
}
Example #20
0
bool RedisProxy::run(const HostAddress& addr)
{
    if (isRunning()) {
        return false;
    }

    if (m_vipEnabled) {
        TcpSocket sock = TcpSocket::createTcpSocket();
        Logger::log(Logger::Message, "connect to vip address(%s:%d)...", m_vipAddress, addr.port());
        if (!sock.connect(HostAddress(m_vipAddress, addr.port()))) {
            Logger::log(Logger::Message, "set VIP [%s,%s]...", m_vipName, m_vipAddress);
            int ret = NonPortable::setVipAddress(m_vipName, m_vipAddress, 0);
            Logger::log(Logger::Message, "set_vip_address return %d", ret);
        } else {
            m_vipSocket = sock;
            m_vipEvent.set(eventLoop(), sock.socket(), EV_READ, vipHandler, this);
            m_vipEvent.active();
        }
    }


    m_monitor->proxyStarted(this);
    Logger::log(Logger::Message, "Start the %s on port %d", APP_NAME, addr.port());

    RedisCommand cmds[] = {
        {"HASHMAPPING", 11, -1, onHashMapping, NULL},
        {"ADDKEYMAPPING", 13, -1, onAddKeyMapping, NULL},
        {"DELKEYMAPPING", 13, -1, onDelKeyMapping, NULL},
        {"SHOWMAPPING", 11, -1, onShowMapping, NULL},
        {"POOLINFO", 8, -1, onPoolInfo, NULL},
        {"SHUTDOWN", 8, -1, onShutDown, this}
    };
    RedisCommandTable::instance()->registerCommand(cmds, sizeof(cmds)/sizeof(RedisCommand));

    return TcpServer::run(addr);
}
Example #21
0
 * redistribution of this file, and for a DISCLAIMER OF ALL
 * WARRANTIES.
 */
#pragma endregion License
#include "Address.h"

#include "boomerang/util/ByteUtil.h"
#include "boomerang/util/log/Log.h"

#include <cassert>

const Address Address::ZERO    = Address(0);
const Address Address::INVALID = Address(static_cast<Address::value_type>(-1));
Byte Address::m_sourceBits     = 32U;

const HostAddress HostAddress::ZERO    = HostAddress(nullptr);
const HostAddress HostAddress::INVALID = HostAddress(static_cast<HostAddress::value_type>(-1));


Address::Address()
    : m_value(0)
{
}


Address::Address(value_type _value)
    : m_value(_value)
{
    if ((m_value != static_cast<value_type>(-1)) && ((_value & ~getSourceMask()) != 0)) {
        LOG_VERBOSE2("Address initialized with invalid value %1",
                     QString("0x%1").arg(m_value, 2 * sizeof(value_type), 16, QChar('0')));
Example #22
0
void startOneCache(void)
{
    CRedisProxyCfg* cfg = CRedisProxyCfg::instance();
    setupSignal();

    EventLoop listenerLoop;
    bool twemproxyMode = cfg->isTwemproxyMode();
    const int points_per_server = 160;
    const int pointer_per_hash = 4;
    int slot_index = 0;

    RedisProxy proxy;
    proxy.setEventLoop(&listenerLoop);
    loop = &listenerLoop;
    CProxyMonitor monitor;
    proxy.setMonitor(&monitor);

    const int defaultPort = 8221;
    int port = cfg->port();
    if (port <= 0) {
        LOG(Logger::Debug, "Port %d invalid, use default port %d", defaultPort);
        port = defaultPort;
    }

    if (!proxy.run(HostAddress(port))) {
        exit(APP_EXIT_KEY);
    }

    proxy.setTwemproxyModeEnabled(twemproxyMode);

    EventLoopThreadPool pool;
    pool.start(cfg->threadNum());
    proxy.setEventLoopThreadPool(&pool);

    const SVipInfo* vipInfo = cfg->vipInfo();
    proxy.setVipName(vipInfo->if_alias_name);
    proxy.setVipAddress(vipInfo->vip_address);
    proxy.setVipEnabled(vipInfo->enable);

    const SHashInfo* sHashInfo = cfg->hashInfo();

    if (!twemproxyMode) {
        proxy.setSlotCount(sHashInfo->hash_value_max);
    } else {
        proxy.setSlotCount(cfg->groupCnt() * points_per_server);
    }

    const GroupOption* groupOption = cfg->groupOption();
    proxy.setGroupRetryTime(groupOption->group_retry_time);
    proxy.setAutoEjectGroupEnabled(groupOption->auto_eject_group);
    proxy.setEjectAfterRestoreEnabled(groupOption->eject_after_restore);
    proxy.setPassword(cfg->password());

    for (int i = 0; i < cfg->groupCnt(); ++i) {
        const CGroupInfo* info = cfg->group(i);

        RedisServantGroup* group = new RedisServantGroup;
        RedisServantGroupPolicy* policy = RedisServantGroupPolicy::createPolicy(info->groupPolicy());
        group->setGroupName(info->groupName());
        group->setPolicy(policy);

        const HostInfoList& hostList = info->hosts();
        HostInfoList::const_iterator itHost = hostList.begin();
        for (; itHost != hostList.end(); ++itHost) {
            const CHostInfo& hostInfo = (*itHost);
            RedisServant* servant = new RedisServant;
            RedisServant::Option opt;
            strcpy(opt.name, hostInfo.get_hostName().c_str());
            opt.poolSize = hostInfo.get_connectionNum();
            opt.reconnInterval = groupOption->backend_retry_interval;
            opt.maxReconnCount = groupOption->backend_retry_limit;
            servant->setOption(opt);
            servant->setRedisAddress(HostAddress(hostInfo.get_ip().c_str(), hostInfo.get_port()));
            servant->setEventLoop(proxy.eventLoop());
            if (hostInfo.get_master()) {
                group->addMasterRedisServant(servant);
            } else {
                group->addSlaveRedisServant(servant);
            }
            servant->connectionPool()->setPassword(itHost->passWord());
        }
        group->setEnabled(true);
        proxy.addRedisGroup(group);

        if (!twemproxyMode) {
            for (int i = info->hashMin(); i <= info->hashMax(); ++i) {
                proxy.setSlot(i, group);
            }

            for (int i = 0; i < cfg->hashMapCnt(); ++i) {
                const CHashMapping* mapping = cfg->hashMapping(i);
                RedisServantGroup* group = proxy.group(mapping->group_name);
                proxy.setSlot(mapping->hash_value, group);
            }
        } else {
            Slot* slot = proxy.slotData();
            for (int pointer_index = 1;
                    pointer_index <= points_per_server / pointer_per_hash;
                    pointer_index++) {

                char host[86];
                int hostlen = sprintf(host, "%s-%u", group->groupName(), pointer_index - 1);
                for (int x = 0; x < pointer_per_hash; x++) {
                    slot[slot_index].group = group;
                    slot[slot_index++].value = ketama_hash(host, hostlen, x);
                }
            }
        }
    }

    if (twemproxyMode) {
        LOG(Logger::Debug, "Twemproxy mode. dist=ketama slotcount=%d", proxy.slotCount());
        Slot* slot = proxy.slotData();
        int slotCount = proxy.slotCount();
        qsort(slot, slotCount, sizeof(Slot), slot_item_cmp);
    }

    HashFunc func = hashfuncFromName(cfg->hashFunctin().c_str());
    proxy.setHashFunction(func);

    for (int i = 0; i < cfg->keyMapCnt(); ++i) {
        const CKeyMapping* mapping = cfg->keyMapping(i);
        RedisServantGroup* group = proxy.group(mapping->group_name);
        if (group != NULL) {
            proxy.addGroupKeyMapping(mapping->key, strlen(mapping->key), group);
        }
    }

    LOG(Logger::Message, "Start the %s on port %d. PID: %d", APP_NAME, port, getpid());
    listenerLoop.exec();
}
Example #23
0
bool PalmBinaryLoader::loadFromMemory(QByteArray &img)
{
    const int size = img.size();
    m_image        = reinterpret_cast<uint8_t *>(img.data());

    if (static_cast<unsigned long>(size) < sizeof(PRCHeader) + sizeof(PRCRecordList)) {
        LOG_ERROR("This is not a standard .prc file");
        return false;
    }

    PRCHeader *prcHeader = reinterpret_cast<PRCHeader *>(img.data());

    // Check type at offset 0x3C; should be "appl" (or "palm"; ugh!)
    if ((strncmp(prcHeader->type, "appl", 4) != 0) && (strncmp(prcHeader->type, "panl", 4) != 0) &&
        (strncmp(prcHeader->type, "libr", 4) != 0)) {
        LOG_ERROR("This is not a standard .prc file");
        return false;
    }

    addTrapSymbols();

    // Get the number of resource headers (one section per resource)
    PRCRecordList *records = reinterpret_cast<PRCRecordList *>(m_image + sizeof(PRCHeader));
    if (records->nextRecordListOffset != 0) {
        LOG_ERROR("Reading PRC files with multiple record lists is not supported!");
        return false;
    }

    const SWord numSections = Util::readWord(&records->resourceCount, Endian::Big);

    // Iterate through the resource headers (generating section info structs)
    PRCResource *resource = reinterpret_cast<PRCResource *>(m_image + sizeof(PRCHeader) +
                                                            sizeof(PRCRecordList));

    std::vector<SectionProperties> sectionProperties;

    for (unsigned i = 0; i < numSections; i++) {
        char buf[5];
        strncpy(buf, reinterpret_cast<char *>(&resource[i].type), 4);
        buf[4] = 0;

        SWord id         = Util::readWord(&resource[i].id, Endian::Big);
        QString name     = QString("%1%2").arg(buf).arg(id);
        DWord dataOffset = Util::readDWord(&resource[i].dataOffset, Endian::Big);

        Address startAddr(dataOffset);

        if (i > 0) {
            sectionProperties[i - 1].to = startAddr;
        }

        sectionProperties.push_back(
            { name, startAddr, Address::INVALID, HostAddress(m_image + dataOffset) });
    }

    // last section extends until eof
    sectionProperties[numSections - 1].to = Address(size);

    for (SectionProperties props : sectionProperties) {
        assert(props.to != Address::INVALID);
        BinarySection *sect = m_binaryImage->createSection(props.name, props.from, props.to);

        if (sect) {
            // Decide if code or data; note that code0 is a special case (not code)
            sect->setHostAddr(props.hostAddr);
            sect->setCode((props.name != "code0") && (props.name.startsWith("code")));
            sect->setData(props.name.startsWith("data"));
            sect->setEndian(Endian::Little);            // little endian
            sect->setEntrySize(1);                      // No info available
            sect->addDefinedArea(props.from, props.to); // no BSS
        }
    }

    // Create a separate, uncompressed, initialised data section
    BinarySection *dataSection = m_binaryImage->getSectionByName("data0");

    if (dataSection == nullptr) {
        LOG_ERROR("No data section found!");
        return false;
    }

    const BinarySection *code0Section = m_binaryImage->getSectionByName("code0");

    if (code0Section == nullptr) {
        LOG_ERROR("No code 0 section found!");
        return false;
    }

    // When the info is all boiled down, the two things we need from the
    // code 0 section are at offset 0, the size of data above a5, and at
    // offset 4, the size below. Save the size below as a member variable
    m_sizeBelowA5 = UINT4ADDR(code0Section->getHostAddr() + 4);

    // Total size is this plus the amount above (>=) a5
    unsigned sizeData = m_sizeBelowA5 + UINT4ADDR(code0Section->getHostAddr());

    // Allocate a new data section
    m_data = new unsigned char[sizeData];

    if (m_data == nullptr) {
        LOG_FATAL("Could not allocate %1 bytes for data section", sizeData);
    }

    // Uncompress the data. Skip first long (offset of CODE1 "xrefs")
    Byte *p   = reinterpret_cast<Byte *>((dataSection->getHostAddr() + 4).value());
    int start = static_cast<int>(UINT4(p));
    p += 4;
    unsigned char *q = (m_data + m_sizeBelowA5 + start);
    bool done        = false;

    while (!done && (p < reinterpret_cast<unsigned char *>(
                             (dataSection->getHostAddr() + dataSection->getSize()).value()))) {
        unsigned char rle = *p++;

        if (rle == 0) {
            done = true;
            break;
        }
        else if (rle == 1) {
            // 0x01 b_0 b_1
            // => 0x00 0x00 0x00 0x00 0xFF 0xFF b_0 b_1
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = 0xFF;
            *q++ = 0xFF;
            *q++ = *p++;
            *q++ = *p++;
        }
        else if (rle == 2) {
            // 0x02 b_0 b_1 b_2
            // => 0x00 0x00 0x00 0x00 0xFF b_0 b_1 b_2
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = 0xFF;
            *q++ = *p++;
            *q++ = *p++;
            *q++ = *p++;
        }
        else if (rle == 3) {
            // 0x03 b_0 b_1 b_2
            // => 0xA9 0xF0 0x00 0x00 b_0 b_1 0x00 b_2
            *q++ = 0xA9;
            *q++ = 0xF0;
            *q++ = 0x00;
            *q++ = 0x00;
            *q++ = *p++;
            *q++ = *p++;
            *q++ = 0x00;
            *q++ = *p++;
        }
        else if (rle == 4) {
            // 0x04 b_0 b_1 b_2 b_3
            // => 0xA9 axF0 0x00 b_0 b_1 b_3 0x00 b_3
            *q++ = 0xA9;
            *q++ = 0xF0;
            *q++ = 0x00;
            *q++ = *p++;
            *q++ = *p++;
            *q++ = *p++;
            *q++ = 0x00;
            *q++ = *p++;
        }
        else if (rle < 0x10) {
            // 5-0xF are invalid.
            assert(false);
        }
        else if (rle >= 0x80) {
            // n+1 bytes of literal data
            for (int k = 0; k <= (rle - 0x80); k++) {
                *q++ = *p++;
            }
        }
        else if (rle >= 40) {
            // n+1 repetitions of 0
            for (int k = 0; k <= (rle - 0x40); k++) {
                *q++ = 0x00;
            }
        }
        else if (rle >= 20) {
            // n+2 repetitions of b
            unsigned char b = *p++;

            for (int k = 0; k < (rle - 0x20 + 2); k++) {
                *q++ = b;
            }
        }
        else {
            // 0x10: n+1 repetitions of 0xFF
            for (int k = 0; k <= (rle - 0x10); k++) {
                *q++ = 0xFF;
            }
        }
    }

    if (!done) {
        LOG_WARN("Compressed data section premature end");
    }

    LOG_VERBOSE("Used %1 bytes of %2 in decompressing data section",
                p - reinterpret_cast<unsigned char *>(dataSection->getHostAddr().value()),
                dataSection->getSize());

    // Replace the data pointer and size with the uncompressed versions

    dataSection->setHostAddr(HostAddress(m_data));
    dataSection->resize(sizeData);

    m_symbols->createSymbol(getMainEntryPoint(), "PilotMain")->setAttribute("EntryPoint", true);
    return true;
}
Example #24
0
// 
// Made by loick michard
// Login   <*****@*****.**>
// 
// Started on  Tue Dec 18 15:51:08 2012 loick michard
//

#include "OS.h"
#if defined(OS_WINDOWS)
# include <winsock2.h>
#else
# include <arpa/inet.h>
#endif
#include "HostAddress.h"

Network::HostAddress Network::HostAddress::AnyAddress = HostAddress(INADDR_ANY);

Network::HostAddress::HostAddress(const std::string& address) {
  _address = inet_addr(address.c_str());
}

Network::HostAddress::HostAddress(uint32 address) {
  _address = htonl(address);
}

uint32 Network::HostAddress::toIPv4Address() const {
  return _address;
}

std::string Network::HostAddress::getString() const {
  in_addr address;
void AvahiResolveHostnameQuery::run() {
    eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>(HostAddress(hostname))), shared_from_this());
}