Source

ppenet / ppenet / peer.py

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
import random
from collections import deque
import protocol

DEFAULT_ROUND_TRIP_TIME = 500
DEFAULT_PACKET_THROTTLE = 32
PACKET_THROTTLE_SCALE = 32
PACKET_THROTTLE_COUNTER = 7
PACKET_THROTTLE_ACCELERATION = 2
PACKET_THROTTLE_DECELERATION = 2
PACKET_THROTTLE_INTERVAL = 5000
PACKET_LOSS_SCALE = (1 << 16)
PACKET_LOSS_INTERVAL = 10000
WINDOW_SIZE_SCALE = 64 * 1024
TIMEOUT_LIMIT = 32
TIMEOUT_MINIMUM = 5000
TIMEOUT_MAXIMUM = 30000
PING_INTERVAL = 500
UNSEQUENCED_WINDOWS = 64
UNSEQUENCED_WINDOW_SIZE = 1024
FREE_UNSEQUENCED_WINDOWS = 32
RELIABLE_WINDOWS = 16
RELIABLE_WINDOW_SIZE = 0x1000
FREE_RELIABLE_WINDOWS = 8


class State:
    (DISCONNECTED,
    CONNECTING,
    ACKNOWLEDGING_CONNECT,
    CONNECTION_PENDING,
    CONNECTION_SUCCEEDED,
    CONNECTED,
    DISCONNECT_LATER,
    DISCONNECTING,
    ACKNOWLEDGING_DISCONNECT,
    ZOMBIE) = range(10)


class PacketFlag:
    RELIABLE = 1 << 0
    UNSEQUENCED = 1 << 1
    UNRELIABLE_FRAGMENT = 1 << 3


class Channel(object):
    def __init__(self):
        self.outgoing_reliable_seq_num = 0
        self.outgoing_unreliable_seq_num = 0
        self.used_reliable_windows = 0
        self.reliable_windows = [0] * RELIABLE_WINDOWS
        self.incoming_reliable_seq_num = 0
        self.incoming_unreliable_seq_num = 0
        self.incoming_reliable_commands = []
        self.incoming_unreliable_commands = []


class Acknowledgement(object):
    def __init__(self, command, sent_time):
        self.ack_list = []
        self.sent_lime = sent_time
        self.command = command


class OutgoingCommand(object):
    def __init__(self, command, data='', offset=0, length=0):
        self.outgoing_command_list = []
        self.reliable_seq_num = 0
        self.unreliable_seq_num = 0
        self.sent_time = 0
        self.round_trip_timeout = 0
        self.round_trip_timeout_limit = 0
        self.fragment_offset = offset
        self.fragment_length = length
        self.send_attempts = 0
        self.command = command
        self.data = data


class IncomingCommand(object):
    def __init__(self, command, data=''):
        self.incoming_command_list = []
        self.reliable_seq_num = 0
        self.unreliable_seq_num = 0
        self.command = command
        self.fragment_count = 0
        self.fragments_remaining = 0
        self.fragments = 0
        self.data = data


class Peer(object):
    def __init__(self, host, peer_id, channel_count):
        self.host = host
        self.incoming_peer_id = peer_id
        self.outgoing_session_id = 0xff
        self.incoming_session_id = 0xff
        self.address = None
        self.data = 0

        self.reset()

    def reset(self):
        self.outgoing_peer_id = protocol.MAXIMUM_PEER_ID
        self.connect_id = 0
        self.state = State.DISCONNECTED
        self.incoming_bandwidth = 0
        self.outgoing_bandwidth = 0
        self.incoming_bandwidth_throttle_epoch = 0
        self.outgoing_bandwidth_throttle_epoch = 0
        self.incoming_data_total = 0
        self.outgoing_data_total = 0
        self.last_send_time = 0
        self.last_receive_time = 0
        self.next_timeout = 0
        self.earliest_timeout = 0
        self.packet_loss_epoch = 0
        self.packets_sent = 0
        self.packets_lost = 0
        self.packet_loss = 0
        self.packet_loss_variance = 0
        self.packet_throttle = DEFAULT_PACKET_THROTTLE
        self.packet_throttle_limit = PACKET_THROTTLE_SCALE
        self.packet_throttle_counter = 0
        self.packet_throttle_epoch = 0
        self.packet_throttle_acceleration = PACKET_THROTTLE_ACCELERATION
        self.packet_throttle_deceleration = PACKET_THROTTLE_DECELERATION
        self.packet_throttle_interval = PACKET_THROTTLE_INTERVAL
        self.ping_interval = PING_INTERVAL
        self.timeout_limit = TIMEOUT_LIMIT
        self.timeout_minimum = TIMEOUT_MINIMUM
        self.timeout_maximum = TIMEOUT_MAXIMUM
        self.last_round_trip_time = DEFAULT_ROUND_TRIP_TIME
        self.lowest_round_trip_time = DEFAULT_ROUND_TRIP_TIME
        self.last_round_trip_time_variance = 0
        self.highest_round_trip_time_variance = 0
        self.round_trip_time = DEFAULT_ROUND_TRIP_TIME
        self.round_trip_time_variance = 0
        self.mtu = self.host.mtu
        self.window_size = protocol.MAXIMUM_WINDOW_SIZE
        self.reliable_data_in_transit = 0
        self.outgoing_reliable_seq_num = 0
        self.incoming_unsequenced_group = 0
        self.outgoing_unsequenced_group = 0
        self.unsequenced_window = []
        self.event_data = 0

        self._reset_queues()

    def _reset_queues(self):
        self.channels = {}
        self.acknowledgements = deque()
        self.sent_reliable_commands = deque()
        self.sent_unreliable_commands = deque()
        self.outgoing_reliable_commands = deque()
        self.outgoing_unreliable_commands = deque()
        self.dispatched_commands = deque()
        self.dispatch_list = deque()
        self.needs_dispatch = 0

    def connect(self, address, data=0):
        host = self.host
        self.state = State.CONNECTING
        self.address = address
        self.connect_id = random.getrandbits(32)
        if host.outgoing_bandwidth == 0:
            window_size = protocol.MAXIMUM_WINDOW_SIZE
        else:
            window_size = (host.outgoing_bandwidth / WINDOW_SIZE_SCALE
                          * protocol.MAXIMUM_WINDOW_SIZE)
        self.window_size = max(min(window_size, protocol.MAXIMUM_WINDOW_SIZE),
                               protocol.MINIMUM_WINDOW_SIZE)
        connect = protocol.Connect(
            protocol.Command.CONNECT | protocol.Flag.COMMAND_ACKNOWLEDGE,
            0xFF,
            0,
            self.incoming_peer_id,
            self.incoming_session_id,
            self.outgoing_session_id,
            self.mtu,
            self.window_size,
            self.channel_count,
            self.incoming_bandwidth,
            self.outgoing_bandwidth,
            self.packet_throttle_interval,
            self.packet_throttle_acceleration,
            self.packet_throttle_deceleration,
            self.connect_id,
            self.data
        )
        self._queue_outgoing_command(OutgoingCommand(connect))

    def _get_channel(self, channel_id):
        try:
            channel = self.channels[channel_id]
        except KeyError:
            if 0 <= channel_id < protocol.MAXIMUM_CHANNEL_COUNT:
                self.channels[channel_id] = channel = Channel()
            else:
                raise ValueError('Wrong channel_id: %d' % channel_id)
        return channel

    def throttle_configure(self, interval=PACKET_THROTTLE_INTERVAL,
                           acceleration=PACKET_THROTTLE_ACCELERATION,
                           deceleration=PACKET_THROTTLE_DECELERATION):
        self.packet_throttle_interval = interval
        self.packet_throttle_acceleration = acceleration
        self.packet_throttle_deceleration = deceleration
        self._queue_outgoing_command(OutgoingCommand(
            protocol.ThrottleConfigure(
                channel_id=0xff,
                packet_throttle_interval=interval,
                packet_throttle_acceleration=acceleration,
                packet_throttle_deceleration=deceleration
            )
        ))

    def _peer_throttle(self, rtt):
        if self.last_round_trip_time <= self.last_round_trip_time_variance:
            self.packet_throttle = self.packet_throttle_limit
        elif rtt < self.last_round_trip_time:
            self.packet_throttle += self.packet_throttle_acceleration
            self.packet_throttle = min(self.packet_throttle,
                                       self.packet_throttle_limit)
            return 1
        elif (rtt > self.last_round_trip_time + 2 *
              self.last_round_trip_time_variance):
            if self.packet_throttle > self.packet_throttle_deceleration:
                self.packet_throttle -= self.packet_throttle_deceleration
            else:
                self.packet_throttle = 0
            return -1
        return 0

    def send(self, channel_id, data, flags=0):
        if self.state != State.CONNECTED:
            raise IOError('Not connected')
        data_len = len(data)
        if data_len > protocol.MAXIMUM_PACKET_SIZE:
            raise ValueError('Data too large')
        fragment_len = self.mtu - protocol.SendFragment.size
        if self.host.checksum is not None:
            fragment_len -= 4  # size of 32bit unsigned integer

        if data_len > fragment_len:
            self._send_fragments(channel_id, data, fragment_len, flags)
        else:
            self._send(channel_id, data, flags)

    def _send(self, channel_id, data, flags):
        data_len = len(data)
        channel = self._get_channel(channel_id)
        if (flags & (PacketFlag.RELIABLE | PacketFlag.UNSEQUENCED) ==
                PacketFlag.UNSEQUENCED):
            command = protocol.SendUnsequenced()
        elif (flags & PacketFlag.RELIABLE or
                channel.outgoing_unreliable_seq_num >= 0xffff):
            command = protocol.SendReliable()
        else:
            command = protocol.SendUnreliable()
        command.channel_id = channel_id
        command.data_length = data_len
        self._queue_outgoing_command(OutgoingCommand(
            command,
            data,
            0,
            data_len
        ))

    def _send_fragments(self, channel_id, data, fragment_len, flags):
        data_len = len(data)
        channel = self._get_channel(channel_id)
        fragment_count = (data_len + fragment_len - 1) / fragment_len
        if fragment_count > protocol.MAXIMUM_FRAGMENT_COUNT:
            raise ValueError('Data too large')
        mask = PacketFlag.RELIABLE | PacketFlag.UNRELIABLE_FRAGMENT
        if (flags & mask == PacketFlag.UNRELIABLE_FRAGMENT and
                channel.outgoing_unreliable_seq_num < 0xffff):
            command_type = protocol.Command.SEND_UNRELIABLE_FRAGMENT
            start_seq_num = channel.outgoing_unreliable_seq_num + 1
        else:
            command_type = (protocol.Command.SEND_FRAGMENT |
                protocol.Flag.COMMAND_ACKNOWLEDGE)
            start_seq_num = channel.outgoing_reliable_seq_num + 1

        for fragment_number, fragment_offset in enumerate(
                xrange(0, data_len, fragment_len)):
            if data_len - fragment_offset < fragment_len:
                # calculate size of last fragment
                fragment_len = data_len - fragment_offset

            self._queue_outgoing_command(OutgoingCommand(
                protocol.SendFragment(
                    command_type,
                    channel_id,
                    0,
                    start_seq_num,
                    fragment_len,
                    fragment_count,
                    fragment_number,
                    data_len,
                    fragment_offset
                ),
                fragment_offset,
                fragment_len
            ))

    def receive(self):
        try:
            incoming_command = self.dispatched_commands.popleft()
        except IndexError:
            return None, None
        channel_id = incoming_command.command.channel_id
        data = incoming_command.data
        return data, channel_id

    def ping(self):
        self._queue_outgoing_command(OutgoingCommand(
            protocol.Ping(
                channel_id=0xff
            )
        ))

    def disconnect_now(self, data):
        if self.state != State.DISCONNECTED:
            if self.state != State.ZOMBIE:
                self._reset_queues()
                self._queue_outgoing_command(OutgoingCommand(
                    protocol.Disconnect(
                        protocol.Command.DISCONNECT |
                            protocol.Flag.COMMAND_UNSEQUENCED,
                        0xff,
                        0,
                        data
                    )
                ))
                self.host.flush()  # TODO: self.host.flush()
            self.reset()

    def disconnect(self, data):
        if self.state in (State.DISCONNECTING,
                          State.DISCONNECTED,
                          State.ACKNOWLEDGING_DISCONNECT,
                          State.ZOMBIE):
            return
        self._reset_queues()

        command_type = protocol.Command.DISCONNECT
        full_disconnect = self.state in (State.CONNECTED,
                                         State.DISCONNECT_LATER)
        if full_disconnect:
            command_type |= protocol.Flag.COMMAND_ACKNOWLEDGE
        else:
            command_type |= protocol.Flag.COMMAND_UNSEQUENCED

        self._queue_outgoing_command(OutgoingCommand(
            protocol.Disconnect(
                command_type,
                0xff,
                0,
                data
            )
        ))

        if full_disconnect:
            self.state = State.DISCONNECTING
        else:
            self.host.flush()
            self.reset()

    def disconnect_later(self, data):
        if (self.state in (State.CONNECTED, State.DISCONNECT_LATER) and
                (len(self.outgoing_reliable_commands) != 0 or
                 len(self.outgoing_unreliable_commands) != 0 or
                 len(self.sent_reliable_commands) != 0)):
            self.state = State.DISCONNECT_LATER
            self.event_data = data
        else:
            self.disconnect(data)

    def _queue_acknowledgement(self, ack):
        command = ack.command

        channel = self.channels.get(command.channel_id)
        if channel is not None:
            reliable_window = command.reliable_seq_num / RELIABLE_WINDOW_SIZE
            current_window = (channel.incoming_reliable_seq_num /
                              RELIABLE_WINDOW_SIZE)
            if command.reliable_seq_num < channel.incoming_reliable_seq_num:
                reliable_window += RELIABLE_WINDOW_SIZE
            c1 = reliable_window >= current_window + FREE_RELIABLE_WINDOWS - 1
            c2 = reliable_window <= current_window + FREE_RELIABLE_WINDOWS
            if c1 and c2:
                return

        self.outgoing_data_total += protocol.Acknowledge.size
        self.acknowledgements.append(ack)

    def _queue_outgoing_command(self, o_cmd):
        command = o_cmd.command

        self.outgoing_data_total += (command.size +
                                     o_cmd.fragment_length)
        if command.channel_id == 0xff:  # virtual reliable channel
            self.outgoing_reliable_seq_num += 1
            o_cmd.reliable_seq_num = self.outgoing_reliable_seq_num
            o_cmd.unreliable_seq_num = 0
        else:
            channel = self._get_channel(command.channel_id)
            if command.command & protocol.Flag.COMMAND_ACKNOWLEDGE:
                channel.outgoing_reliable_seq_num += 1
                channel.outgoing_unreliable_seq_num = 0
                o_cmd.reliable_seq_num = channel.outgoing_reliable_seq_num
                o_cmd.unreliable_seq_num = 0
            elif command.command & protocol.Flag.COMMAND_UNSEQUENCED:
                self.outgoing_unsequenced_group += 1
                o_cmd.reliable_seq_num = 0
                o_cmd.unreliable_seq_num = 0
            else:
                if o_cmd.fragment_offset == 0:
                    channel.outgoing_unreliable_seq_num += 1
                o_cmd.reliable_seq_num = channel.outgoing_reliable_seq_num
                o_cmd.unreliable_seq_num = channel.outgoing_unreliable_seq_num
        command.reliable_seq_num = o_cmd.reliable_seq_num

        command_type = command.command & protocol.COMMAND_MASK
        if command_type == protocol.Command.SEND_UNRELIABLE:
            command.unreliable_seq_num = o_cmd.unreliable_seq_num
        elif command_type == protocol.Command.SEND_UNSEQUENCED:
            command.unsequenced_group = self.outgoing_unsequenced_group

        if command.command & protocol.Flag.COMMAND_ACKNOWLEDGE:
            self.outgoing_reliable_commands.append(o_cmd)
        else:
            self.outgoing_unreliable_commands.append(o_cmd)