Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/ipv6/src/external/enet/host.c @ 7390

Last change on this file since 7390 was 7389, checked in by adrfried, 14 years ago

fix some stuff

File size: 17.7 KB
Line 
1/**
2 @file host.c
3 @brief ENet host management functions
4*/
5#define ENET_BUILDING_LIB 1
6#include <string.h>
7#include <time.h>
8#include "enet/enet.h"
9
10static ENetSocket
11enet_socket_create_bind (const ENetAddress * address, ENetAddressFamily family)
12{
13    ENetSocket socket = enet_socket_create (ENET_SOCKET_TYPE_DATAGRAM, family);
14    if (socket == ENET_SOCKET_NULL)
15        return ENET_SOCKET_NULL;
16
17    if (address != NULL && enet_socket_bind (socket, address, family) < 0)
18    {
19        enet_socket_destroy (socket);
20        return ENET_SOCKET_NULL;
21    }
22
23    enet_socket_set_option (socket, ENET_SOCKOPT_NONBLOCK, 1);
24    enet_socket_set_option (socket, ENET_SOCKOPT_BROADCAST, 1);
25    enet_socket_set_option (socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE);
26    enet_socket_set_option (socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE);
27
28    return socket;
29}
30
31/** @defgroup host ENet host functions
32    @{
33*/
34
35/** Creates a host for communicating to peers. 
36
37    @param address   the address at which other peers may connect to this host.  If NULL, then no peers may connect to the host.
38    @param peerCount the maximum number of peers that should be allocated for the host.
39    @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
40    @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
41    @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
42
43    @returns the host on success and NULL on failure
44
45    @remarks ENet will strategically drop packets on specific sides of a connection between hosts
46    to ensure the host's bandwidth is not overwhelmed.  The bandwidth parameters also determine
47    the window size of a connection which limits the amount of reliable packets that may be in transit
48    at any given time.
49*/
50ENetHost *
51enet_host_create (const ENetAddress * address, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth)
52{
53    ENetHost * host;
54    ENetPeer * currentPeer;
55
56    if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID)
57      return NULL;
58
59    host = (ENetHost *) enet_malloc (sizeof (ENetHost));
60    if (host == NULL)
61      return NULL;
62
63    host -> peers = (ENetPeer *) enet_malloc (peerCount * sizeof (ENetPeer));
64    if (host -> peers == NULL)
65    {
66       enet_free (host);
67
68       return NULL;
69    }
70    memset (host -> peers, 0, peerCount * sizeof (ENetPeer));
71
72    int family = (address == NULL || !memcmp (& address -> host, & ENET_HOST_ANY, sizeof (ENetHostAddress))) ?
73        ENET_IPV4 | ENET_IPV6 :
74        enet_get_address_family (address);
75
76    host -> socket4 = (family & ENET_IPV4) ?
77      enet_socket_create_bind (address, ENET_IPV4) :
78      ENET_SOCKET_NULL;
79    host -> socket6 = (family & ENET_IPV6) ?
80      enet_socket_create_bind (address, ENET_IPV6) :
81      ENET_SOCKET_NULL;
82
83    if (host -> socket4 == ENET_SOCKET_NULL && host -> socket6 == ENET_SOCKET_NULL)
84    {
85        enet_free (host -> peers);
86        enet_free (host);
87        return NULL;
88    }
89
90    if (address != NULL)
91      host -> address = * address;
92
93    if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
94      channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
95    else
96    if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
97      channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
98
99    host -> randomSeed = (enet_uint32) time(NULL) + (enet_uint32) (size_t) host;
100    host -> randomSeed = (host -> randomSeed << 16) | (host -> randomSeed >> 16);
101    host -> channelLimit = channelLimit;
102    host -> incomingBandwidth = incomingBandwidth;
103    host -> outgoingBandwidth = outgoingBandwidth;
104    host -> bandwidthThrottleEpoch = 0;
105    host -> recalculateBandwidthLimits = 0;
106    host -> mtu = ENET_HOST_DEFAULT_MTU;
107    host -> peerCount = peerCount;
108    host -> commandCount = 0;
109    host -> bufferCount = 0;
110    host -> checksum = NULL;
111    host -> receivedAddress.host = ENET_HOST_ANY;
112    host -> receivedAddress.port = 0;
113    host -> receivedData = NULL;
114    host -> receivedDataLength = 0;
115     
116    host -> totalSentData = 0;
117    host -> totalSentPackets = 0;
118    host -> totalReceivedData = 0;
119    host -> totalReceivedPackets = 0;
120
121    host -> compressor.context = NULL;
122    host -> compressor.compress = NULL;
123    host -> compressor.decompress = NULL;
124    host -> compressor.destroy = NULL;
125
126    enet_list_clear (& host -> dispatchQueue);
127
128    for (currentPeer = host -> peers;
129         currentPeer < & host -> peers [host -> peerCount];
130         ++ currentPeer)
131    {
132       currentPeer -> host = host;
133       currentPeer -> incomingPeerID = currentPeer - host -> peers;
134       currentPeer -> outgoingSessionID = currentPeer -> incomingSessionID = 0xFF;
135       currentPeer -> data = NULL;
136
137       enet_list_clear (& currentPeer -> acknowledgements);
138       enet_list_clear (& currentPeer -> sentReliableCommands);
139       enet_list_clear (& currentPeer -> sentUnreliableCommands);
140       enet_list_clear (& currentPeer -> outgoingReliableCommands);
141       enet_list_clear (& currentPeer -> outgoingUnreliableCommands);
142       enet_list_clear (& currentPeer -> dispatchedCommands);
143
144       enet_peer_reset (currentPeer);
145    }
146
147    return host;
148}
149
150/** Destroys the host and all resources associated with it.
151    @param host pointer to the host to destroy
152*/
153void
154enet_host_destroy (ENetHost * host)
155{
156    ENetPeer * currentPeer;
157
158    if (host -> socket4 != ENET_SOCKET_NULL)
159      enet_socket_destroy (host -> socket4);
160    if (host -> socket6 != ENET_SOCKET_NULL)
161      enet_socket_destroy (host -> socket6);
162
163    for (currentPeer = host -> peers;
164         currentPeer < & host -> peers [host -> peerCount];
165         ++ currentPeer)
166    {
167       enet_peer_reset (currentPeer);
168    }
169
170    if (host -> compressor.context != NULL && host -> compressor.destroy)
171      (* host -> compressor.destroy) (host -> compressor.context);
172
173    enet_free (host -> peers);
174    enet_free (host);
175}
176
177/** Initiates a connection to a foreign host.
178    @param host host seeking the connection
179    @param address destination for the connection
180    @param channelCount number of channels to allocate
181    @param data user data supplied to the receiving host
182    @returns a peer representing the foreign host on success, NULL on failure
183    @remarks The peer returned will have not completed the connection until enet_host_service()
184    notifies of an ENET_EVENT_TYPE_CONNECT event for the peer.
185*/
186ENetPeer *
187enet_host_connect (ENetHost * host, const ENetAddress * address, size_t channelCount, enet_uint32 data)
188{
189    ENetPeer * currentPeer;
190    ENetChannel * channel;
191    ENetProtocol command;
192
193    if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
194      channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
195    else
196    if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
197      channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
198
199    for (currentPeer = host -> peers;
200         currentPeer < & host -> peers [host -> peerCount];
201         ++ currentPeer)
202    {
203       if (currentPeer -> state == ENET_PEER_STATE_DISCONNECTED)
204         break;
205    }
206
207    if (currentPeer >= & host -> peers [host -> peerCount])
208      return NULL;
209
210    currentPeer -> channels = (ENetChannel *) enet_malloc (channelCount * sizeof (ENetChannel));
211    if (currentPeer -> channels == NULL)
212      return NULL;
213    currentPeer -> channelCount = channelCount;
214    currentPeer -> state = ENET_PEER_STATE_CONNECTING;
215    currentPeer -> address = * address;
216    currentPeer -> connectID = ++ host -> randomSeed;
217
218    if (host -> outgoingBandwidth == 0)
219      currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
220    else
221      currentPeer -> windowSize = (host -> outgoingBandwidth /
222                                    ENET_PEER_WINDOW_SIZE_SCALE) * 
223                                      ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
224
225    if (currentPeer -> windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
226      currentPeer -> windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
227    else
228    if (currentPeer -> windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
229      currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
230         
231    for (channel = currentPeer -> channels;
232         channel < & currentPeer -> channels [channelCount];
233         ++ channel)
234    {
235        channel -> outgoingReliableSequenceNumber = 0;
236        channel -> outgoingUnreliableSequenceNumber = 0;
237        channel -> incomingReliableSequenceNumber = 0;
238
239        enet_list_clear (& channel -> incomingReliableCommands);
240        enet_list_clear (& channel -> incomingUnreliableCommands);
241
242        channel -> usedReliableWindows = 0;
243        memset (channel -> reliableWindows, 0, sizeof (channel -> reliableWindows));
244    }
245       
246    command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
247    command.header.channelID = 0xFF;
248    command.connect.outgoingPeerID = ENET_HOST_TO_NET_16 (currentPeer -> incomingPeerID);
249    command.connect.incomingSessionID = currentPeer -> incomingSessionID;
250    command.connect.outgoingSessionID = currentPeer -> outgoingSessionID;
251    command.connect.mtu = ENET_HOST_TO_NET_32 (currentPeer -> mtu);
252    command.connect.windowSize = ENET_HOST_TO_NET_32 (currentPeer -> windowSize);
253    command.connect.channelCount = ENET_HOST_TO_NET_32 (channelCount);
254    command.connect.incomingBandwidth = ENET_HOST_TO_NET_32 (host -> incomingBandwidth);
255    command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth);
256    command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleInterval);
257    command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleAcceleration);
258    command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleDeceleration);
259    command.connect.connectID = currentPeer -> connectID;
260    command.connect.data = ENET_HOST_TO_NET_32 (data);
261 
262    enet_peer_queue_outgoing_command (currentPeer, & command, NULL, 0, 0);
263
264    return currentPeer;
265}
266
267/** Queues a packet to be sent to all peers associated with the host.
268    @param host host on which to broadcast the packet
269    @param channelID channel on which to broadcast
270    @param packet packet to broadcast
271*/
272void
273enet_host_broadcast (ENetHost * host, enet_uint8 channelID, ENetPacket * packet)
274{
275    ENetPeer * currentPeer;
276
277    for (currentPeer = host -> peers;
278         currentPeer < & host -> peers [host -> peerCount];
279         ++ currentPeer)
280    {
281       if (currentPeer -> state != ENET_PEER_STATE_CONNECTED)
282         continue;
283
284       enet_peer_send (currentPeer, channelID, packet);
285    }
286
287    if (packet -> referenceCount == 0)
288      enet_packet_destroy (packet);
289}
290
291/** Sets the packet compressor the host should use to compress and decompress packets.
292    @param host host to enable or disable compression for
293    @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled
294*/
295void
296enet_host_compress (ENetHost * host, const ENetCompressor * compressor)
297{
298    if (host -> compressor.context != NULL && host -> compressor.destroy)
299      (* host -> compressor.destroy) (host -> compressor.context);
300
301    if (compressor)
302      host -> compressor = * compressor;
303    else
304      host -> compressor.context = NULL;
305}
306
307/** Limits the maximum allowed channels of future incoming connections.
308    @param host host to limit
309    @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
310*/
311void
312enet_host_channel_limit (ENetHost * host, size_t channelLimit)
313{
314    if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
315      channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
316    else
317    if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
318      channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
319
320    host -> channelLimit = channelLimit;
321}
322
323
324/** Adjusts the bandwidth limits of a host.
325    @param host host to adjust
326    @param incomingBandwidth new incoming bandwidth
327    @param outgoingBandwidth new outgoing bandwidth
328    @remarks the incoming and outgoing bandwidth parameters are identical in function to those
329    specified in enet_host_create().
330*/
331void
332enet_host_bandwidth_limit (ENetHost * host, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth)
333{
334    host -> incomingBandwidth = incomingBandwidth;
335    host -> outgoingBandwidth = outgoingBandwidth;
336    host -> recalculateBandwidthLimits = 1;
337}
338
339void
340enet_host_bandwidth_throttle (ENetHost * host)
341{
342    enet_uint32 timeCurrent = enet_time_get (),
343           elapsedTime = timeCurrent - host -> bandwidthThrottleEpoch,
344           peersTotal = 0,
345           dataTotal = 0,
346           peersRemaining,
347           bandwidth,
348           throttle = 0,
349           bandwidthLimit = 0;
350    int needsAdjustment;
351    ENetPeer * peer;
352    ENetProtocol command;
353
354    if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
355      return;
356
357    for (peer = host -> peers;
358         peer < & host -> peers [host -> peerCount];
359         ++ peer)
360    {
361        if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)
362          continue;
363
364        ++ peersTotal;
365        dataTotal += peer -> outgoingDataTotal;
366    }
367
368    if (peersTotal == 0)
369      return;
370
371    peersRemaining = peersTotal;
372    needsAdjustment = 1;
373
374    if (host -> outgoingBandwidth == 0)
375      bandwidth = ~0;
376    else
377      bandwidth = (host -> outgoingBandwidth * elapsedTime) / 1000;
378
379    while (peersRemaining > 0 && needsAdjustment != 0)
380    {
381        needsAdjustment = 0;
382       
383        if (dataTotal < bandwidth)
384          throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
385        else
386          throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
387
388        for (peer = host -> peers;
389             peer < & host -> peers [host -> peerCount];
390             ++ peer)
391        {
392            enet_uint32 peerBandwidth;
393           
394            if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
395                peer -> incomingBandwidth == 0 ||
396                peer -> outgoingBandwidthThrottleEpoch == timeCurrent)
397              continue;
398
399            peerBandwidth = (peer -> incomingBandwidth * elapsedTime) / 1000;
400            if ((throttle * peer -> outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
401              continue;
402
403            peer -> packetThrottleLimit = (peerBandwidth * 
404                                            ENET_PEER_PACKET_THROTTLE_SCALE) / peer -> outgoingDataTotal;
405           
406            if (peer -> packetThrottleLimit == 0)
407              peer -> packetThrottleLimit = 1;
408           
409            if (peer -> packetThrottle > peer -> packetThrottleLimit)
410              peer -> packetThrottle = peer -> packetThrottleLimit;
411
412            peer -> outgoingBandwidthThrottleEpoch = timeCurrent;
413
414           
415            needsAdjustment = 1;
416            -- peersRemaining;
417            bandwidth -= peerBandwidth;
418            dataTotal -= peerBandwidth;
419        }
420    }
421
422    if (peersRemaining > 0)
423    for (peer = host -> peers;
424         peer < & host -> peers [host -> peerCount];
425         ++ peer)
426    {
427        if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
428            peer -> outgoingBandwidthThrottleEpoch == timeCurrent)
429          continue;
430
431        peer -> packetThrottleLimit = throttle;
432
433        if (peer -> packetThrottle > peer -> packetThrottleLimit)
434          peer -> packetThrottle = peer -> packetThrottleLimit;
435    }
436   
437    if (host -> recalculateBandwidthLimits)
438    {
439       host -> recalculateBandwidthLimits = 0;
440
441       peersRemaining = peersTotal;
442       bandwidth = host -> incomingBandwidth;
443       needsAdjustment = 1;
444
445       if (bandwidth == 0)
446         bandwidthLimit = 0;
447       else
448       while (peersRemaining > 0 && needsAdjustment != 0)
449       {
450           needsAdjustment = 0;
451           bandwidthLimit = bandwidth / peersRemaining;
452
453           for (peer = host -> peers;
454                peer < & host -> peers [host -> peerCount];
455                ++ peer)
456           {
457               if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
458                   peer -> incomingBandwidthThrottleEpoch == timeCurrent)
459                 continue;
460
461               if (peer -> outgoingBandwidth > 0 &&
462                   peer -> outgoingBandwidth >= bandwidthLimit)
463                 continue;
464
465               peer -> incomingBandwidthThrottleEpoch = timeCurrent;
466 
467               needsAdjustment = 1;
468               -- peersRemaining;
469               bandwidth -= peer -> outgoingBandwidth;
470           }
471       }
472
473       for (peer = host -> peers;
474            peer < & host -> peers [host -> peerCount];
475            ++ peer)
476       {
477           if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)
478             continue;
479
480           command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
481           command.header.channelID = 0xFF;
482           command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth);
483
484           if (peer -> incomingBandwidthThrottleEpoch == timeCurrent)
485             command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (peer -> outgoingBandwidth);
486           else
487             command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (bandwidthLimit);
488
489           enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0);
490       } 
491    }
492
493    host -> bandwidthThrottleEpoch = timeCurrent;
494
495    for (peer = host -> peers;
496         peer < & host -> peers [host -> peerCount];
497         ++ peer)
498    {
499        peer -> incomingDataTotal = 0;
500        peer -> outgoingDataTotal = 0;
501    }
502}
503   
504/** @} */
Note: See TracBrowser for help on using the repository browser.