Source

blake / blake_netbuffer.cpp

Full commit
  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
/*
Copyright (C) 2001-2007 Daybo Logic.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/*
  blake_netbuffer is an object by David Duncan Ross Palmer
  to directly handle the networking aspects of Blake.
  It should be instantaniated inside the clients and the server.
  The C function DataReader and DataWriter have to be installed into
  Blake before the global class can know about data or send data.
  In the server, don't use the Connect() feature, just use
  the Push and Pop etc and construct with a pre-existing socket.
  Either keep pointers to dynamically created TNetBuffer's in a linked
  list or some sort of fixed structure.

  Note that this module in C++ and to use it in C, you will need to use
  blake_netbuffer_wrapper.cpp, which will export C interfaces.
*/
//---------------------------------------------------------------------------

#define BLAKE_SOURCE

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

#include <cassert>
#include <string>
#include <ctime>
#include <iostream>
#include <cstdio>
#include <cstdlib> /* For abort() */
#include <cstring> /* For memset()/memcpy() */

#ifdef HAVE_LIMITS_H
# include <limits.h>
#endif /*HAVE_LIMITS_H*/

#ifdef BLAKE_HDRSTOP
# pragma hdrstop
#endif /*BLAKE_HDRSTOP*/

#ifdef HAVE_DLSTDINC_H
# include "dlstdinc.h"
#endif /*HAVE_DLSTDINC_H*/

#include "blake_threads.h"
#include "blake.h"
#include "blake_main.h"
#include "blake_netbuffer.hpp"

using namespace std;
//---------------------------------------------------------------------------
static const char *const rcsid =
  "$Id: blake_netbuffer.cpp,v 0.9 2007/01/11 00:13:00 ddrp Exp $";

static void (*UserErrorHandler)(enum blakeError ErrNum) = NULL;
static size_t GetExpectSz(const unsigned char* RawData);

#ifdef DEBUG
static void DumpBuff(
  const char *File,
  const unsigned int Line,
  const unsigned char *RawBuffer,
  unsigned int Level
);
#endif //DEBUG
//---------------------------------------------------------------------------
void Blake::TNetBuffer::InitBuffers()
{
  this->outBuffLevel = 0U;
  this->inBuffLevel = 0U;
  memset(this->outBuff, 0, sizeof(this->outBuff));
  memset(this->inBuff, 0, sizeof(this->inBuff));

  memset(this->buff, 0, sizeof(this->buff)); // Current packet buffer
  this->marker = 0U;
  this->expectSz = 0U;

  blake_Unused(rcsid);
}
//---------------------------------------------------------------------------
Blake::TNetBuffer::TNetBuffer()
:
  s(0),
  UseIPv6(false),
  Port(BLAKE_PORT_DEFAULT)
{
  this->InitBuffers();
}
//---------------------------------------------------------------------------
Blake::TNetBuffer::TNetBuffer(int S)
:
  s(S),
  UseIPv6(false),
  Port(0)
{
  this->InitBuffers();
}
//---------------------------------------------------------------------------
Blake::TNetBuffer::TNetBuffer(
  unsigned short int iPort,
  bool bUseIPv6
)
:
  s(0),
  UseIPv6(bUseIPv6),
  Port(iPort)
{
  this->InitBuffers();
}
//---------------------------------------------------------------------------
Blake::TNetBuffer::~TNetBuffer()
{
  this->Close();
}
//---------------------------------------------------------------------------
enum blakeError Blake::TNetBuffer::Resolve(
  const string &ServerName, 
  OVERCHAT_IP *ReturnedAddress
)
{
  return network_Resolve(ServerName.c_str(), ReturnedAddress);
}
//---------------------------------------------------------------------------
enum blakeError Blake::TNetBuffer::CreateSocket(
  int *PSocket
)
{
  this->s = network_CreateSocket(this->UseIPv6, false, false);
  if ( PSocket ) *PSocket = this->s;
  if ( this->s == -1 ) { // Blake could not create a socket
    this->s = 0;
    return blakeUnknownFailure;
  }
  return blakeSuccess;
}
//---------------------------------------------------------------------------
enum blakeError Blake::TNetBuffer::Connect(
  const OVERCHAT_IP *Address
)
{
  enum blakeError err;

  err = network_Connect(s, UseIPv6, Port, Address); // Connect to server
  if ( err != blakeSuccess ) // Fail
    Close(); // Socket cannot be used (clean up)
  else
    network_MakeNonBlocking(s); // Connected to server, switch to nonblocking

  return err;
}
//---------------------------------------------------------------------------
void Blake::TNetBuffer::Close()
{
  if ( s ) {
    network_CloseSocket(s);
    s = 0;
    InitBuffers(); /* Incase this net buffer is re-used */
  }
}
//---------------------------------------------------------------------------
enum blakeNetBufferError Blake::TNetBuffer::Push(
  enum blakeNetBufferDirection Direction,
  const void *Data,
  const size_t DataSize
)
{
  enum blakeNetBufferError err = bnbeNoError;

  assert(Data && DataSize);
  if ( DataSize > BLAKE_NET_PKTMAXSZ * BLAKE_NET_TXSZ )
    return bnbeExtremeSize;

  switch ( Direction ) {
    case bnbdIncoming : {
      if (
        DataSize > (BLAKE_NET_PKTMAXSZ * BLAKE_NET_RXSZ) - inBuffLevel
      ) {
        err = bnbeCannotAccommodate;
        break;
      }
      memcpy((char*)inBuff + inBuffLevel, Data, DataSize);
      inBuffLevel += DataSize;
      assert(inBuffLevel <= (BLAKE_NET_PKTMAXSZ * BLAKE_NET_RXSZ));
      break;
    }
    case bnbdOutgoing : {
      if (
        DataSize > (BLAKE_NET_PKTMAXSZ * BLAKE_NET_TXSZ) - outBuffLevel
      ) {
        err = bnbeCannotAccommodate;
        break;
      }
      memcpy((char*)outBuff + outBuffLevel, Data, DataSize);
      outBuffLevel += DataSize;
      assert(outBuffLevel <= (BLAKE_NET_PKTMAXSZ * BLAKE_NET_TXSZ));
      break;
    }
    default : {
      err = bnbeBadDirection;
    }
  }

  return err;
}
//---------------------------------------------------------------------------
size_t Blake::TNetBuffer::Pop(
  enum blakeNetBufferDirection Direction,
  void *Data,
  const size_t MaxDataSize,
  enum blakeNetBufferError *PNetError
)
{
  enum blakeNetBufferError err = bnbeNoError;
  size_t ret = 0;

  assert(Data && MaxDataSize);
  switch ( Direction ) {
    case bnbdIncoming : {
      unsigned int MoveAmount = BLAKE_MIN(MaxDataSize, inBuffLevel);
      if ( MoveAmount ) {
        memcpy(Data, inBuff, MoveAmount);
        memmove(
          inBuff,
          (char*)inBuff+MoveAmount,
          (BLAKE_NET_PKTMAXSZ * BLAKE_NET_RXSZ) - MoveAmount
        );
        inBuffLevel -= MoveAmount;
      }
      ret = MoveAmount;
      break;
    }
    case bnbdOutgoing : {
      unsigned int MoveAmount = BLAKE_MIN(MaxDataSize, outBuffLevel);
      if ( MoveAmount ) {
        memcpy(Data, outBuff, MoveAmount);
        memmove(
          outBuff,
          (char*)outBuff+MoveAmount,
          (BLAKE_NET_PKTMAXSZ * BLAKE_NET_TXSZ) - MoveAmount
        );
        outBuffLevel -= MoveAmount;
      }
      ret = MoveAmount;
      break;
    }
    default : {
      err = bnbeBadDirection;
    }
  }

  if ( PNetError ) *PNetError = err;
  return ret;
}
//---------------------------------------------------------------------------
void Blake::TNetBuffer::PacketCompiler(
  size_t Amount
)
{
#ifdef DEBUG
  DumpBuff(__FILE__, __LINE__, inBuff, inBuffLevel);
#endif //DEBUG

  while ( Amount ) {
    if ( marker == 0 ) { /* Begin new packet - length reader */
      /* Read max two bytes (length indicator) */
      int nread = Pop(bnbdIncoming, buff, 2, NULL);
      if ( !nread ) return;
      /*
        Remove number of bytes read from master packet independent bytes
        arrived marker
      */
      Amount -= nread;
      switch ( nread ) {
        case 0 : /* Nowt read */
          goto setandunlock; /* Avoid time wastage */
        case 1 : { /* Could only read 'alf of the blighter */
          marker++; /* Remember it was read */
          break;
        }
        case 2 : { /* Got it!  Now swap it... */
          marker += 2;
          expectSz = GetExpectSz(buff);
          /*
            IMPORTANT:
            The following assertion causes the server/client to crash in
            debugging builds.  The peer to the connection can send a
            malicious packet to trigger this, so make sure that you switch
            off debugging (assertions at a minimum) in production servers
            and production clients.
          */
          assert(expectSz); // Crash on zero length packet
          if ( expectSz >= 2 ) {
            /*
              Now expect packet size remaining
              (minus length field already read)
            */
            expectSz -= 2;
          }

          break;
        }
        default : /* What's this, -1? */
          goto setandunlock; /* Forget it mate */
      }
    }
    else if ( marker == 1 ) { /* Previously read half the length! */
      /* OK we only want one byte!  I don't care how much is waiting */
      int nread = Pop(bnbdIncoming, buff + 1, 1, NULL);
      if ( !nread ) return;
      if ( nread != 1 ) goto setandunlock;
      marker++;
      expectSz = GetExpectSz(buff);
      assert(expectSz);
      if ( expectSz >= 2 ) expectSz -= 2;
      assert(expectSz);
      Amount -= nread;
    }
    else { /* Already got length, read packet */
      /* Read in up to the the packet size, if the length is malicious or
      corrupt cap at size of the RX buffer. */
      int maxRead = BLAKE_MIN((expectSz+2) - marker, sizeof(buff));
       /* Do some error/warning checking for diagnostics and for safety */
      if ( !expectSz ) goto setandunlock; /* Get out if no packet */
      if ( expectSz < 2 ) { /* Not enough room to have even sent the length */
        goto unlock;
      }
      else if ( expectSz < 3 ) { /* Just the two bytes for the length!? */
       goto setandunlock;
      }
      /* Back to some real work */
      if ( maxRead ) {
        int nread = Pop(bnbdIncoming, buff + marker, maxRead, NULL);
        if ( !nread ) return;
        marker += nread;
        Amount -= nread;
      }
      if ( (expectSz) && marker == (expectSz+2) ) {
        /* Pass to the Blake cracker */
        enum blakeError err = blake_CrackPacket(
          GetSocket(),
          buff,
          expectSz+2
        );

        /* Reset variables for next packet */
        marker = 0;
        expectSz = 0;
        /* Check for Blake errors */
        if ( err != blakeSuccess ) {
          if ( UserErrorHandler )
            UserErrorHandler(err);
        }
      }
    }
  }

setandunlock:


unlock:

  return;
}
//---------------------------------------------------------------------------
void NetBufferInstallBlakeErrorCallback(
  void (*ErrorHandler)(enum blakeError ErrNum)
)
{
  assert(ErrorHandler); // NULL is not acceptable, use uninstall
  assert(!UserErrorHandler); // Ensure no previous handler
  UserErrorHandler = ErrorHandler; // Install it
}
//---------------------------------------------------------------------------
void NetBufferUninstallBlakeErrorCallback(
  void (*ErrorHandler)(enum blakeError ErrNum)
)
{
  // Make sure caller knows what he's talking about
  assert(ErrorHandler == UserErrorHandler);

  if ( ErrorHandler == UserErrorHandler )
    UserErrorHandler = NULL; // Uninstall
  else
    abort();
}
//---------------------------------------------------------------------------
#ifdef DEBUG
static void DumpBuff(
  const char *File,
  const unsigned int Line,
  const unsigned char *RawBuffer,
  unsigned int Level
)
{
  unsigned int i;

  printf("Dump buffer called from %s L%u\n", File, Line);
  if ( Level ) {
    for ( i = 0U; i < Level; i++ )
      printf("%X, ", RawBuffer[i]);
    putchar('\n');
  }
  else
    puts("Nothing to dump.");
}
#endif //DEBUG
//---------------------------------------------------------------------------
static size_t GetExpectSz(
  const unsigned char *RawData
)
{
  size_t sz = 0U;
  unsigned char rawnumber[sizeof(unsigned short)];
  char test[3];

  test[0] = RawData[0];
  test[1] = RawData[1];
  test[2] = '\0';

  if ( RawData ) {
    unsigned short int *pnum;
    memcpy(rawnumber, RawData, 2); /* Get first two bytes */
    pnum = (unsigned short int*)rawnumber;
    sz = *pnum;
    /* Now do a swap */
    sz = network_NetToHostShort((unsigned short int)sz);
    /* Now cap */
    sz = BLAKE_MIN(sz, BLAKE_NET_PKTMAXSZ - 2);
  }
#ifdef DEBUG
  printf(
    "DEBUG: sz==%u  TESTRAW(%c%c)\n",
    (unsigned int)sz,
    test[0],
    test[1]
  );
#endif /*DEBUG*/
  return sz;
}
//---------------------------------------------------------------------------