コード例 #1
0
ファイル: NetAddress.cpp プロジェクト: 090809/TrinityCore
void NetAddress::serialize(class BinaryOutput& b) const {
    b.writeUInt32(ip());
    b.writeUInt16(port());
}
コード例 #2
0
/*!
 * \reimp
 */
bool QxtHttpSessionManager::start()
{
    Q_ASSERT(qxt_d().connector);
    return connector()->listen(listenInterface(), port());
}
コード例 #3
0
ファイル: hostandport.cpp プロジェクト: mongodb/mongo
bool HostAndPort::operator<(const HostAndPort& r) const {
    const int cmp = host().compare(r.host());
    if (cmp)
        return cmp < 0;
    return port() < r.port();
}
コード例 #4
0
ファイル: EClientSocket.cpp プロジェクト: arvicco/ib-ruby
bool EClientSocket::eConnectImpl(int clientId, bool extraAuth, ConnState* stateOutPt)
{
	// resolve host
	struct hostent* hostEnt = gethostbyname( host().c_str());
	if ( !hostEnt) {
		getWrapper()->error( NO_VALID_ID, CONNECT_FAIL.code(), CONNECT_FAIL.msg());
		return false;
	}

	// create socket
	m_fd = socket(AF_INET, SOCK_STREAM, 0);

	// cannot create socket
	if( m_fd < 0) {
		getWrapper()->error( NO_VALID_ID, FAIL_CREATE_SOCK.code(), FAIL_CREATE_SOCK.msg());
		return false;
	}

	// starting to connect to server
	struct sockaddr_in sa;
	memset( &sa, 0, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port = htons( port());
	sa.sin_addr.s_addr = ((in_addr*)hostEnt->h_addr)->s_addr;

	// try to connect
	if( (connect( m_fd, (struct sockaddr *) &sa, sizeof( sa))) < 0) {
		// error connecting
		SocketClose( m_fd);
		m_fd = -1;
		getWrapper()->error( NO_VALID_ID, CONNECT_FAIL.code(), CONNECT_FAIL.msg());
		return false;
	}

    getTransport()->fd(m_fd);

	// set client id
	setClientId( clientId);
	setExtraAuth( extraAuth);

    int res = sendConnectRequest();

    if (res < 0 && !handleSocketError())
        return false;

	if( !isConnected()) {
		if( connState() != CS_DISCONNECTED) {
			assert( connState() == CS_REDIRECT);
			if( stateOutPt) {
				*stateOutPt = connState();
			}
			eDisconnect();
		}
		return false;
	}

	// set socket to non-blocking state
	if ( !SetSocketNonBlocking(m_fd)) {
	// error setting socket to non-blocking
		eDisconnect();
		getWrapper()->error( NO_VALID_ID, CONNECT_FAIL.code(), CONNECT_FAIL.msg());
		return false;
	}

	assert( connState() == CS_CONNECTED);
	if( stateOutPt) {
		*stateOutPt = connState();
	}
            
    if (!m_asyncEConnect) {
        EReader reader(this, m_pSignal);

        while (m_pSignal && !m_serverVersion && isSocketOK()) {
            reader.checkClient();
            m_pSignal->waitForSignal();
            reader.processMsgs();
        }
    }

	// successfully connected
	return isSocketOK();
}
コード例 #5
0
int ONVIF::AudioEncoderConfiguration::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 13)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 13;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 13)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 13;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QString*>(_v) = token(); break;
        case 1: *reinterpret_cast< QString*>(_v) = name(); break;
        case 2: *reinterpret_cast< int*>(_v) = useCount(); break;
        case 3: *reinterpret_cast< QString*>(_v) = encoding(); break;
        case 4: *reinterpret_cast< int*>(_v) = bitrate(); break;
        case 5: *reinterpret_cast< int*>(_v) = sampleRate(); break;
        case 6: *reinterpret_cast< QString*>(_v) = type(); break;
        case 7: *reinterpret_cast< QString*>(_v) = ipv4Address(); break;
        case 8: *reinterpret_cast< QString*>(_v) = ipv6Address(); break;
        case 9: *reinterpret_cast< int*>(_v) = port(); break;
        case 10: *reinterpret_cast< int*>(_v) = ttl(); break;
        case 11: *reinterpret_cast< bool*>(_v) = autoStart(); break;
        case 12: *reinterpret_cast< QString*>(_v) = sessionTimeout(); break;
        default: break;
        }
        _id -= 13;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setToken(*reinterpret_cast< QString*>(_v)); break;
        case 1: setName(*reinterpret_cast< QString*>(_v)); break;
        case 2: setUseCount(*reinterpret_cast< int*>(_v)); break;
        case 3: setEncoding(*reinterpret_cast< QString*>(_v)); break;
        case 4: setBitrate(*reinterpret_cast< int*>(_v)); break;
        case 5: setSampleRate(*reinterpret_cast< int*>(_v)); break;
        case 6: setType(*reinterpret_cast< QString*>(_v)); break;
        case 7: setIpv4Address(*reinterpret_cast< QString*>(_v)); break;
        case 8: setIpv6Address(*reinterpret_cast< QString*>(_v)); break;
        case 9: setPort(*reinterpret_cast< int*>(_v)); break;
        case 10: setTtl(*reinterpret_cast< int*>(_v)); break;
        case 11: setAutoStart(*reinterpret_cast< bool*>(_v)); break;
        case 12: setSessionTimeout(*reinterpret_cast< QString*>(_v)); break;
        default: break;
        }
        _id -= 13;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 13;
    } else if (_c == QMetaObject::RegisterPropertyMetaType) {
        if (_id < 13)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 13;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
コード例 #6
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
IPSockAddress IPSockAddress::defaults(IPPort defaultPort) const
{
    return IPSockAddress(address(), port() ? port() : defaultPort);
}
コード例 #7
0
ファイル: IPEndpoint.test.cpp プロジェクト: bachase/rippled
    void testEndpoint ()
    {
        testcase ("Endpoint");

        {
            std::pair <Endpoint, bool> result (
                Endpoint::from_string_checked ("1.2.3.4"));
            expect (result.second);
            if (expect (result.first.address().is_v4 ()))
            {
                expect (result.first.address().to_v4() ==
                    AddressV4 (1, 2, 3, 4));
                expect (result.first.port() == 0);
                expect (to_string (result.first) == "1.2.3.4");
            }
        }

        {
            std::pair <Endpoint, bool> result (
                Endpoint::from_string_checked ("1.2.3.4:5"));
            expect (result.second);
            if (expect (result.first.address().is_v4 ()))
            {
                expect (result.first.address().to_v4() ==
                    AddressV4 (1, 2, 3, 4));
                expect (result.first.port() == 5);
                expect (to_string (result.first) == "1.2.3.4:5");
            }
        }

        Endpoint ep;

        ep = Endpoint (AddressV4 (127,0,0,1), 80);
        expect (! is_unspecified (ep));
        expect (! is_public (ep));
        expect (  is_private (ep));
        expect (! is_multicast (ep));
        expect (  is_loopback (ep));
        expect (to_string (ep) == "127.0.0.1:80");

        ep = Endpoint (AddressV4 (10,0,0,1));
        expect (AddressV4::get_class (ep.to_v4()) == 'A');
        expect (! is_unspecified (ep));
        expect (! is_public (ep));
        expect (  is_private (ep));
        expect (! is_multicast (ep));
        expect (! is_loopback (ep));
        expect (to_string (ep) == "10.0.0.1");

        ep = Endpoint (AddressV4 (166,78,151,147));
        expect (! is_unspecified (ep));
        expect (  is_public (ep));
        expect (! is_private (ep));
        expect (! is_multicast (ep));
        expect (! is_loopback (ep));
        expect (to_string (ep) == "166.78.151.147");

        {
            ep = Endpoint::from_string ("192.0.2.112");
            expect (! is_unspecified (ep));
            expect (ep == Endpoint::from_string_altform ("192.0.2.112"));

            auto const ep1 = Endpoint::from_string ("192.0.2.112:2016");
            expect (! is_unspecified (ep1));
            expect (ep.address() == ep1.address());
            expect (ep1.port() == 2016);

            auto const ep2 =
                Endpoint::from_string_altform ("192.0.2.112:2016");
            expect (! is_unspecified (ep2));
            expect (ep.address() == ep2.address());
            expect (ep2.port() == 2016);
            expect (ep1 == ep2);

            auto const ep3 =
                Endpoint::from_string_altform ("192.0.2.112 2016");
            expect (! is_unspecified (ep3));
            expect (ep.address() == ep3.address());
            expect (ep3.port() == 2016);
            expect (ep2 == ep3);

            auto const ep4 =
                Endpoint::from_string_altform ("192.0.2.112     2016");
            expect (! is_unspecified (ep4));
            expect (ep.address() == ep4.address());
            expect (ep4.port() == 2016);
            expect (ep3 == ep4);

            expect (to_string(ep1) == to_string(ep2));
            expect (to_string(ep1) == to_string(ep3));
            expect (to_string(ep1) == to_string(ep4));
        }

        // Failures:
        expect (is_unspecified (
            Endpoint::from_string ("192.0.2.112:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("192.0.2.112:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("192.0.2.112 port")));

        expect (is_unspecified (
            Endpoint::from_string ("ip:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("ip:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("ip port")));

        expect (is_unspecified (
            Endpoint::from_string("")));
        expect (is_unspecified (
            Endpoint::from_string_altform("")));

        expect (is_unspecified (
            Endpoint::from_string("255")));
        expect (is_unspecified (
            Endpoint::from_string_altform("255")));

        expect (is_unspecified (
            Endpoint::from_string("512")));
        expect (is_unspecified (
            Endpoint::from_string_altform("512")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3.256")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3.256")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3:80")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3:80")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3 80")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3.4:65536")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3:65536")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3 65536")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3.4:89119")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3:89119")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3 89119")));
    }
コード例 #8
0
ファイル: IPEndPoint.cpp プロジェクト: DrDrake/mcore3d
bool IPEndPoint::operator==(const IPEndPoint& rhs) const {
	return mAddress == rhs.mAddress && port() == rhs.port();
}
コード例 #9
0
ファイル: clip.cpp プロジェクト: JohanAberg/Ramen
OFX::Host::ImageEffect::Image* clip_t::get_input_image( OfxTime time, OfxRectD *optionalBounds)
{
    assert( node());
    assert( node()->composition());

    node_t *in = node()->input( port());

    if( !in)
	return 0;

    render::render_context_t context = node()->render_context();

    context.composition = node()->composition();
    context.result_node = in;
    context.time = time;

    Imath::Box2i area;

    if( optionalBounds)
    {
        // TODO: is this correct if the effect does not support tiles?
	area = Imath::Box2i( Imath::V2i( optionalBounds->x1, optionalBounds->y1), Imath::V2i( optionalBounds->x2 - 1, optionalBounds->y2 - 1));
	area = node()->vertical_flip_box( area);
    }
    else
        area = scale( node()->defined(), context.subsample);

    render::renderer_t r( context, true, false);
    r.render( area);

    if( optionalBounds)
    {
	area.min.x = optionalBounds->x1;
	area.min.y = optionalBounds->y1;
	area.max.x = optionalBounds->x2 - 1;
	area.max.y = optionalBounds->y2 - 1;
	area = node()->vertical_flip_box( area);
	area = intersect( in->defined(), area);
    }
    else
	area = in->defined();

    if( area.isEmpty())
	return 0;

    image::image_buffer_t pixels = in->image();
    image::const_image_view_t view( in->const_subimage_view( area));

    int rowbytes;
    void *ptr = view_get_ptr_and_stride( view, rowbytes);

    area = node()->vertical_flip_box( area);

    OfxRectI bounds;
    bounds.x1 = area.min.x;
    bounds.y1 = area.min.y;
    bounds.x2 = area.max.x + 1;
    bounds.y2 = area.max.y + 1;

    std::stringstream s;
    for( int i = 0; i < 16; ++i)
	s << (int) in->digest()[i];

    input_image_t *result = new input_image_t( *this, pixels, 1.0 / node()->render_context().subsample, ptr, bounds, bounds, rowbytes, s.str());
    in->release_image();
    return result;
}
コード例 #10
0
ファイル: IPEndPoint.cpp プロジェクト: DrDrake/mcore3d
void IPEndPoint::setAddress(const IPAddress& address) {
	uint16_t p = port();
	mAddress = address;
	setPort(p);
}
コード例 #11
0
ファイル: IPEndPoint.cpp プロジェクト: DrDrake/mcore3d
std::string IPEndPoint::getString() const {
	std::stringstream ss;
	ss << mAddress.getString() << ":" << port();
	return ss.str();
}
コード例 #12
0
ファイル: main.cpp プロジェクト: kierzek/MUFINS
int main(int argc, char** argv) {
    if (argc != 3 && argc != 5 && argc != 6) {
        cout << VERSION << endl;
        cout << "USAGE FOR STANDALONE: qsspn qsspn_file ctrl_file" << endl;
        cout << "USAGE FOR SERVER: qsspn qsspn_file ctrl_file address port cache_size" << endl;
        cout << "USAGE FOR CLIENT: qsspn qsspn_file ctrl_file address port" << endl;
        cout << "The qsspn_file file with extension .json is read as Json file" << endl;
        cout << "The qsspn file without .json extension is assumed to be in old qsspn format" << endl;
        cout << "Example cache size is 100000000" << endl;
        exit(1);
    }

    if (argc == 3) {//standalone
        PetriNet *pn = new PetriNet();
        string path(argv[1]);
        string path1(argv[2]);
        if (isJason(path)) {
            pn->readModel(path);
        } else {
            pn->readPetriNet(path);
        }
        pn->runWorkflowStandalone(path1);
        exit(0);
    } else if (argc == 5) {//client
        PetriNet *pn = new PetriNet();
        string path(argv[1]);
        string path1(argv[2]);
        string serverAddress(argv[3]);
        string serverPort(argv[4]);
        if (isJason(path)) {
            pn->readModel(path);
        } else {
            pn->readPetriNet(path);
        }
       pn->runWorkflowClient(path1, serverAddress, serverPort);
        exit(0);
    } else try {//server
        string path(argv[1]);
        string path1(argv[2]);
        string address(argv[3]);
        string port(argv[4]);
        int cache_size = atoi(argv[5]);

        Cache *cache = new Cache(cache_size);
        PetriNet *pn = new PetriNet();
        if (isJason(path)) {
            pn->readModel(path);
        } else {
            pn->readPetriNet(path);
        }

        fstream infile;
        string word;
        vector<string> text;

        infile.open(path1.c_str());
        if (!infile) {
            cerr << "Could not open file:" << path1 << endl;
            exit(0);
        }

        while (infile >> word) text.push_back(word);
        infile.close();

        asio::io_service io_service;

        MetabolismServer server(address, port, io_service, 1, pn, cache, text);

        server.run();

        delete pn;
        delete cache;
    } catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}
コード例 #13
0
ファイル: ksockaddr.cpp プロジェクト: serghei/kde3-kdelibs
QString KInetSocketAddress::serviceName() const
{
    return QString::number(port());
}
コード例 #14
0
 std::string socket_address::location() const
 {
     return host() + ":" + ak::cast<std::string>(port());
 }
コード例 #15
0
ファイル: mcdx.c プロジェクト: smx-smx/dsl-n55u
static int __init mcdx_init_drive(int drive)
{
	struct s_version version;
	struct gendisk *disk;
	struct s_drive_stuff *stuffp;
	int size = sizeof(*stuffp);
	char msg[80];

	xtrace(INIT, "init() try drive %d\n", drive);

	xtrace(INIT, "kmalloc space for stuffpt's\n");
	xtrace(MALLOC, "init() malloc %d bytes\n", size);
	if (!(stuffp = kzalloc(size, GFP_KERNEL))) {
		xwarn("init() malloc failed\n");
		return 1;
	}

	disk = alloc_disk(1);
	if (!disk) {
		xwarn("init() malloc failed\n");
		kfree(stuffp);
		return 1;
	}

	xtrace(INIT, "init() got %d bytes for drive stuff @ %p\n",
	       sizeof(*stuffp), stuffp);

	/* set default values */
	stuffp->present = 0;	/* this should be 0 already */
	stuffp->toc = NULL;	/* this should be NULL already */

	/* setup our irq and i/o addresses */
	stuffp->irq = irq(mcdx_drive_map[drive]);
	stuffp->wreg_data = stuffp->rreg_data = port(mcdx_drive_map[drive]);
	stuffp->wreg_reset = stuffp->rreg_status = stuffp->wreg_data + 1;
	stuffp->wreg_hcon = stuffp->wreg_reset + 1;
	stuffp->wreg_chn = stuffp->wreg_hcon + 1;

	init_waitqueue_head(&stuffp->busyq);
	init_waitqueue_head(&stuffp->lockq);
	init_waitqueue_head(&stuffp->sleepq);

	/* check if i/o addresses are available */
	if (!request_region(stuffp->wreg_data, MCDX_IO_SIZE, "mcdx")) {
		xwarn("0x%03x,%d: Init failed. "
		      "I/O ports (0x%03x..0x%03x) already in use.\n",
		      stuffp->wreg_data, stuffp->irq,
		      stuffp->wreg_data,
		      stuffp->wreg_data + MCDX_IO_SIZE - 1);
		xtrace(MALLOC, "init() free stuffp @ %p\n", stuffp);
		kfree(stuffp);
		put_disk(disk);
		xtrace(INIT, "init() continue at next drive\n");
		return 0;	/* next drive */
	}

	xtrace(INIT, "init() i/o port is available at 0x%03x\n"
	       stuffp->wreg_data);
	xtrace(INIT, "init() hardware reset\n");
	mcdx_reset(stuffp, HARD, 1);

	xtrace(INIT, "init() get version\n");
	if (-1 == mcdx_requestversion(stuffp, &version, 4)) {
		/* failed, next drive */
		release_region(stuffp->wreg_data, MCDX_IO_SIZE);
		xwarn("%s=0x%03x,%d: Init failed. Can't get version.\n",
		      MCDX, stuffp->wreg_data, stuffp->irq);
		xtrace(MALLOC, "init() free stuffp @ %p\n", stuffp);
		kfree(stuffp);
		put_disk(disk);
		xtrace(INIT, "init() continue at next drive\n");
		return 0;
	}

	switch (version.code) {
	case 'D':
		stuffp->readcmd = READ2X;
		stuffp->present = DOUBLE | DOOR | MULTI;
		break;
	case 'F':
		stuffp->readcmd = READ1X;
		stuffp->present = SINGLE | DOOR | MULTI;
		break;
	case 'M':
		stuffp->readcmd = READ1X;
		stuffp->present = SINGLE;
		break;
	default:
		stuffp->present = 0;
		break;
	}

	stuffp->playcmd = READ1X;

	if (!stuffp->present) {
		release_region(stuffp->wreg_data, MCDX_IO_SIZE);
		xwarn("%s=0x%03x,%d: Init failed. No Mitsumi CD-ROM?.\n",
		      MCDX, stuffp->wreg_data, stuffp->irq);
		kfree(stuffp);
		put_disk(disk);
		return 0;	/* next drive */
	}

	xtrace(INIT, "init() register blkdev\n");
	if (register_blkdev(MAJOR_NR, "mcdx")) {
		release_region(stuffp->wreg_data, MCDX_IO_SIZE);
		kfree(stuffp);
		put_disk(disk);
		return 1;
	}

	mcdx_queue = blk_init_queue(do_mcdx_request, &mcdx_lock);
	if (!mcdx_queue) {
		unregister_blkdev(MAJOR_NR, "mcdx");
		release_region(stuffp->wreg_data, MCDX_IO_SIZE);
		kfree(stuffp);
		put_disk(disk);
		return 1;
	}

	xtrace(INIT, "init() subscribe irq and i/o\n");
	if (request_irq(stuffp->irq, mcdx_intr, IRQF_DISABLED, "mcdx", stuffp)) {
		release_region(stuffp->wreg_data, MCDX_IO_SIZE);
		xwarn("%s=0x%03x,%d: Init failed. Can't get irq (%d).\n",
		      MCDX, stuffp->wreg_data, stuffp->irq, stuffp->irq);
		stuffp->irq = 0;
		blk_cleanup_queue(mcdx_queue);
		kfree(stuffp);
		put_disk(disk);
		return 0;
	}

	xtrace(INIT, "init() get garbage\n");
	{
		int i;
		mcdx_delay(stuffp, HZ / 2);
		for (i = 100; i; i--)
			(void) inb(stuffp->rreg_status);
	}


#ifdef WE_KNOW_WHY
	/* irq 11 -> channel register */
	outb(0x50, stuffp->wreg_chn);
#endif

	xtrace(INIT, "init() set non dma but irq mode\n");
	mcdx_config(stuffp, 1);

	stuffp->info.ops = &mcdx_dops;
	stuffp->info.speed = 2;
	stuffp->info.capacity = 1;
	stuffp->info.handle = stuffp;
	sprintf(stuffp->info.name, "mcdx%d", drive);
	disk->major = MAJOR_NR;
	disk->first_minor = drive;
	strcpy(disk->disk_name, stuffp->info.name);
	disk->fops = &mcdx_bdops;
	disk->flags = GENHD_FL_CD;
	stuffp->disk = disk;

	sprintf(msg, " mcdx: Mitsumi CD-ROM installed at 0x%03x, irq %d."
		" (Firmware version %c %x)\n",
		stuffp->wreg_data, stuffp->irq, version.code, version.ver);
	mcdx_stuffp[drive] = stuffp;
	xtrace(INIT, "init() mcdx_stuffp[%d] = %p\n", drive, stuffp);
	if (register_cdrom(&stuffp->info) != 0) {
		printk("Cannot register Mitsumi CD-ROM!\n");
		free_irq(stuffp->irq, NULL);
		release_region(stuffp->wreg_data, MCDX_IO_SIZE);
		kfree(stuffp);
		put_disk(disk);
		if (unregister_blkdev(MAJOR_NR, "mcdx") != 0)
			xwarn("cleanup() unregister_blkdev() failed\n");
		blk_cleanup_queue(mcdx_queue);
		return 2;
	}
	disk->private_data = stuffp;
	disk->queue = mcdx_queue;
	add_disk(disk);
	printk(msg);
	return 0;
}
コード例 #16
0
	    bool Connection::isHandled(HttpRequest &req)
        {
			return active() && req.url().scheme() == scheme() && req.url().host() == host() &&
				(req.url().port() == port() || (req.url().port() == 0 && port() == 443));
        }
コード例 #17
0
ファイル: main.cpp プロジェクト: toddwithers/Bot
// This is our botting thread
void *main_thread( void *arg ) {
	
// NPC details
// ModelInfo - Model: 496, Weapon: 85, Shield: 0, Helmet: 0, Color: 0199
// ModelInfo - Model: 496, Weapon: 85, Shield: 0, Helmet: 0, Color: 0344
	uint16 quest_giver = 0;
	uint16 other_guard = 0;


	int xs[] = { 1343, 1338, 1343, 1348, 1354, 1358, 1354, 1354, 1354, 1358, 1354, 1348, 1343, 1338, 1343, 1343 };
	int ys[] = {  888,  884,  888,  888,  888,  884,  888,  893,  899,  904,  899,  899,  899,  904,  899,  893 };

	int total = 0;

	while( !exit_bot ) {
		// Make sure we are logged in before we continue
		while( !loggedin ) {
			SLEEP( 1000 );
		}

		have_quest = false;

		requestLog( player_id );
		SLEEP( 5000 );

		if( !have_quest && lastQL.curquest != 0x57 ) {
			port( player_id, 2 );

			SLEEP( 2000 );

			transXY( player_id, ( 758 + rand()%2 ), ( 2333 + rand()%2 ));

			SLEEP( 1500 );

			/*while( 1 ) {
				for( auto& x: um_units ) {
					printf(  "Player: %i | X,Y: %i,%i | ModelInfo - Model: %i, Weapon: %i, Shield: %i, Helmet: %i, Color: %04X\n", 
						x.second.id, x.second.movement.positionX, x.second.movement.positionY, x.second.models.model, x.second.models.weapon, x.second.models.shield, x.second.models.helmet, x.second.models.colorbits );
				}
				fprintf( out, "\n" );
				SLEEP( 2000 );
			}*/

			other_guard = 0;
			while( other_guard == 0 ) {
				other_guard = locateUnit( 496, 85, 0, 0, 0x0244 );
				SLEEP( 1000 );
			}

			while( um_units.count( other_guard ) == 0 ) {
				SLEEP( 1000 );
			}

			clickUnit( player_id, other_guard, um_units[ other_guard ].movement.positionY );
			SLEEP( 2000 );

			Say( player_id, (char*)"Pix Animus Task", 15 );
			SLEEP( 2000 );
			Say( player_id, (char*)"OK", 2 );
			SLEEP( 2000 );
			Say( player_id, (char*)"-quitquest", 10 );
			SLEEP( 2000 );

			transXY( player_id, ( 762 + rand()%3 ), 2329 );
			SLEEP( 2000 );

			quest_giver = 0;
			while( quest_giver == 0 ) {
				quest_giver = locateUnit( 496, 85, 0, 0, 0x0099 );
				SLEEP( 1000 );
			}

			while( um_units.count( quest_giver ) == 0 ) {
				SLEEP( 1000 );
			}

			clickUnit( player_id, quest_giver, um_units[ quest_giver ].movement.positionY );
			SLEEP( 2000 );

			Say( player_id, (char*)"warlock task", 12 );
			SLEEP( 2000 );

			Say( player_id, (char*)"OK", 2 );
			SLEEP( 2000 );
		} else {
			port( player_id, 8 );
			SLEEP( 2000 );
		}

		port( player_id, 7 );
		SLEEP( 2000 );
		

		finished_quest = false;
		missing_quest  = false;

		createSkelly( player_id, 1346, 896 );
		SLEEP( 1500 );
		createSkelly( player_id, 1348, 896 );
		SLEEP( 1500 );

		Say( player_id, (char*)"-battle", 7 );
		SLEEP( 1500 );

		int index = 0;
		while( !finished_quest ) {
			if( aliveUnitsRadius( 200 )) {
				rotFlesh( player_id );
				SLEEP( 1000 );
			}
			transXY( player_id, xs[ index ], ys[ index ] );
			SLEEP( 1000 );
			if( !CheckRadius(( xs[ index ] * 20 ), ( ys[ index ] * 20 ), player_x, player_y, 200 )) {
				printf( "[%s] Radius check failed. Restart everything: %i/%i %i/%i\n", currentDateTime().c_str(), ( xs[ index ] * 20 ), ( ys[ index ] * 20 ), player_x, player_y );
				Say( player_id, (char*)"-quitquest", 10 );
				SLEEP( 1000 );
				finished_quest = true;
				missing_quest  = true;
			}
			if( index == 15 ) {
				index = 0;
				if(( rand()%5 ) == 3 ) {
					Say( player_id, (char*)"-battle", 7 );
					SLEEP( 500 );
				}

				requestLog( player_id );
				SLEEP( 500 );
			} else {
				index++;
			}
		}

		if( !missing_quest ) {
			Say( player_id, (char*)"-destroy", 8 );
			SLEEP( 2000 );

			port( player_id, 2 );
			SLEEP( 2000 );

			quest_giver = 0;
			while( quest_giver == 0 ) {
				quest_giver = locateUnit( 496, 85, 0, 0, 0x0099 );
				SLEEP( 1000 );
			}

			while( um_units.count( quest_giver ) == 0 ) {
				SLEEP( 1000 );
			}

			clickUnit( player_id, quest_giver, um_units[ quest_giver ].movement.positionY );
			SLEEP( 2000 );

			port( player_id, 8 );
			SLEEP( 10000 );


			total++;

			printf( "[%s] Quest Done. #%i\n", currentDateTime().c_str(), total );
		}
	}

	//SLEEP( 10000 );

}
コード例 #18
0
ファイル: RunFlightList.cpp プロジェクト: davidswelt/XCSoar
int main(int argc, char **argv)
{
  if (argc != 4) {
    fprintf(stderr, "Usage: %s DRIVER PORT BAUD\n"
            "Where DRIVER is one of:\n", argv[0]);

    const struct DeviceRegister *driver;
    for (unsigned i = 0; (driver = GetDriverByIndex(i)) != NULL; ++i)
      if (driver->IsLogger())
        _ftprintf(stderr, _T("\t%s\n"), driver->name);

    return EXIT_FAILURE;
  }

  PathName driver_name(argv[1]);
  PathName port_name(argv[2]);

  DeviceConfig config;
  config.Clear();
  config.baud_rate = atoi(argv[3]);

#ifdef HAVE_POSIX
  TTYPort port(port_name, config.baud_rate, *(Port::Handler *)NULL);
#else
  SerialPort port(port_name, config.baud_rate, *(Port::Handler *)NULL);
#endif
  if (!port.Open()) {
    fprintf(stderr, "Failed to open COM port\n");
    return EXIT_FAILURE;
  }

  ConsoleOperationEnvironment env;
  RecordedFlightList flight_list;
  const struct DeviceRegister *driver = FindDriverByName(driver_name);
  if (driver == NULL) {
    fprintf(stderr, "No such driver: %s\n", argv[1]);
    return EXIT_FAILURE;
  }

  if (!driver->IsLogger()) {
    fprintf(stderr, "Not a logger driver: %s\n", argv[1]);
    return EXIT_FAILURE;
  }

  assert(driver->CreateOnPort != NULL);
  Device *device = driver->CreateOnPort(config, port);
  assert(device != NULL);

  if (!device->Open(env)) {
    delete device;
    fprintf(stderr, "Failed to open driver: %s\n", argv[1]);
    return EXIT_FAILURE;
  }

  if (!device->EnableDownloadMode()) {
    delete device;
    fprintf(stderr, "Failed to enable download mode\n");
    return EXIT_FAILURE;
  }

  if (!device->ReadFlightList(flight_list, env)) {
    device->DisableDownloadMode();
    delete device;
    fprintf(stderr, "Failed to download flight list\n");
    return EXIT_FAILURE;
  }

  device->DisableDownloadMode();
  delete device;

  for (auto i = flight_list.begin(); i != flight_list.end(); ++i) {
    const RecordedFlightInfo &flight = *i;
    printf("%04u/%02u/%02u %02u:%02u-%02u:%02u\n",
           flight.date.year, flight.date.month, flight.date.day,
           flight.start_time.hour, flight.start_time.minute,
           flight.end_time.hour, flight.end_time.minute);
  }
}
コード例 #19
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
IPSockAddress::operator string () const
{
    char buffer[4*(3+1)+5+1];	// nnn.nnn.nnn.nnn:ppppp
    snprintf(buffer, sizeof(buffer), "%s:%d", string(address()).c_str(), port());
    return buffer;
}
コード例 #20
0
/**
 * Node entry-point. Handles ROS setup, and serial port connection/reconnection.
 */
int main(int argc, char **argv)
{
  //ros::init(argc, argv, "um7_driver");

    using_shared_memory();

  // Load parameters from private node handle.
  std::string port("/dev/robot/imu");
  int32_t baud = 115200;
  //ros::param::param<std::string>("~port", port, "/dev/ttyUSB0");
  //ros::param::param<int32_t>("~baud", baud, 115200);

  serial::Serial ser;
  ser.setPort(port);
  ser.setBaudrate(baud);
  serial::Timeout to = serial::Timeout(50, 50, 0, 50, 0);
  ser.setTimeout(to);

  //ros::NodeHandle n;
  //std_msgs::Header header;
  //ros::param::param<std::string>("~frame_id", header.frame_id, "imu_link");

  // Initialize covariance. The UM7 sensor does not provide covariance values so,
  //   by default, this driver provides a covariance array of all zeros indicating
  //   "covariance unknown" as advised in sensor_msgs/Imu.h.
  // This param allows the user to specify alternate covariance values if needed.

//  std::string covariance;
//  char cov[200];
//  char *ptr1;

//  ros::param::param<std::string>("~covariance", covariance, "0 0 0 0 0 0 0 0 0");
//  snprintf(cov, sizeof(cov), "%s", covariance.c_str());

//  char* p = strtok_r(cov, " ", &ptr1);           // point to first value
//  for (int iter = 0; iter < 9; iter++)
//  {
//    if (p) covar[iter] = atof(p);                // covar[] is global var
//    else  covar[iter] = 0.0;
//    p = strtok_r(NULL, " ", &ptr1);              // point to next value (nil if none)
//  }

  // Real Time Loop
  bool first_failure = true;
  while (1)
  {
    try
    {
      ser.open();
    }
    catch(const serial::IOException& e)
    {
      std::cout<<"Unable to connect to port."<<std::endl;
    }
    if (ser.isOpen())
    {
      std::cout<<"Successfully connected to serial port."<<std::endl;
      first_failure = true;
      try
      {
        um7::Comms sensor(&ser);
        configureSensor(&sensor);
        um7::Registers registers;
        //ros::ServiceServer srv = n.advertiseService<um7::Reset::Request, um7::Reset::Response>(
        //    "reset", boost::bind(handleResetService, &sensor, _1, _2));
		handleResetService(&sensor);
        int t=0;
        int contador = 0;
        float med_accel_z = 0, ac_med_accel_z = 0;
        while (1)
        {
            //--------- calcula a média do accel em Z-----------------------------
            if(contador>=40)
            {
                med_accel_z = ac_med_accel_z/40; // calcula a média do accel em Z
                contador = 0;
                ac_med_accel_z = 0;
            }
            ac_med_accel_z = ac_med_accel_z + IMU_ACCEL_Z;
            contador++;
            //--------------------------------------------------------------------

            if(med_accel_z>0.70) // Identifica se o robô esta caido ou em pé
                IMU_STATE = 0; // Robo caido
            else
                IMU_STATE = 1; // Robo em pé

            if(t>20)
            {

            std::cout<<"Robo caido = "<<std::fixed<<IMU_STATE<<std::endl;
            std::cout<<"med_acc_z = "<<std::fixed<<med_accel_z<<std::endl;
            std::cout<<"giros_x = "<<std::fixed<<IMU_GYRO_X<<std::endl;
            std::cout<<"giros_y = "<<std::fixed<<IMU_GYRO_Y<<std::endl;
            std::cout<<"giros_z = "<<std::fixed<<IMU_GYRO_Z<<std::endl;

            std::cout<<"accel_x = "<<std::fixed<<IMU_ACCEL_X<<std::endl;
            std::cout<<"accel_y = "<<std::fixed<<IMU_ACCEL_Y<<std::endl;
            std::cout<<"accel_z = "<<std::fixed<<IMU_ACCEL_Z<<std::endl;

            std::cout<<"magne_x = "<<std::fixed<<IMU_COMPASS_X<<std::endl;
            std::cout<<"magne_y = "<<std::fixed<<IMU_COMPASS_Y<<std::endl;
            std::cout<<"magne_z = "<<std::fixed<<IMU_COMPASS_Z<<std::endl;
            std::cout<<"Quat_x = "<<std::fixed<<IMU_QUAT_X<<std::endl;
            std::cout<<"Quat_y = "<<std::fixed<<IMU_QUAT_Y<<std::endl;
            std::cout<<"Quat_z = "<<std::fixed<<IMU_QUAT_Z<<std::endl;
            std::cout<<"Euler_x = "<<std::fixed<<IMU_EULER_X<<std::endl;
            std::cout<<"Euler_y = "<<std::fixed<<IMU_EULER_Y<<std::endl;
            std::cout<<"Euler_z = "<<std::fixed<<IMU_EULER_Z<<std::endl<<std::endl;
            t=0;
            }
            t++;
          // triggered by arrival of last message packet
          if (sensor.receive(&registers) == TRIGGER_PACKET)
          {
            //header.stamp = ros::Time::now();
            publishMsgs(registers);
            //ros::spinOnce();
          }
        }
      }
      catch(const std::exception& e)
      {
        if (ser.isOpen()) ser.close();
        //ROS_ERROR_STREAM(e.what());
        //ROS_INFO("Attempting reconnection after error.");
        std::cout<<"Attempting reconnection after error."<<std::endl;
        //ros::Duration(1.0).sleep();
      }
    }
    else
    {
      //ROS_WARN_STREAM_COND(first_failure, "Could not connect to serial device "
      //    << port << ". Trying again every 1 second.");
      std::cout<< "Could not connect to serial device "
                << port << ". Trying again every 1 second."<< std::endl;
      first_failure = false;
      //ros::Duration(1.0).sleep();
    }
  }
}
コード例 #21
0
ファイル: socket_posix.cpp プロジェクト: mrG7/voip_workspace
std::string Ipv4SocketAddress::toString(bool wPort) const {
  std::stringstream r;
  r << address();
  if (wPort) r << ":" << port();
  return r.str();
}
コード例 #22
0
ファイル: endpoint.cpp プロジェクト: klupek/cppcms
endpoint::endpoint(std::string const &ip_in,int port_in) :
	d(new data())
{
	ip(ip_in);
	port(port_in);
}
コード例 #23
0
	bool	is_fully_qualified()	const throw()	{ return !key().empty() && !sockfam().is_null()
									&& port();	}
コード例 #24
0
ファイル: ContactUser.cpp プロジェクト: 62gs8ha/ricochet
void ContactUser::updateOutgoingSocket()
{
    if (m_status != Offline && m_status != RequestPending) {
        if (m_outgoingSocket) {
            m_outgoingSocket->disconnect(this);
            m_outgoingSocket->abort();
            m_outgoingSocket->deleteLater();
            m_outgoingSocket = 0;
        }
        return;
    }

    // Refuse to make outgoing connections to the local hostname
    if (hostname() == identity->hostname())
        return;

    if (m_outgoingSocket && m_outgoingSocket->status() == Protocol::OutboundConnector::Ready) {
        BUG() << "Called updateOutgoingSocket with an existing socket in Ready. This should've been deleted.";
        m_outgoingSocket->disconnect(this);
        m_outgoingSocket->deleteLater();
        m_outgoingSocket = 0;
    }

    if (!m_outgoingSocket) {
        m_outgoingSocket = new Protocol::OutboundConnector(this);
        m_outgoingSocket->setAuthPrivateKey(identity->hiddenService()->privateKey());
        connect(m_outgoingSocket, &Protocol::OutboundConnector::ready, this,
            [this]() {
                assignConnection(m_outgoingSocket->takeConnection());
            }
        );

        /* As an ugly hack, because Ricochet 1.0.x versions have no way to notify about
         * protocol issues, and it's not feasible to support both protocols for this
         * tiny upgrade period:
         *
         * The first time we make an outgoing connection to an existing contact, if they
         * are using the old version, send a chat message that lets them know about the
         * new version, then disconnect. This message is only sent once per contact.
         *
         * XXX: This logic should be removed an appropriate amount of time after the new
         * protocol has been released.
         */
        connect(m_outgoingSocket, &Protocol::OutboundConnector::oldVersionNegotiated, this,
            [this](QTcpSocket *socket) {
                if (m_settings->read("sentUpgradeNotification").toBool())
                    return;
                QByteArray secret = m_settings->read<Base64Encode>("remoteSecret");
                if (secret.size() != 16)
                    return;

                static const char upgradeMessage[] =
                    "[automatic message] I'm using a newer version of Ricochet that is not "
                    "compatible with yours. This is a one-time change to help improve Ricochet. "
                    "See https://ricochet.im/upgrade for instructions on getting the latest "
                    "version. Once you have upgraded, I will be able to see your messages again.";
                uchar command[] = {
                    0x00, 0x00, 0x10, 0x00, 0x00, 0x01, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                };

                qToBigEndian(quint16(sizeof(upgradeMessage) + 7), command);
                qToBigEndian(quint16(sizeof(upgradeMessage) - 1), command + sizeof(command) - sizeof(quint16));

                QByteArray data;
                data.append((char)0x00);
                data.append(secret);
                data.append(reinterpret_cast<const char*>(command), sizeof(command));
                data.append(upgradeMessage);
                socket->write(data);

                m_settings->write("sentUpgradeNotification", true);
                updateStatus();
            }
        );
    }

    m_outgoingSocket->connectToHost(hostname(), port());
}
コード例 #25
0
ファイル: main.cpp プロジェクト: bitfixer/bitfixer
int main(int argc, char * const argv[]) {
    // initialize
    int c;
    int frame_size = C64_FRAME_SIZE;
    int output_port = 99999;
    FILE* fp = stdin;
    int ip[4] = {127, 0, 0, 1};
    
    while ((c = getopt(argc, argv, "t:p:i:a:")) != -1)
    {
        if (c == 't')
        {
            if (strcmp(optarg, "c64") == 0)
            {
                frame_size = C64_FRAME_SIZE;
            }
            else if (strcmp(optarg, "pet") == 0)
            {
                frame_size = PET_FRAME_SIZE;
            }
            else if (strcmp(optarg, "pet40") == 0)
            {
                frame_size = PET_40_FRAME_SIZE;
            }
        }
        else if (c == 'p')
        {
            output_port = atoi(optarg);
        }
        else if (c == 'i')
        {
            fp = fopen(optarg, "rb");
        }
        else if (c == 'a') // ip address
        {
            sscanf(optarg, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]);
        }
    }
    
    Frame frame(frame_size);
    Tools::Timer timer;
    NetPort port(ip[0],ip[1],ip[2],ip[3],5555,output_port);
    NetPort timeListenerPort(127,0,0,1,5556,output_port);
    
    unsigned char temp[2000];
    
    float start_pts = -1;
    double external_offset = 0.0;
    while (frame.read(fp))
    {
        fprintf(stderr, "pts: %f\n", frame.pts());
        if (start_pts < 0.0)
        {
            start_pts = frame.pts();
            timer.start();
        }
        
        float rel_pts = frame.pts() - start_pts;
        
        // get current time
        double currentTime = timer.getTime() + external_offset;
        fprintf(stderr, "current time: %lf timer %lf offset %lf\n", currentTime, timer.getTime(), external_offset);
        while (currentTime < rel_pts)
        {
            float sleepTimeUs = (rel_pts - currentTime) * 1000000.0;
            
            // check for timer update
            uint32_t nTimeUs = 0;
            int ret = timeListenerPort.recv((unsigned char*)&nTimeUs, sizeof(uint32_t));
            if (ret == sizeof(uint32_t))
            {
                uint32_t timeUs = ntohl(nTimeUs);
                printf("got time update: %d at time %lf\n", timeUs, timer.getTime());
                
                double ext_time = (double)timeUs / 1000000.0;
                external_offset = ext_time - timer.getTime();
            }
            
            if (sleepTimeUs > 1.0)
            {
                usleep(sleepTimeUs);
            }
            
            currentTime = timer.getTime() + external_offset;
        }
        
        fprintf(stderr, "sending frame at time %lf relpts %f error %f\n", currentTime, rel_pts, currentTime-rel_pts);
        
        // write data to output
        //fwrite(frame.data, 1, C64_FRAME_SIZE, fp_out);
        //memcpy(temp, frame.data(), frame.dataSize());
        int ret = port.send(frame.data(), frame.dataSize());
        //int ret = port.send(temp, 2000);
        //printf("send returned %d op %d %d %d %d %d\n", ret, ip[0], ip[1], ip[2], ip[3], output_port);
    }
    
    if (fp != stdin)
    {
        fclose(fp);
    }
    
    return 0;
}
コード例 #26
0
//
// The MachServer hookup
//
PortPowerWatcher::PortPowerWatcher()
{
    port(IONotificationPortGetMachPort(mPortRef));
}
コード例 #27
0
/*!
 * Handles incoming HTTP requests and dispatches them to the appropriate service.
 *
 * The \a requestID is an opaque value generated by the connector.
 *
 * Subclasses may override this function to perform preprocessing on each
 * request, but they must call the base class implementation in order to
 * generate and dispatch the appropriate events.
 *
 * To facilitate use with multi-threaded applications, the event will remain
 * valid until a response is posted.
 */
void QxtHttpSessionManager::incomingRequest(quint32 requestID, const QHttpRequestHeader& header, QxtWebContent* content)
{
    QMultiHash<QString, QString> cookies;
    foreach(const QString& cookie, header.allValues("cookie"))   // QHttpHeader is case-insensitive, thankfully
    {
        foreach(const QString& kv, cookie.split("; "))
        {
            int pos = kv.indexOf('=');
            if (pos == -1) continue;
            cookies.insert(kv.left(pos), kv.mid(pos + 1));
        }
    }

    int sessionID;
    QString sessionCookie = cookies.value(qxt_d().sessionCookieName);

    qxt_d().sessionLock.lock();
    if (qxt_d().sessionKeys.contains(sessionCookie))
    {
        sessionID = qxt_d().sessionKeys[sessionCookie];
        if(!sessionID && header.majorVersion() > 0 && qxt_d().autoCreateSession)
            sessionID = newSession();
    }
    else if (header.majorVersion() > 0 && qxt_d().autoCreateSession)
    {
        sessionID = newSession();
    }
    else
    {
        sessionID = 0;
    }

    QIODevice* device = connector()->getRequestConnection(requestID);
    QxtHttpSessionManagerPrivate::ConnectionState& state = qxt_d().connectionState[device];
    state.sessionID = sessionID;
    state.httpMajorVersion = header.majorVersion();
    state.httpMinorVersion = header.minorVersion();
    if (state.httpMajorVersion == 0 || (state.httpMajorVersion == 1 && state.httpMinorVersion == 0) || header.value("connection").toLower() == "close")
        state.keepAlive = false;
    else
        state.keepAlive = true;
    qxt_d().sessionLock.unlock();

    QxtWebRequestEvent* event = new QxtWebRequestEvent(sessionID, requestID, QUrl::fromEncoded(header.path().toUtf8()));
    qxt_d().eventLock.lock();
    qxt_d().pendingRequests.insert(QPair<int,int>(sessionID, requestID), event);
    qxt_d().eventLock.unlock();
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(device);
    if (socket)
    {
        event->remoteAddress = socket->peerAddress();
#if defined(QT_SECURETRANSPORT) || !defined(QT_NO_OPENSSL)
        QSslSocket* sslSocket = qobject_cast<QSslSocket*>(socket);
        if(sslSocket) {
            event->isSecure = true;
            event->clientCertificate = sslSocket->peerCertificate();
        }
#endif
    }
    event->method = header.method();
    event->cookies = cookies;
    event->url.setScheme("http");
    if (event->url.host().isEmpty())
        event->url.setHost(header.value("host"));
    if (event->url.port() == -1)
        event->url.setPort(port());
    event->contentType = header.contentType();
    event->content = content;
    typedef QPair<QString, QString> StringPair;
    foreach(const StringPair& line, header.values())
    {
        if (line.first.toLower() == "cookie") continue;
        event->headers.insert(line.first, line.second);
    }
    event->headers.insert("X-Request-Protocol", "HTTP/" + QString::number(state.httpMajorVersion) + '.' + QString::number(state.httpMinorVersion));
    if (sessionID && session(sessionID))
    {
        QxtAbstractWebService *service = session(sessionID);
        if(content)
            content->setParent(service); // Set content ownership to the service
        service->pageRequestedEvent(event);
    }
    else if (qxt_d().staticService)
    {
        qxt_d().staticService->pageRequestedEvent(event);
    }
    else
    {
        postEvent(new QxtWebErrorEvent(0, requestID, 500, "Internal Configuration Error"));
    }
}
コード例 #28
0
INTERFACE[16550]:

#include "types.h"

/**
 * 16550 implementation of the UART interface.
 */
EXTENSION class Uart
{
public:

  /**
   * Start this serial port for I/O.
   * @param port the I/O port base address.
   * @param irq the IRQ assigned to this port, -1 if none.
   */
  bool startup(Address port, int irq);

  enum {
    PAR_NONE = 0x00,
    PAR_EVEN = 0x18,
    PAR_ODD  = 0x08,
    DAT_5    = 0x00,
    DAT_6    = 0x01,
    DAT_7    = 0x02,
    DAT_8    = 0x03,
    STOP_1   = 0x00,
    STOP_2   = 0x04,

    MODE_8N1 = PAR_NONE | DAT_8 | STOP_1,
    MODE_7E1 = PAR_EVEN | DAT_7 | STOP_1,

  // these two values are to leave either mode
  // or baud rate unchanged on a call to change_mode
    MODE_NC  = 0x1000000,
    BAUD_NC  = 0x1000000,

  };

private:

  enum Registers {
    TRB      = 0, // Transmit/Receive Buffer  (read/write)
    BRD_LOW  = 0, // Baud Rate Divisor LSB if bit 7 of LCR is set  (read/write)
    IER      = 1, // Interrupt Enable Register  (read/write)
    BRD_HIGH = 1, // Baud Rate Divisor MSB if bit 7 of LCR is set  (read/write)
    IIR      = 2, // Interrupt Identification Register  (read only)
    FCR      = 2, // 16550 FIFO Control Register  (write only)
    LCR      = 3, // Line Control Register  (read/write)
    MCR      = 4, // Modem Control Register  (read/write)
    LSR      = 5, // Line Status Register  (read only)
    MSR      = 6, // Modem Status Register  (read only)
    SPR      = 7, // Scratch Pad Register  (read/write)
  };

  Address port;
  int _irq;
};


IMPLEMENTATION[16550]:

#include "io.h"
#include "processor.h"


IMPLEMENT
Uart::Uart() : port(~0U), _irq(-1)
{}

IMPLEMENT
Uart::~Uart()
{}


PRIVATE inline NEEDS["io.h"]
void Uart::outb( Unsigned8 b, Registers reg )
{
  Io::out8(b, port + (reg << Access_shift));
}
コード例 #29
0
ファイル: hostandport.cpp プロジェクト: mongodb/mongo
bool HostAndPort::operator==(const HostAndPort& r) const {
    return host() == r.host() && port() == r.port();
}
コード例 #30
0
ファイル: isself.cpp プロジェクト: NathanZamecnik/mongo
    bool HostAndPort::isSelf() const {

        int _p = port();
        int p = _p == -1 ? CmdLine::DefaultDBPort : _p;

        if( p != cmdLine.port ) {
            // shortcut - ports have to match at the very least
            return false;
        }

        string host = str::stream() << this->host() << ":" << p;

        {
            // check cache for this host
            // debatably something _could_ change, but I'm not sure right now (erh 10/14/2010)
            scoped_lock lk( isSelfCommand._cacheLock );
            map<string,bool>::const_iterator i = isSelfCommand._cache.find( host );
            if ( i != isSelfCommand._cache.end() )
                return i->second;
        }

#if !defined(_WIN32) && !defined(__sunos__)
        // on linux and os x we can do a quick check for an ip match

        const vector<string> myaddrs = getMyAddrs();
        const vector<string> addrs = getAllIPs(_host);

        for (vector<string>::const_iterator i=myaddrs.begin(), iend=myaddrs.end(); i!=iend; ++i) {
            for (vector<string>::const_iterator j=addrs.begin(), jend=addrs.end(); j!=jend; ++j) {
                string a = *i;
                string b = *j;

                if ( a == b ||
                        ( str::startsWith( a , "127." ) && str::startsWith( b , "127." ) )  // 127. is all loopback
                   ) {

                    // add to cache
                    scoped_lock lk( isSelfCommand._cacheLock );
                    isSelfCommand._cache[host] = true;
                    return true;
                }
            }
        }

#endif

        if ( ! Listener::getTimeTracker() ) {
            // this ensures we are actually running a server
            // this may return true later, so may want to retry
            return false;
        }

        try {
            isSelfCommand.init();
            DBClientConnection conn;
            string errmsg;
            if ( ! conn.connect( host , errmsg ) ) {
                // should this go in the cache?
                return false;
            }

            if (AuthorizationManager::isAuthEnabled() && !cmdLine.keyFile.empty() ) {
                if (!authenticateInternalUser(&conn)) {
                    return false;
                }
            }

            BSONObj out;
            bool ok = conn.simpleCommand( "admin" , &out , "_isSelf" );
            bool me = ok && out["id"].type() == jstOID && isSelfCommand._id == out["id"].OID();

            // add to cache
            scoped_lock lk( isSelfCommand._cacheLock );
            isSelfCommand._cache[host] = me;

            return me;
        }
        catch ( std::exception& e ) {
            warning() << "could't check isSelf (" << host << ") " << e.what() << endl;
        }

        return false;
    }