Menu

[r1037]: / trunk / src / cpp / packetsocket.cpp  Maximize  Restore  History

Download this file

491 lines (340 with data), 14.1 kB

  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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*============================================================================
packetsocket
==============================================================================
This is a facility for communicating socket-style, with defined
packets like a datagram socket but with reliable delivery like a
stream socket. It's like a POSIX "sequential packet" socket, except
it is built on top of a stream socket, so it is usable on the many
systems that have stream sockets but not sequential packet sockets.
By Bryan Henderson 2007.05.12
Contributed to the public domain by its author.
============================================================================*/
/*============================================================================
The protocol for carrying packets on a character stream:
The protocol consists of the actual bytes to be transported with a bare
minimum of framing information added:
An ASCII Escape (<ESC> == 0x1B) character marks the start of a
4-ASCII-character control word. These are defined:
<ESC>PKT : marks the beginning of a packet.
<ESC>END : marks the end of a packet.
<ESC>ESC : represents an <ESC> character in the packet
<ESC>NOP : no meaning
Any other bytes after <ESC> is a protocol error.
A stream is all the data transmitted during a single socket
connection.
End of stream in the middle of a packet is a protocol error.
All bytes not part of a control word are literal bytes of a packet.
You can create a packet socket from any file descriptor from which
you can read and write a bidirectional character stream. Typically,
it's a TCP socket.
One use of the NOP control word is to validate that the connection
is still working. You might send one periodically to detect, for
example, an unplugged TCP/IP network cable. It's probably better
to use the TCP keepalive facility for that.
============================================================================*/
#define _BSD_SOURCE // gets uint defined
#include <cassert>
#include <string>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/types.h>
#include "c_util.h"
#include "xmlrpc-c/string_int.h"
#include "xmlrpc-c/girerr.hpp"
using girerr::throwf;
#include "xmlrpc-c/packetsocket.hpp"
#define ESC 0x1B // ASCII Escape character
#define ESC_STR "\x1B"
namespace xmlrpc_c {
packet::packet() :
bytes(NULL), length(0), allocSize(0) {}
void
packet::initialize(const unsigned char * const data,
size_t const dataLength) {
this->bytes = reinterpret_cast<unsigned char *>(malloc(dataLength));
if (this->bytes == NULL)
throwf("Can't get storage for a %u-byte packet.", dataLength);
this->allocSize = dataLength;
memcpy(this->bytes, data, dataLength);
this->length = dataLength;
}
packet::packet(const unsigned char * const data,
size_t const dataLength) {
this->initialize(data, dataLength);
}
packet::packet(const char * const data,
size_t const dataLength) {
this->initialize(reinterpret_cast<const unsigned char *>(data),
dataLength);
}
packet::~packet() {
if (this->bytes)
free(bytes);
}
void
packet::addData(const unsigned char * const data,
size_t const dataLength) {
/*----------------------------------------------------------------------------
Add the 'length' bytes at 'data' to the packet.
We allocate whatever additional memory is needed to fit the new
data in.
-----------------------------------------------------------------------------*/
size_t const neededSize(this->length + dataLength);
if (this->allocSize < neededSize)
this->bytes = reinterpret_cast<unsigned char *>(
realloc(this->bytes, neededSize));
if (this->bytes == NULL)
throwf("Can't get storage for a %u-byte packet.", neededSize);
memcpy(this->bytes + this->length, data, dataLength);
this->length += dataLength;
}
packetPtr::packetPtr() {
// Base class constructor will construct pointer that points to nothing
}
packetPtr::packetPtr(packet * const packetP) : autoObjectPtr(packetP) {}
packet *
packetPtr::operator->() const {
girmem::autoObject * const p(this->objectP);
return dynamic_cast<packet *>(p);
}
packetSocket::packetSocket(int const sockFd) {
int dupRc;
dupRc = dup(sockFd);
if (dupRc < 0)
throwf("dup() failed. errno=%d (%s)", errno, strerror(errno));
else {
this->sockFd = dupRc;
this->inEscapeSeq = false;
this->inPacket = false;
this->escAccum.len = 0;
fcntl(this->sockFd, F_SETFL, O_NONBLOCK);
this->eof = false;
}
}
packetSocket::~packetSocket() {
close(this->sockFd);
}
static void
writeFd(int const fd,
const unsigned char * const data,
size_t const size) {
size_t totalBytesWritten;
totalBytesWritten = 0;
while (totalBytesWritten < size) {
ssize_t rc;
rc = write(fd, data, size);
if (rc < 0)
throwf("write() of socket failed with errno %d (%s)",
errno, strerror(errno));
else if (rc == 0)
throwf("Zero byte short write.");
else {
size_t const bytesWritten(rc);
totalBytesWritten += bytesWritten;
}
}
}
void
packetSocket::writeWait(packetPtr const& packetP) const {
const unsigned char * const packetStart(
reinterpret_cast<const unsigned char *>(ESC_STR "PKT"));
const unsigned char * const packetEnd(
reinterpret_cast<const unsigned char *>(ESC_STR "END"));
writeFd(this->sockFd, packetStart, 4);
writeFd(this->sockFd, packetP->getBytes(), packetP->getLength());
writeFd(this->sockFd, packetEnd, 4);
}
static ssize_t
libc_read(int const fd,
void * const buf,
size_t const count) {
return read(fd, buf, count);
}
void
packetSocket::takeSomeEscapeSeq(const unsigned char * const buffer,
size_t const length,
size_t * const bytesTakenP) {
/*----------------------------------------------------------------------------
Take and process some bytes from the incoming stream 'buffer',
which contains 'length' bytes, assuming they are within an escape
sequence.
-----------------------------------------------------------------------------*/
size_t bytesTaken;
bytesTaken = 0;
while (this->escAccum.len < 3 && bytesTaken < length)
this->escAccum.bytes[this->escAccum.len++] = buffer[bytesTaken++];
assert(this->escAccum.len <= 3);
if (this->escAccum.len == 3) {
if (0) {
} else if (xmlrpc_memeq(this->escAccum.bytes, "NOP", 3)) {
// Nothing to do
} else if (xmlrpc_memeq(this->escAccum.bytes, "PKT", 3)) {
this->packetAccumP = packetPtr(new packet);
this->inPacket = true;
} else if (xmlrpc_memeq(this->escAccum.bytes, "END", 3)) {
if (this->inPacket) {
this->readBuffer.push(this->packetAccumP);
this->inPacket = false;
this->packetAccumP = packetPtr();
} else
throwf("END control word received without preceding PKT");
} else if (xmlrpc_memeq(this->escAccum.bytes, "ESC", 3)) {
if (this->inPacket)
this->packetAccumP->addData((const unsigned char *)ESC_STR, 1);
else
throwf("ESC control work received outside of a packet");
} else
throwf("Invalid escape sequence 0x%02x%02x%02x read from "
"stream socket under packet socket",
this->escAccum.bytes[0],
this->escAccum.bytes[1],
this->escAccum.bytes[2]);
this->inEscapeSeq = false;
this->escAccum.len = 0;
}
*bytesTakenP = bytesTaken;
}
void
packetSocket::takeSomePacket(const unsigned char * const buffer,
size_t const length,
size_t * const bytesTakenP) {
assert(!this->inEscapeSeq);
const unsigned char * const escPos(
(const unsigned char *)memchr(buffer, ESC, length));
if (escPos) {
size_t const escOffset(escPos - &buffer[0]);
// move everything before the escape sequence into the
// packet accumulator.
this->packetAccumP->addData(buffer, escOffset);
// Caller can pick up from here; we don't know nothin' 'bout
// no escape sequences.
*bytesTakenP = escOffset;
} else {
// No complete packet yet and no substitution to do;
// just throw the whole thing into the accumulator.
this->packetAccumP->addData(buffer, length);
*bytesTakenP = length;
}
}
void
packetSocket::verifyNothingAccumulated() {
/*----------------------------------------------------------------------------
Throw an error if there is a partial packet accumulated.
-----------------------------------------------------------------------------*/
if (this->inEscapeSeq)
throwf("Streams socket closed in the middle of an "
"escape sequence");
if (this->inPacket)
throwf("Stream socket closed in the middle of a packet "
"(%u bytes of packet received; no END marker to mark "
"end of packet)", this->packetAccumP->getLength());
}
void
packetSocket::processBytesRead(const unsigned char * const buffer,
size_t const bytesRead) {
uint cursor; // Cursor into buffer[]
cursor = 0;
while (cursor < bytesRead) {
size_t bytesTaken;
if (this->inEscapeSeq)
this->takeSomeEscapeSeq(&buffer[cursor],
bytesRead - cursor,
&bytesTaken);
else if (buffer[cursor] == ESC) {
this->inEscapeSeq = true;
bytesTaken = 1;
} else if (this->inPacket)
this->takeSomePacket(&buffer[cursor],
bytesRead - cursor,
&bytesTaken);
else
throwf("Byte 0x%02x is not in a packet or escape sequence. "
"Sender is probably not using packet socket protocol",
buffer[cursor]);
cursor += bytesTaken;
}
}
void
packetSocket::readFromFile() {
/*----------------------------------------------------------------------------
Read some data from the underlying stream socket. Read as much as is
available right now, up to 4K. Update 'this' to reflect the data read.
E.g. if we read an entire packet, we add it to the packet buffer
(this->readBuffer). If we read the first part of a packet, we add
it to the packet accumulator (*this->packetAccumP). If we read the end
of a packet, we add the full packet to the packet buffer and empty
the packet accumulator. Etc.
-----------------------------------------------------------------------------*/
bool wouldblock;
wouldblock = false;
while (this->readBuffer.empty() && !this->eof && !wouldblock) {
unsigned char buffer[4096];
ssize_t rc;
rc = libc_read(this->sockFd, buffer, sizeof(buffer));
if (rc < 0) {
if (errno == EWOULDBLOCK)
wouldblock = true;
else
throwf("read() of socket failed with errno %d (%s)",
errno, strerror(errno));
} else {
size_t const bytesRead(rc);
if (bytesRead == 0) {
this->eof = true;
this->verifyNothingAccumulated();
} else
this->processBytesRead(buffer, bytesRead);
}
}
}
void
packetSocket::read(bool * const eofP,
bool * const gotPacketP,
packetPtr * const packetPP) {
/*----------------------------------------------------------------------------
Read one packet from the socket, through the internal packet buffer.
If there is a packet immediately available, return it as *packetPP and
return *gotPacketP true. Otherwise, return *gotPacketP false.
Iff the socket has no more data coming (it is shut down) and there
is no complete packet in the packet buffer, return *eofP.
This leaves one other possibility: there is no full packet immediately
available, but there may be in the future because the socket is still
alive. In that case, we return *eofP == false and *gotPacketP == false.
Any packet we return belongs to caller; Caller must delete it.
-----------------------------------------------------------------------------*/
// Move any packets now waiting to be read in the underlying stream
// socket into our packet buffer (this->readBuffer).
this->readFromFile();
if (this->readBuffer.empty()) {
*gotPacketP = false;
*eofP = this->eof;
} else {
*gotPacketP = true;
*eofP = false;
*packetPP = this->readBuffer.front();
readBuffer.pop();
}
}
void
packetSocket::readWait(bool * const eofP,
packetPtr * const packetPP) {
bool gotPacket;
bool eof;
gotPacket = false;
eof = false;
while (!gotPacket && !eof) {
struct pollfd pollfds[1];
pollfds[0].fd = this->sockFd;
pollfds[0].events = POLLIN;
poll(pollfds, ARRAY_SIZE(pollfds), -1);
this->read(&eof, &gotPacket, packetPP);
}
*eofP = eof;
}
} // namespace
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.