File: BaseConnection.cpp

package info (click to toggle)
eris 1.3.10-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,592 kB
  • ctags: 1,516
  • sloc: cpp: 9,850; sh: 8,288; perl: 287; ansic: 165; makefile: 162
file content (236 lines) | stat: -rw-r--r-- 5,477 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#ifdef HAVE_CONFIG_H
	#include "config.h"
#endif

#include <Eris/BaseConnection.h>

#include <Eris/Exceptions.h>
#include <Eris/Timeout.h>
#include <Eris/Poll.h>
#include <Eris/Log.h>
#include <Eris/DeleteLater.h>
#include <Eris/Operations.h>

#include <Atlas/Codec.h>
#include <Atlas/Net/Stream.h>
#include <Atlas/Objects/Encoder.h>
#include <Atlas/Objects/objectFactory.h>

#include <skstream/skstream.h>
#include <sigc++/slot.h>

#include <sstream>
#include <cassert>

namespace Eris {
	
////////////////////////////////////////////////////////////////////////////////////////////////////////	
	
BaseConnection::BaseConnection(const std::string &cnm, 
	const std::string &id,
	Atlas::Bridge *br) :
	_sc(NULL),
	_status(DISCONNECTED),
	_id(id),
	_stream(NULL),
	_clientName(cnm),
	_bridge(br),
	_timeout(NULL),
	_host(""),
	_port(0)
{
	assert(_bridge);
    
    Atlas::Objects::Factories* f = Atlas::Objects::Factories::instance();
    if (!f->hasFactory("unseen")) 
    {
        Atlas::Objects::Operation::UNSEEN_NO = f->addFactory("unseen", &Atlas::Objects::generic_factory);
        Atlas::Objects::Operation::ATTACK_NO = f->addFactory("attack", &Atlas::Objects::generic_factory);
    }
}
	
BaseConnection::~BaseConnection()
{    
    if (_status != DISCONNECTED)
    {
        hardDisconnect(true);
    }
}
	
int BaseConnection::connect(const std::string &host, short port)
{
    if (_stream != NULL) {
        warning() << "in base connection :: connect, had existing stream, discarding it";
        hardDisconnect(true);
    }
	
    _host = host;
    _port = port;
    
    // start timeout
    _timeout = new Timeout(20 * 1000);
    _timeout->Expired.connect(sigc::mem_fun(this, &BaseConnection::onConnectTimeout));
	
    setStatus(CONNECTING);

    _stream = new tcp_socket_stream(host, port, true);

    Poll::instance().addStream(_stream, Poll::WRITE);
    return 0;
}

void BaseConnection::hardDisconnect(bool emit)
{
    if (_status == DISCONNECTED) return;
    
    assert(_stream);
    
    // okay, tear it down
    if ((_status == CONNECTED) || (_status == DISCONNECTING)){
        delete m_codec;
        delete _encode;
    } else if (_status == NEGOTIATE) {
        delete _sc;
        _sc = NULL;
    } else if (_status == CONNECTING) {
        // nothing to be done, but can happen
    } else
        throw InvalidOperation("Bad connection state for disconnection");
    
    deleteLater(_timeout);
    _timeout = NULL;
    
    Poll::instance().removeStream(_stream);
    delete _stream;
    _stream = NULL;

    setStatus(DISCONNECTED);
    if (emit) Disconnected.emit();
}

void BaseConnection::recv()
{
	int err = 0;
	assert(_status != DISCONNECTED);
	assert(_stream);
	
	if (_stream->eof() || _stream->fail()) {
		handleFailure("Connection stream failed");
		hardDisconnect(false);
	} else {
		switch (_status) {
		case CONNECTING:
		    nonblockingConnect();
		    break;

		case NEGOTIATE:
            pollNegotiation();
            break;

		case CONNECTED:
		case DISCONNECTING:
            m_codec->poll();
            break;
		default:
			throw InvalidOperation("Unexpected connection status in poll()");
		}	
	}
	
	// another paranoid check
	if (_stream && (err = _stream->getLastError()) != 0) {
		char msgBuf[128];
		::snprintf(msgBuf, 128, "recv() got stream failure, error %d", _stream->getLastError());
		handleFailure(msgBuf);
		hardDisconnect(false);
	}
}		

void BaseConnection::nonblockingConnect()
{
	assert(_stream);
    if (!_stream->isReady())
		return;

    if(!_stream->is_open()) {
		handleFailure("Failed to connect to " + _host);
		hardDisconnect(false);
		return;
    }

    Poll::instance().changeStream(_stream, Poll::READ);

    // negotiation timeout
    delete _timeout;
    _timeout = new Timeout(5000);
    _timeout->Expired.connect(sigc::mem_fun(this, &BaseConnection::onNegotiateTimeout));

    _sc = new Atlas::Net::StreamConnect(_clientName, *_stream);
    setStatus(NEGOTIATE);
}

void BaseConnection::pollNegotiation()
{
    if (!_sc || (_status != NEGOTIATE))
    {
        throw InvalidOperation("pollNegotiation: unexpected connection status");
    }
	
    _sc->poll();
    if (_sc->getState() == Atlas::Net::StreamConnect::IN_PROGRESS)
        // more negotiation to do once more netwrok data arrives
        return;
	
    if (_sc->getState() == Atlas::Net::StreamConnect::SUCCEEDED)
    {
        m_codec = _sc->getCodec(*_bridge);
        _encode = new Atlas::Objects::ObjectsEncoder(*m_codec);
        m_codec->streamBegin();
        // clean up
        delete _sc;
        _sc = NULL;
	    
        delete _timeout;
        _timeout = NULL;
	    
        setStatus(CONNECTED);
        onConnect();
    } else {
        // assume it all went wrong
        handleFailure("Atlas negotiation failed");
        hardDisconnect(false);
    }
}

void BaseConnection::onConnect()
{
    // tell anyone who cares with a signal
    Connected.emit();	
}

void BaseConnection::onConnectTimeout()
{
    std::ostringstream os;
    os << "Connect to " << _host << ':' << _port << " timed out";
    handleTimeout(os.str());
    hardDisconnect(false);
}

void BaseConnection::onNegotiateTimeout()
{
    handleTimeout("Atlas negotiation timed out");
    hardDisconnect(false);
}

void BaseConnection::setStatus(Status sc)
{
    _status = sc;
}

int BaseConnection::getFileDescriptor()
{
    if (!_stream)
        throw InvalidOperation("Not connected, hence no FD");
    return _stream->getSocket();
}

} // of namespace