2
Grapple - A fully featured network layer with a simple interface
3
Copyright (C) 2006 Michael Simms
5
This library is free software; you can redistribute it and/or
6
modify it under the terms of the GNU Lesser General Public
7
License as published by the Free Software Foundation; either
8
version 2.1 of the License, or (at your option) any later version.
10
This library is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
Lesser General Public License for more details.
15
You should have received a copy of the GNU Lesser General Public
16
License along with this library; if not, write to the Free Software
17
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20
michael@linuxgamepublishing.com
25
#include <sys/types.h>
26
#include <sys/socket.h>
27
#include <sys/select.h>
29
#include <netinet/in.h>
33
#include <arpa/inet.h>
35
#include <sys/ioctl.h>
38
#include <linux/limits.h>
40
#include <openssl/ssl.h>
44
#define MSG_DONTWAIT 0x40
47
#include "dynstring.h"
50
extern int gethostname (char *, size_t);
52
static int socket_udp2way_connectmessage(socketbuf *);
53
static int socket_udp2way_listener_data_process(socketbuf *,
55
size_t,signed char *,int);
56
static int socket_udp2way_reader_data_process(socketbuf *sock,
57
signed char *buf,int datalen);
61
//Handle the SSL errors
63
static int ssl_process_error(SSL *ssl,int rv)
65
switch (SSL_get_error(ssl,rv))
68
case SSL_ERROR_WANT_READ:
69
case SSL_ERROR_WANT_WRITE:
70
case SSL_ERROR_WANT_CONNECT:
71
case SSL_ERROR_WANT_ACCEPT:
72
rv=0; //Set rv (the retutn value) to 0 for each of these errors
74
case SSL_ERROR_ZERO_RETURN:
75
case SSL_ERROR_WANT_X509_LOOKUP:
76
case SSL_ERROR_SYSCALL:
83
//Function to initialise the socket to be encrypted
84
static void socket_set_listener_encrypted(socketbuf *sock)
88
SSL_METHOD *ssl_meth=0;
90
ssl_meth=SSLv23_server_method();
92
sock->ctx = SSL_CTX_new(ssl_meth);
96
sock->flags |= SOCKET_DEAD;
100
if (!sock->server_cert_file || !*sock->server_cert_file ||
101
!sock->server_key_file || !*sock->server_key_file)
104
sock->flags |= SOCKET_DEAD;
108
rv=SSL_CTX_use_certificate_file(sock->ctx,sock->server_cert_file,
111
rv=SSL_CTX_use_RSAPrivateKey_file(sock->ctx,sock->server_key_file,
114
if (!SSL_CTX_check_private_key(sock->ctx))
116
printf("Private key does not match the certificate public key\n");
118
sock->flags |= SOCKET_DEAD;
122
//It has all initialised correctly, set it as encrypted
126
//Set the socket to be a host type encrypted socket - so other sockets will
128
static void socket_set_server_encrypted(socketbuf *sock)
132
if (sock->encrypted==2)
134
sock->ctx = sock->parent->ctx;
138
sock->flags |= SOCKET_DEAD;
142
sock->ssl = SSL_new(sock->ctx);
145
SSL_CTX_free(sock->ctx);
148
sock->flags |= SOCKET_DEAD;
152
SSL_set_fd(sock->ssl,sock->fd);
157
if (sock->encrypted==3)
159
rv=SSL_accept(sock->ssl);
163
rv=ssl_process_error(sock->ssl,rv);
168
SSL_CTX_free(sock->ctx);
175
sock->flags |= SOCKET_DEAD;
185
if (sock->encrypted==4)
187
if (!strcmp(SSL_get_cipher(sock->ssl),"(NONE)"))
189
SSL_CTX_free(sock->ctx);
196
sock->flags |= SOCKET_DEAD;
201
SSL_set_mode(sock->ssl,
202
SSL_get_mode(sock->ssl)|SSL_MODE_ENABLE_PARTIAL_WRITE);
204
//It worked, note it as an encrypted socket
210
//Set this socket up to be an encryption client that will verift against the
212
static void socket_set_client_encrypted(socketbuf *sock)
214
SSL_METHOD *ssl_meth=0;
217
if (sock->encrypted==2)
219
ssl_meth=SSLv23_client_method();
221
sock->ctx = SSL_CTX_new(ssl_meth);
225
sock->flags |= SOCKET_DEAD;
229
sock->ssl=SSL_new(sock->ctx);
232
SSL_CTX_free(sock->ctx);
235
sock->flags |= SOCKET_DEAD;
239
if (sock->client_ca_file)
241
rv=SSL_CTX_load_verify_locations(sock->ctx,sock->client_ca_file,NULL);
245
SSL_CTX_free(sock->ctx);
248
sock->flags |= SOCKET_DEAD;
253
SSL_set_fd(sock->ssl,sock->fd);
258
if (sock->encrypted==3)
260
rv=SSL_connect(sock->ssl);
264
rv=ssl_process_error(sock->ssl,rv);
269
SSL_CTX_free(sock->ctx);
276
sock->flags |= SOCKET_DEAD;
286
if (sock->encrypted==4)
288
if (!strcmp(SSL_get_cipher(sock->ssl),"(NONE)"))
290
SSL_CTX_free(sock->ctx);
297
sock->flags |= SOCKET_DEAD;
302
if (sock->client_ca_file)
304
//Now we verify that the cert we have is good
305
rv=SSL_get_verify_result(sock->ssl);
309
SSL_CTX_free(sock->ctx);
316
sock->flags |= SOCKET_DEAD;
322
SSL_set_mode(sock->ssl,
323
SSL_get_mode(sock->ssl)|SSL_MODE_ENABLE_PARTIAL_WRITE);
331
static void socket_process_ssl(socketbuf *sock)
333
if (sock->flags & SOCKET_INCOMING)
334
socket_set_server_encrypted(sock);
336
socket_set_client_encrypted(sock);
341
//Simple debug function that reports all socket data to a file, the filename
342
//based on the fd number
343
static void socket_data_debug(socketbuf *sock,char *buf,int len,int writer)
347
char filename[PATH_MAX];
351
sprintf(filename,"/tmp/socket_%d.write",sock->fd);
353
sprintf(filename,"/tmp/socket_%d.read",sock->fd);
355
//Open the file for appending
356
fp=fopen(filename,"a");
359
//Write the bytes into the file, on oneline. If the value is printable
360
//also write the character, as this can help debugging some streams
361
for (loopa=0;loopa<len;loopa++)
363
if (isprint(buf[loopa]))
364
fprintf(fp,"%d(%c) ",buf[loopa],buf[loopa]);
366
fprintf(fp,"%d ",buf[loopa]);
369
//Finish off with a newline
372
//Close the file, we're done
379
//Generic function to write data to the socket. This is called from
380
//outside. We do NOT actually write the data to the socket at this stage, we
381
//just add it to a buffer
382
void socket_write(socketbuf *sock,
383
const char *data,size_t len)
385
socket_intchar udplen,udpdata;
388
//If we are using UDP we need to do it differently, as UDP sends discrete
389
//packets not a stream
390
if (sock->protocol==SOCKET_UDP)
392
//Calculate how long the length will be of the UDP packet
396
//It will be 4 extra bytes if it is a 2 way UDP
398
if (sock->udp2w_infd)
399
//And an extra 4 if we have the incoming socket ready
406
//So, the first data goes in, this is the length of the following data
407
//This happens for all UDP packets, so the buffer knows how long to send
410
dynstringRawappend(sock->outdata,udplen.c,4);
414
//Then for 2 way UDP, we send the protocol - we are sending user
415
//data not a low level protocol packet
416
udpdata.i=htonl(SOCKET_UDP2W_PROTOCOL_DATA);
417
dynstringRawappend(sock->outdata,udpdata.c,4);
418
if (sock->udp2w_infd)
420
//We then send the port number of the return port, if we have one
421
udpdata.i=htonl(sock->udp2w_port);
422
dynstringRawappend(sock->outdata,udpdata.c,4);
428
//Now we simply append the data itself. If this is TCP thats all we need
429
//to do, as TCP sends a whole stream, its up to the client to rebuild
430
//it, with UDP we have made and sent a header
431
dynstringRawappend(sock->outdata,data,len);
432
sock->bytes_out+=len;
437
//rdata is the resend data, used on reliable UDP packets to resend
438
//packets that may have gone missing. Here we delete one from a
439
//linked list. Any linked list, we dont care
440
static socket_udp_rdata *socket_rdata_delete(socket_udp_rdata *list,
441
socket_udp_rdata *target)
443
if (target->next==target)
449
target->next->prev=target->prev;
450
target->prev->next=target->next;
462
//This function locates a rdata packet by its ID from a list
463
static socket_udp_rdata *socket_rdata_locate_packetnum(socket_udp_rdata *list,
466
socket_udp_rdata *scan;
470
//Scan through the list
473
if (scan->packetnum==packetnum)
474
//We have a match, return it
479
//Come to the end of the list (it is circular)
483
//No match, return NULL
487
//Allocate an rdata packet and put it into a list
488
static socket_udp_rdata *rdata_allocate(socket_udp_rdata *list,
490
const char *data,int len,int sent)
492
socket_udp_rdata *newpacket;
494
//Allocate the memory
495
newpacket=(socket_udp_rdata *)calloc(1,sizeof(socket_udp_rdata));
497
//Allocate the data segment memory
498
newpacket->data=(char *)malloc(len);
499
memcpy(newpacket->data,data,len);
501
newpacket->length=len;
502
newpacket->sent=sent;
505
gettimeofday(&newpacket->sendtime,NULL);
507
newpacket->packetnum=packetnum;
509
//Link this into the list we have supplied
512
newpacket->next=list;
513
newpacket->prev=list->prev;
514
newpacket->prev->next=newpacket;
515
newpacket->next->prev=newpacket;
520
newpacket->next=newpacket;
521
newpacket->prev=newpacket;
527
//Write a data packet in reliable mode
528
void socket_write_reliable(socketbuf *sock,
529
const char *data,size_t len)
531
socket_intchar udplen,udpdata;
532
int newlen,packetnum;
534
//If we arent using 2 way UDP, we just send, as we cant have reliable one way
535
//UDP and UDP is the only protocol we support that is unreliable
536
if (sock->protocol!=SOCKET_UDP || !sock->udp2w)
543
//Incriment the outbound packet number
544
packetnum=sock->udp2w_routpacket++;
546
//Calculate the length of the data
548
if (sock->udp2w_infd)
553
//Send the length first //This does NOT get htonl'd as it gets stripped
554
//before actually sending it
556
dynstringRawappend(sock->outdata,udplen.c,4);
559
udpdata.i=htonl(SOCKET_UDP2W_PROTOCOL_RDATA);
561
dynstringRawappend(sock->outdata,udpdata.c,4);
563
if (sock->udp2w_infd)
565
//Then the port number
566
udpdata.i=htonl(sock->udp2w_port);
567
dynstringRawappend(sock->outdata,udpdata.c,4);
570
//Then the packet number, so the other end keeps in sync
571
udpdata.i=htonl(packetnum);
572
dynstringRawappend(sock->outdata,udpdata.c,4);
574
//Then the data itself
575
dynstringRawappend(sock->outdata,data,len);
576
sock->bytes_out+=len;
578
//Add this packet to the RDATA out list, so we know to resend it if we
579
//dont get a confirmation of the receipt
580
sock->udp2w_rdata_out=rdata_allocate(sock->udp2w_rdata_out,
587
//Just a user accessible function to return the number of bytes received
588
size_t socket_bytes_in(socketbuf *sock)
590
return sock->bytes_in;
593
//Just a user accessible function to return the number of bytes sent
594
size_t socket_bytes_out(socketbuf *sock)
596
return sock->bytes_out;
599
//Sockets are processed out of a 'processlist' - which is a linked list
600
//of socketbuf's. This function adds a socketbuf to a processlist. It creates
601
//a processlist object to hold the socketbuf
602
socket_processlist *socket_link(socket_processlist *list,socketbuf *sock)
604
socket_processlist *newitem;
605
newitem=(socket_processlist *)malloc(sizeof(socket_processlist));
610
newitem->next=newitem;
611
newitem->prev=newitem;
617
newitem->prev=list->prev;
619
newitem->next->prev=newitem;
620
newitem->prev->next=newitem;
625
//And this function unlinks a socketbuf from a processlist. It also frees the
626
//processlist container that held the socketbuf
627
socket_processlist *socket_unlink(socket_processlist *list,socketbuf *sock)
629
socket_processlist *scan;
631
if (list->next==list)
633
if (list->sock!=sock)
644
if (scan->sock==sock)
646
scan->prev->next=scan->next;
647
scan->next->prev=scan->prev;
661
//This is the basic function for creating a socketbuf object around a
663
static socketbuf *socket_create(int fd)
665
socketbuf *returnval;
667
//Allocate the memory for the socket
668
returnval=(socketbuf *)calloc(1,sizeof(socketbuf));
670
//Give it a small in and out buffer - these resize dynamically so it doesnt
671
//really matter what size we give it. 128 is a fairly small number in case
672
//the socket only sends small bits of data, this saves over-allocating.
673
returnval->indata=dynstringInit(128);
674
returnval->outdata=dynstringInit(128);
676
//Set the file descriptor into the structure
679
//Thats it, we have our socketbuf. Much more wil happen to this depending
680
//on what the type of socket being made is, this data will be filled in
681
//by the function that calls this one.
685
//We are destroying a socket. We are also however needing to be careful that
686
//we destroy any connecting sockets if this is a listener.
687
void socket_destroy(socketbuf *sock)
691
while (sock->new_children)
693
//Now we MUST destroy this, they are connecting sockets who have
694
//no parent, if we dont destroy now we will leak memory
695
//This will, incidentally, cascade down, destroying always the last
696
//one in the tree, and then roll back up to here
697
socket_destroy(sock->new_children);
700
//Here we must now also disconnect all connected children. These have been
701
//accessed by the parent program and so it is not our responsibility to
702
//keep track of them. Why did we keep them in a list in the first place?
703
//Well, things like UDP, all data comes in on the listener, not on a
704
//socket dedicated to the other end, so we need to have a list of all
705
//who have connected, so we know who to send the data to/
706
scan=sock->connected_children;
709
if (scan->parent==sock)
712
scan=scan->connected_child_next;
713
if (scan==sock->connected_children)
717
//If we have a parent, then unlink ourselves from the parent, so that
718
//this socket is no longer in contention for any data received by the
719
//parent socket, if it is UDP
722
if (sock->new_child_next)
724
if (sock->parent->new_children==sock)
725
sock->parent->new_children=sock->new_child_next;
726
if (sock->parent->new_children==sock)
727
sock->parent->new_children=NULL;
730
if (sock->connected_child_next)
732
if (sock->parent->connected_children==sock)
733
sock->parent->connected_children=sock->connected_child_next;
734
if (sock->parent->connected_children==sock)
735
sock->parent->connected_children=NULL;
739
//Unlink ourselves from the list of sockets connected to the same
740
//parent, which can be intact even if the parent is gone.
741
if (sock->new_child_next)
743
sock->new_child_next->new_child_prev=sock->new_child_prev;
744
sock->new_child_prev->new_child_next=sock->new_child_next;
747
if (sock->connected_child_next)
749
sock->connected_child_next->connected_child_prev=sock->connected_child_prev;
750
sock->connected_child_prev->connected_child_next=sock->connected_child_next;
753
//Finally we have done the internal management, we need to actually
754
//destroy the socket!
757
//If we have the socket, kill it
759
if (sock->flags & SOCKET_CONNECTED)
760
//shutdown, if its connected
761
shutdown(sock->fd,0);
763
//Then close the socket
766
//The data socket itself is now disconnected.
768
//On a 2 way UDP, we need to also close the other socket
769
if (sock->udp2w_infd)
771
//If we have the socket, kill it
773
//shutdown, if its connected
774
shutdown(sock->udp2w_infd,0);
776
//Then close the socket
777
close(sock->udp2w_infd);
779
//The udp2w_infd socket itself is now disconnected.
781
//On an interrupt docket we have a different one
782
if (sock->interrupt_fd)
784
//If we have the socket, kill it
786
//shutdown, if its connected
787
shutdown(sock->interrupt_fd,0);
789
//Then close the socket
790
close(sock->interrupt_fd);
793
//Free the memory used in the transmit and receive queues
795
dynstringUninit(sock->indata);
798
dynstringUninit(sock->outdata);
800
//Free the resend data queues, we dont need them any more, any data that
801
//still hasnt made it isnt going to now.
802
while (sock->udp2w_rdata_out)
803
sock->udp2w_rdata_out=socket_rdata_delete(sock->udp2w_rdata_out,
804
sock->udp2w_rdata_out);
805
while (sock->udp2w_rdata_in)
806
sock->udp2w_rdata_in=socket_rdata_delete(sock->udp2w_rdata_in,
807
sock->udp2w_rdata_in);
813
//Free the pathname (applies to unix sockets only)
816
if (sock->flags & SOCKET_LISTENER)
821
//Free the socket data, we are done
827
//Create the listener socket for a unix connection
828
socketbuf *socket_create_unix_wait(const char *path,int wait)
831
socketbuf *returnval;
832
struct sockaddr_un sa;
841
//We must specify a path in the filesystem, that is where the socket lives.
842
//Without it, no way to create it.
846
//create the sockets file descriptor
847
fd=socket(PF_UNIX,SOCK_STREAM,0);
851
//Socket creation failed.
855
memset(&sa,0,sizeof(struct sockaddr_in));
857
//Set the fd as a UNIX socket
858
sa.sun_family = AF_UNIX;
859
strcpy(sa.sun_path,path);
861
//Set non-blocking, so we can check for a data without freezing. If we
862
//fail to set non-blocking we must abort, we require it.
866
if (ioctl(fd,FIONBIO,&dummy)<0)
873
flags=fcntl(fd,F_GETFL,0);
881
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK)<0)
888
# error No valid non-blocking method - cannot build;
889
# endif // O_NONBLOCK
893
//We have the good file descriptor, set it into a socketbuf structure
894
returnval=socket_create(fd);
897
returnval->protocol=SOCKET_UNIX;
900
returnval->path=(char *)malloc(strlen(path)+1);
901
strcpy(returnval->path,path);
903
//Up to now this has all been preparation, now we actually connect to the
905
if (connect(fd,(struct sockaddr *)&sa,sizeof(sa))==0)
907
//Connect was successful, we can finish this here
908
returnval->flags |= SOCKET_CONNECTED;
909
returnval->connect_time=time(NULL);
914
//The connection is 'in progress'
915
if (errno==EINPROGRESS)
917
//Connect was possibly OK, but we havent finished, come back
918
//and check later with select
919
returnval->flags|=SOCKET_CONNECTING;
923
//We were called with the option NOT to wait for it to connect, so
924
//we return here. It is now the responsibility of the caller to
925
//process this socket occasionally and see if it has now connected
926
//or if the connection failed.
932
//We were asked to keep waiting for the socket to connect
933
while (returnval->flags & SOCKET_CONNECTING)
935
//To test if we have connected yet, we select on the socket,
936
//to see if its writer returns
938
FD_SET(returnval->fd,&writer);
940
//We need to wait, as long as it takes, so we set no timeout
941
selectnum=select(FD_SETSIZE,0,&writer,0,NULL);
943
//The select failed, this means an error, we couldnt connect
946
socket_destroy(returnval);
952
//At least one socket (it has to be us) returned data
953
if (FD_ISSET(returnval->fd,&writer))
957
returnval->flags &=~ SOCKET_CONNECTING;
958
returnval->flags |= SOCKET_CONNECTED;
959
returnval->connect_time=time(NULL);
967
//It was an error, and a bad one, close this
968
socket_destroy(returnval);
973
//Create a wakeup socket
974
socketbuf *socket_create_interrupt(void)
977
socketbuf *returnval;
985
//create the sockets file descriptor
989
//Set non-blocking, so we can check for a data without freezing. If we
990
//fail to set non-blocking we must abort, we require it.
994
if (ioctl(fd[0],FIONBIO,&dummy)<0)
1003
if (ioctl(fd[1],FIONBIO,&dummy)<0)
1012
flags=fcntl(fd[0],F_GETFL,0);
1021
if (fcntl(fd[0],F_SETFL,flags|O_NONBLOCK)<0)
1028
flags=fcntl(fd[1],F_GETFL,0);
1037
if (fcntl(fd[1],F_SETFL,flags|O_NONBLOCK)<0)
1045
# error No valid non-blocking method - cannot build;
1046
# endif // O_NONBLOCK
1050
//We have the good file descriptor, set it into a socketbuf structure
1051
returnval=socket_create(fd[0]);
1052
returnval->interrupt_fd=fd[1];
1055
returnval->protocol=SOCKET_INTERRUPT;
1057
returnval->flags |= SOCKET_CONNECTED;
1059
returnval->connect_time=time(NULL);
1064
int socket_interrupt(socketbuf *sock)
1066
if (sock && sock->protocol==SOCKET_INTERRUPT)
1068
write(sock->interrupt_fd,"0",1);
1075
//Create a TCPIP connection to a remote socket
1076
socketbuf *socket_create_inet_tcp_wait(const char *host,int port,int wait)
1079
socketbuf *returnval;
1080
struct sockaddr_in sa;
1081
int dummy,selectnum;
1082
struct in_addr inet_address;
1085
struct sockaddr_in peername;
1093
//We need the hostname, where will we connect without one
1094
if (!host || !*host)
1098
fd=socket(AF_INET,SOCK_STREAM,0);
1102
//Basic socket connection failed, this really shouldnt happen
1106
memset(&sa,0,sizeof(struct sockaddr_in));
1109
hp=gethostbyname(host);
1111
//We cant resolve the hostname
1112
inet_address.s_addr=-1;
1114
//We have the hostname
1115
memcpy((char *)&inet_address,hp->h_addr,sizeof(struct in_addr));
1117
//The hostname was unresolvable, we cant connect to it
1118
if (inet_address.s_addr==-1)
1124
//Set the socket data
1125
sa.sin_family=AF_INET;
1126
sa.sin_port=htons(port);
1127
sa.sin_addr=inet_address;
1131
setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char *)&dummy,sizeof(dummy));
1134
//Set non-blocking, so we can check for a data without freezing
1139
if (ioctl(fd,FIONBIO,&dummy)<0)
1146
flags=fcntl(fd,F_GETFL,0);
1154
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK)<0)
1161
# error No valid non-blocking method - cannot build;
1162
# endif // O_NONBLOCK
1166
//We have a valid socket, now we wrap a socketbuf around it
1167
returnval=socket_create(fd);
1170
returnval->protocol=SOCKET_TCP;
1172
//Note the hostname and the portnumber in the structure
1173
returnval->host=(char *)malloc(strlen(host)+1);
1174
strcpy(returnval->host,host);
1175
returnval->port=port;
1177
//Now try and actually connect to the remote address
1178
if (connect(fd,(struct sockaddr *)&sa,sizeof(sa))==0)
1180
//Connect was successful, we can finish this here
1181
returnval->flags |= SOCKET_CONNECTED;
1182
returnval->connect_time=time(NULL);
1187
//We have an in-progress connection
1188
if (errno==EINPROGRESS)
1190
//Connect was possibly OK, but we havent finished, come back
1191
//and check later with select
1192
returnval->flags|=SOCKET_CONNECTING;
1196
//The caller requested we do not wait for the connection to finish,
1197
//it will now be the callers responsibility to check this using
1203
//We have been requested to keep on waiting for the connection
1204
while (returnval->flags & SOCKET_CONNECTING)
1206
//We do this by selecting on the socket, see what the
1209
FD_SET(returnval->fd,&writer);
1211
//Wait forever if needbe
1212
selectnum=select(FD_SETSIZE,0,&writer,0,NULL);
1216
//There was an error on the select, this means the connection
1217
//has definitely died.
1218
socket_destroy(returnval);
1223
if (FD_ISSET(returnval->fd,&writer))
1225
//We have a writer, but is it ok or has it failed
1226
//to connect, check with getpeername()
1228
peersize=sizeof(struct sockaddr_in);
1230
if (!getpeername(returnval->fd,
1231
(struct sockaddr *)&peername,
1235
returnval->flags &=~ SOCKET_CONNECTING;
1236
returnval->flags |= SOCKET_CONNECTED;
1237
returnval->connect_time=time(NULL);
1243
socket_destroy(returnval);
1252
//It was an error, and a bad one, close this
1253
socket_destroy(returnval);
1258
//Create a UDP socket. Actually this never connects so the
1259
//wait parameter is ignored. It just sets up a route where data can be thrown
1260
//to. With UDP you dont know if it has reached its target or not.
1261
socketbuf *socket_create_inet_udp_wait(const char *host,int port,int wait)
1264
socketbuf *returnval;
1265
struct in_addr inet_address;
1273
//We need to know where to connect to.
1274
if (!host || !*host)
1278
fd=socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
1282
//Now create the data structure around the socket
1283
returnval=socket_create(fd);
1285
memset(&returnval->udp_sa,0,sizeof(struct sockaddr_in));
1287
//Lookup the hostname we are sending to
1288
hp=gethostbyname(host);
1290
inet_address.s_addr=-1;
1292
memcpy((char *)&inet_address,hp->h_addr,sizeof(struct in_addr));
1294
if (inet_address.s_addr==-1)
1296
//We couldnt resolve the address, destroy the socket
1297
socket_destroy(returnval);
1302
//Save the data for later use in the datastruct
1303
returnval->udp_sa.sin_family=AF_INET;
1304
returnval->udp_sa.sin_port=htons(port);
1305
returnval->udp_sa.sin_addr.s_addr=inet_address.s_addr;
1308
returnval->protocol=SOCKET_UDP;
1310
//Save the text representation of the address
1311
returnval->host=(char *)malloc(strlen(host)+1);
1312
strcpy(returnval->host,host);
1313
returnval->port=port;
1316
//Set non-blocking, so we can check for a data without freezing
1321
if (ioctl(fd,FIONBIO,&dummy)<0)
1328
flags=fcntl(fd,F_GETFL,0);
1336
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK)<0)
1343
# error No valid non-blocking method - cannot build;
1344
# endif // O_NONBLOCK
1347
//While we technically havent connected, we are ready to send data, and thats
1349
returnval->flags |= SOCKET_CONNECTED;
1350
returnval->connect_time=time(NULL);
1355
//Test to see of a socket is connected
1356
int socket_connected(socketbuf *sock)
1358
if (sock->flags & SOCKET_DEAD)
1359
//A dead socket is never connected
1362
if (sock->flags & SOCKET_CONNECTED)
1369
//Test to see if a socket is dead
1370
int socket_dead(socketbuf *sock)
1372
if (sock->flags & SOCKET_DEAD)
1380
//This function drops a set length of data from the socket This is handy
1381
//For it we have already peeked it, so we HAVE the data, we dont want to
1382
//reallocate. Or if we have a set of data we KNOW is useless
1383
void socket_indata_drop(socketbuf *sock,int len)
1385
//memmove freaks out at a zero length memory move
1389
//Decrease the recorded amount of data stored
1390
sock->indata->len-=len;
1392
if (sock->indata->len<1)
1394
sock->indata->len=0;
1398
//move the later data to the start of the buffer
1399
memmove(sock->indata->buf,sock->indata->buf+len,sock->indata->len);
1404
//This function drops a set length of data from the socket OUTBUFFER
1405
//This is dangerous and is only an internal function, dont let the end user
1406
//do it or the whole socket could break, especially in UDP
1407
static void socket_outdata_drop(socketbuf *sock,int len)
1409
//memmove freaks out at a zero length memory move
1413
//Decriment the recorded amount of data
1414
sock->outdata->len-=len;
1416
if (sock->outdata->len<1)
1418
sock->outdata->len=0;
1422
//Move the rest to the start
1423
memmove(sock->outdata->buf,sock->outdata->buf+len,sock->outdata->len);
1428
//Free a UDP data packet Fairly obvious
1429
int socket_udp_data_free(socket_udp_data *data)
1438
//A 2 way UDP socket has received some data on its return socket
1439
static socket_udp_data *socket_udp2way_indata_action(socketbuf *sock,int pull)
1441
socket_udp_data *returnval;
1445
//All data must be at least 4 bytes - this is the length of the data in the
1447
if (sock->indata->len<4)
1450
//get the length of the data
1451
memcpy(len.c,sock->indata->buf,4);
1455
//The packet isnt big enough to hold all the data we expected - this is a
1456
//corrupted packet, ABORT!
1457
if (datalen+4 > sock->indata->len)
1460
//Create an internal UDP packet to handle the data we have received
1461
returnval=(socket_udp_data *)calloc(1,sizeof(socket_udp_data));
1463
//Allocate enough buffer for the incoming data
1464
returnval->data=(char *)malloc(datalen);
1465
memcpy(returnval->data,sock->indata->buf+4,datalen);
1467
returnval->length=datalen;
1469
//If we are deleting the data - then do so
1471
socket_indata_drop(sock,datalen+4);
1473
//return the UDP data block
1477
//Receive a packet on a basic UDP socket
1478
static socket_udp_data *socket_udp_indata_action(socketbuf *sock,int pull)
1480
socket_udp_data *returnval;
1485
//We need to have at least 4 bytes as the length of the data in the packet
1486
if (sock->indata->len<4)
1489
//If this is a 2 way UDP socket, process it using 2 way UDP handlers
1491
return socket_udp2way_indata_action(sock,pull);
1493
//Note the length of the sa structure - this is written wholesale
1494
//into the buffer, this is actually OK
1495
memcpy(len.c,sock->indata->buf,4);
1499
//Check we have enough space
1500
if (sa_len+8 > sock->indata->len)
1503
//Find the length of the data now.
1504
memcpy(len.c,sock->indata->buf+4+sa_len,4);
1507
//Check we have the whole data packet
1508
if (sa_len+datalen+8 > sock->indata->len)
1509
//We dont, its corrupt
1512
//Allocate a data structure for the packet
1513
returnval=(socket_udp_data *)calloc(1,sizeof(socket_udp_data));
1515
//Store the sa in the data structure.
1516
memcpy(&returnval->sa,sock->indata->buf+4,sa_len);
1518
//And the data itself
1519
returnval->data=(char *)malloc(datalen);
1520
memcpy(returnval->data,sock->indata->buf+8+sa_len,datalen);
1522
returnval->length=datalen;
1524
//If we are pulling instead of just looking, delete the data from the buffer
1526
socket_indata_drop(sock,8+sa_len+datalen);
1528
//Return the UDP data packet
1533
//Wrapper function for the user to pull UDP data from the buffer
1534
socket_udp_data *socket_udp_indata_pull(socketbuf *sock)
1536
return socket_udp_indata_action(sock,1);
1539
//Wrapper function for the user to look at UDP data without removing it
1541
socket_udp_data *socket_udp_indata_view(socketbuf *sock)
1543
return socket_udp_indata_action(sock,0);
1546
//This is a user function to pull data from any non-UDP socket
1547
char *socket_indata_pull(socketbuf *sock,int len)
1551
//Ensure we dont overrun
1552
if (len > sock->indata->len)
1553
len=sock->indata->len;
1555
//Allocate the return buffer
1556
returnval=(char *)calloc(1,len+1);
1559
memcpy(returnval,sock->indata->buf,len);
1561
//Drop the data from the buffer
1562
socket_indata_drop(sock,len);
1567
//Allows the user to view the buffer
1568
const char *socket_indata_view(socketbuf *sock)
1570
//Just return the buffer. It is returned const so the user cant mess
1572
return (char *)sock->indata->buf;
1575
//Find the length of the incoming data
1576
size_t socket_indata_length(socketbuf *sock)
1578
return sock->indata->len;
1581
size_t socket_outdata_length(socketbuf *sock)
1583
//find the length of data still to send
1584
return sock->outdata->len;
1587
//Read a unix listener socket. Not a user function, this is an internal
1588
//function filtered down to when we know what kind of
1590
static int socket_read_listener_unix(socketbuf *sock)
1594
struct sockaddr_un sa;
1596
struct linger lingerval;
1601
//The length of the data passed into accept
1602
socklen=(socklen_t)sizeof(sa);
1604
//Accept the new connection on this socket
1605
fd = accept(sock->fd,(struct sockaddr *) &sa, &socklen);
1609
//The connection was bad, forget it
1613
//Set non-blocking on the new socket
1616
if (ioctl(fd,FIONBIO,&dummy)<0)
1624
flags=fcntl(fd,F_GETFL,0);
1632
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK) < 0)
1639
# error no valid non-blocking method
1643
//We have a new non-blocking socket
1646
//Set linger on this, to make sure all data possible is sent when the
1648
lingerval.l_onoff=0;
1649
lingerval.l_linger=0;
1650
setsockopt(fd,SOL_SOCKET,SO_LINGER,(char *)&lingerval,
1651
sizeof(struct linger));
1653
//Create the socketbuf to hold the fd
1654
newsock=socket_create(fd);
1655
newsock->protocol=SOCKET_UNIX;
1656
newsock->path=(char *)malloc(strlen(sock->path)+1);
1657
strcpy(newsock->path,sock->path);
1659
//This socket is automatically connected (thats what we've been doing)
1660
newsock->flags |= (SOCKET_CONNECTED|SOCKET_INCOMING);
1662
//Set the mode to be the same as the socket that accepts (mode is things like
1663
//sequential data and the like...
1664
newsock->mode=sock->mode;
1667
newsock->parent=sock;
1669
//This is a new child, it is NOT acknowledged by the parent, so we simply
1670
//put it into a queue waiting for the calling process to acknowledge we
1672
if (sock->new_children)
1674
newsock->new_child_next=sock->new_children;
1675
newsock->new_child_prev=newsock->new_child_next->new_child_prev;
1676
newsock->new_child_next->new_child_prev=newsock;
1677
newsock->new_child_prev->new_child_next=newsock;
1681
newsock->new_child_next=newsock;
1682
newsock->new_child_prev=newsock;
1683
sock->new_children=newsock;
1686
newsock->connect_time=time(NULL);
1689
if (sock->encrypted)
1691
socket_set_server_key(newsock,sock->server_key_file);
1692
socket_set_server_cert(newsock,sock->server_cert_file);
1693
socket_set_encrypted(newsock);
1700
//Some data has been received on the UDP socket. As UDP doesnt have connections
1701
//it just gets data thrown at it, this is unlike other listeners, as we
1702
//dont just create a new socket here, we have to process the data we receive
1704
static int socket_read_listener_inet_udp(socketbuf *sock,int failkill)
1706
int chars_left,chars_read,total_read;
1708
char quickbuf[1024];
1709
struct sockaddr_in sa;
1713
//Check how much data is there to read
1715
if (ioctl(sock->fd,FIONREAD,&chars_left)== -1)
1718
if (ioctl(sock->fd,I_NREAD,&chars_left)== -1)
1720
# error no valid read length method
1726
//The socket had no data, but it was supposed to, that means its
1728
sock->flags|=SOCKET_DEAD;
1738
sock->flags|=SOCKET_DEAD;
1743
//The buffer to store the data in. This is allocated statically as it gets
1744
//used and reused and there is NO point in creating it time and time
1745
//again **change** It wasnt threadsafe - oops
1746
if (chars_left < 1024)
1749
buf=malloc(chars_left);
1753
//Loop while there is data to read
1754
while (chars_left>0)
1756
sa_len=sizeof(struct sockaddr);
1758
//Actually perfrorm the read from the UDP socket
1759
chars_read=recvfrom(sock->fd,
1763
(struct sockaddr *)&sa,
1768
if (errno!=EAGAIN) /*An EAGAIN simply means that it wasnt quite ready
1769
so try again later.*/
1771
//There was an error on the read, dead socket
1772
sock->flags|=SOCKET_DEAD;
1781
//No chars were read, so nothing was ready, try again next time
1787
//Note that the socket received data, this is to stop it timing out,
1788
//as UDP sockets are stateless
1789
sock->udp2w_lastmsg=time(NULL);
1792
//if we are in debug mode, run that now
1794
socket_data_debug(sock,(char *)buf,chars_read,0);
1797
//We are a 2 way UDP socket, process the data via the UDP2W data handler
1799
socket_udp2way_listener_data_process(sock,
1801
(signed char *)buf,chars_read);
1804
//We are a one way UDP socket
1806
//Add the sa to the datastream
1808
dynstringRawappend(sock->indata,len.c,4);
1809
dynstringRawappend(sock->indata,(char *)&sa,sa_len);
1813
dynstringRawappend(sock->indata,len.c,4);
1814
dynstringRawappend(sock->indata,(char *)buf,chars_read);
1816
//Note how many chars have been read, and loop back to see if we have
1817
//another packets worth of data to read
1818
chars_left-=chars_read;
1819
sock->bytes_in+=chars_read;
1820
total_read+=chars_read;
1826
//Try again for more packets, but bear in mind it is OK if there are none, so
1827
//we set the failkill parameter to 0
1828
socket_read_listener_inet_udp(sock,0);
1833
//Read the listener of a TCPIP socket
1834
static int socket_read_listener_inet_tcp(socketbuf *sock)
1838
struct sockaddr_in sa;
1840
struct linger lingerval;
1845
//The length of the data passed into accept
1846
socklen=(socklen_t)sizeof(sa);
1848
//Get the incoming socket
1849
fd = accept(sock->fd,(struct sockaddr *) &sa, &socklen);
1853
//It was a bad socket, drop it
1857
//Set it to be non-blocking
1860
if (ioctl(fd,FIONBIO,&dummy)<0)
1868
flags=fcntl(fd,F_GETFL,0);
1876
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK) < 0)
1883
# error no valid non-blocking method
1888
//Set linger so that the socket will send all its data when it close()s
1889
lingerval.l_onoff=0;
1890
lingerval.l_linger=0;
1891
setsockopt(fd,SOL_SOCKET,SO_LINGER,(char *)&lingerval,
1892
sizeof(struct linger));
1894
//Create the socketbuf to hold the socket
1895
newsock=socket_create(fd);
1896
newsock->protocol=SOCKET_TCP;
1897
newsock->port=ntohs(sa.sin_port);
1898
newsock->host=(char *)malloc(strlen(inet_ntoa(sa.sin_addr))+1);
1899
strcpy(newsock->host,inet_ntoa(sa.sin_addr));
1901
//This is a connected socket so note it as such
1902
newsock->flags |= (SOCKET_CONNECTED|SOCKET_INCOMING);
1903
newsock->mode=sock->mode;
1905
//Link this into the parent so that the calling program can
1906
//actually get hold of this socket
1907
newsock->parent=sock;
1909
if (sock->new_children)
1911
newsock->new_child_next=sock->new_children;
1912
newsock->new_child_prev=newsock->new_child_next->new_child_prev;
1913
newsock->new_child_next->new_child_prev=newsock;
1914
newsock->new_child_prev->new_child_next=newsock;
1918
newsock->new_child_next=newsock;
1919
newsock->new_child_prev=newsock;
1920
sock->new_children=newsock;
1923
newsock->connect_time=time(NULL);
1927
if (sock->encrypted)
1929
socket_set_encrypted(newsock);
1937
//Generic function to wrap all listener read functions. It simply
1938
//Looks at the protocol and calls the appropriate function
1939
static int socket_read_listener(socketbuf *sock)
1941
switch (sock->protocol)
1944
return socket_read_listener_inet_tcp(sock);
1947
return socket_read_listener_inet_udp(sock,1);
1950
return socket_read_listener_unix(sock);
1952
case SOCKET_INTERRUPT:
1957
//Couldnt find a listener handler - erm, that cant happen!
1961
//Read a 2 way UDP socket. This will be the return socket on the client,
1962
//as the outbound is read on the listener. Technicallt this is also a
1963
//listener but it can only belong to one socketbuf so we can skip a load
1964
//of the ownership tests that happen lower down the line
1965
static int socket_udp2way_read(socketbuf *sock,int failkill)
1967
int chars_left,chars_read,total_read;
1969
char quickbuf[1024];
1970
struct sockaddr_in sa;
1974
//Check how much data is there to read
1976
if (ioctl(sock->udp2w_infd,FIONREAD,&chars_left)== -1)
1979
if (ioctl(sock->udp2w_infd,I_NREAD,&chars_left)== -1)
1981
# error no valid read length method
1987
//Kill the socket, there is no data when we expected there would be
1988
sock->flags|=SOCKET_DEAD;
1998
sock->flags|=SOCKET_DEAD;
2003
//The buffer to store the data in. This is allocated statically as it gets
2004
//used and reused and there is NO point in creating it time and time
2006
if (chars_left<1024)
2009
buf=malloc(chars_left+1);
2013
//Loop while there is data to read
2014
while (chars_left>0)
2016
sa_len=sizeof(struct sockaddr);
2018
//Actually perfrorm the read from the UDP socket
2019
chars_read=recvfrom(sock->udp2w_infd,
2023
(struct sockaddr *)&sa,
2028
if (errno!=EAGAIN) /*An EAGAIN simply means that it wasnt quite ready
2029
so try again later.*/
2032
//There was an error on the read, dead socket
2033
sock->flags|=SOCKET_DEAD;
2044
//No chars were read, so nothing was ready, try again next time
2051
//Note that the socket received data, this is to stop it timing out,
2052
//as UDP sockets are stateless
2053
sock->udp2w_lastmsg=time(NULL);
2056
//if we are in debug mode, run that now
2058
socket_data_debug(sock,(char *)buf,chars_read,0);
2061
//We ARE a 2 way UDP socket reader, pass this data off to that
2063
socket_udp2way_reader_data_process(sock,(signed char *)buf,chars_read);
2065
//Note how many chars have been read, and loop back to see if we have
2066
//another packets worth of data to read
2067
chars_left-=chars_read;
2068
sock->bytes_in+=chars_read;
2069
total_read+=chars_read;
2075
//Try again for more packets, but bear in mind it is OK if there are none, so
2076
//we set the failkill parameter to 0
2077
socket_udp2way_read(sock,0);
2082
//This is the generic function called to read data from the socket into the
2083
//socket buffer. This is not called by the user. The user just looks at the
2084
//buffer. This is called fro any type of socket, and the ones that this is not
2085
//appropriate for it just hands off to other functions. This is THE base read
2086
//functionf or ANY socket
2087
static int socket_read(socketbuf *sock)
2089
int chars_left,chars_read,total_read;
2091
char quickbuf[1024];
2093
//Its a listener, read it differently using accepts
2094
if (sock->flags & SOCKET_LISTENER)
2095
return socket_read_listener(sock);
2097
//Its a UDP socket, all readable UDP sockets are listeners, you cant read
2098
//an outbound UDP socket
2099
if (sock->protocol==SOCKET_UDP)
2102
//Check how much data there is coming in
2104
if (ioctl(sock->fd,FIONREAD,&chars_left)== -1)
2107
if (ioctl(sock->fd,I_NREAD,&chars_left)== -1)
2109
# error no valid read length method
2113
//The ioctl failed, this is a dead-socket case
2114
sock->flags|=SOCKET_DEAD;
2121
sock->flags|=SOCKET_DEAD;
2126
//The buffer to store the data in. This is allocated statically as it gets
2127
//used and reused and there is NO point in creating it time and time
2129
if (chars_left < 1024)
2132
buf=malloc(chars_left);
2136
//Keep on looping till all data has been read
2137
while (chars_left>0)
2139
//actually read the data from the socket
2141
if (sock->encrypted==1)
2142
chars_read=SSL_read(sock->ssl,buf,chars_left);
2145
chars_read=read(sock->fd,buf,chars_left);
2149
//there was an error
2150
if (errno!=EAGAIN) //EAGAIN isnt bad, it just means try later
2152
//Anything else is bad, the socket is dead
2153
sock->flags|=SOCKET_DEAD;
2164
//No data was read, it shouldnt happen, if it does, then return from
2173
//If we are in debug mode do that now
2175
socket_data_debug(sock,(char *)buf,chars_read,0);
2178
//Add the read data into the indata buffer
2179
if (sock->protocol!=SOCKET_INTERRUPT)
2180
dynstringRawappend(sock->indata,(char *)buf,chars_read);
2181
chars_left-=chars_read;
2182
sock->bytes_in+=chars_read;
2183
total_read+=chars_read;
2192
//This function actually writes data to the socket. This is NEVER called by
2193
//the user, as the socket could be in any state, and calling from the user
2194
//would just break everything. This is called for stream sockets but not
2195
//for datagram sockets like UDP
2196
static int socket_process_write_stream(socketbuf *sock)
2200
//Perform the write. Try and write as much as we can, as fast as we can
2201
written=write(sock->fd,sock->outdata->buf,sock->outdata->len);
2205
//The write had an error
2206
if (errno!=EAGAIN) /*EAGAIN simply means that the write buffer is full,
2207
try again later, no problem*/
2209
//Any other error is fatal
2210
sock->flags |= SOCKET_DEAD;
2213
else if (written > 0)
2216
//In debug mode, run the debug function
2218
socket_data_debug(sock,(char *)sock->outdata->buf,written,1);
2221
//Drop the written data from the buffer
2222
socket_outdata_drop(sock,written);
2225
//Return the number of bytes written, in case they are needed
2229
//This function actually writes data to the socket. This is NEVER called by
2230
//the user, as the socket could be in any state, and calling from the user
2231
//would just break everything. This is called for datagram sockets but not
2232
//for stream sockets like TCP or UNIX
2233
static int socket_process_write_dgram(socketbuf *sock)
2236
socket_intchar towrite;
2238
//The buffer contains one int of length data and then lots of data to
2239
//indicate a packet that should be sent all at once
2240
if (sock->outdata->len<4)
2243
//This is the length
2244
memcpy(towrite.c,sock->outdata->buf,4);
2246
//check we have enough data in the buffer to send it all
2247
if (sock->outdata->len<4+towrite.i)
2250
//We have enough, send the data. DO NOT send the initial length header,
2251
//it will get included in the receive data anyway, so we dont have to send
2253
written=sendto(sock->fd,
2254
sock->outdata->buf+4,towrite.i,
2256
(struct sockaddr *)&sock->udp_sa,
2257
sizeof(struct sockaddr_in));
2260
if (written==-1) //There was an error
2262
if (errno==EMSGSIZE)
2264
//Data too big, nothing we can do, drop the packet
2265
socket_outdata_drop(sock,towrite.i+4);
2269
else if (errno!=EAGAIN) //If the error was EAGAIN just try later
2271
//The error was something fatal
2272
sock->flags |= SOCKET_DEAD;
2276
else if (written > 0)
2278
//There was data sent
2281
//If we are in debug mode, handle that
2283
socket_data_debug(sock,(char *)sock->outdata->buf+4,written,1);
2286
//Drop the data from the buffer
2287
socket_outdata_drop(sock,towrite.i+4);
2289
//Recurse so we send as much as we can now till its empty or we error
2290
written += socket_process_write_dgram(sock);
2296
//This is the generic function to handle writes for ALL sockets
2297
static int socket_process_write(socketbuf *sock)
2299
//Only if we are connected and we have something to send
2300
if (socket_connected(sock) && sock->outdata && sock->outdata->len>0)
2303
if (sock->encrypted)
2304
return SSL_write(sock->ssl,sock->outdata->buf,sock->outdata->len);
2308
if (sock->protocol==SOCKET_UDP)
2309
return socket_process_write_dgram(sock);
2311
return socket_process_write_stream(sock);
2318
//2 way UDP sockets will ping each other to keep the socket alive. They ping
2319
//every 10 seconds. If the sockets go 60 seconds with no ping, then the
2320
//socket is considered dead.
2321
static int process_pings(socketbuf *sock)
2328
//Only ping 2 way UDP sockets
2332
//Cant ping from a listener, a listener is inbound
2333
if (sock->flags & SOCKET_LISTENER)
2337
this_second=time(NULL);
2339
//Check we need to send a ping
2340
if (sock->udp2w_nextping < this_second)
2342
sock->udp2w_nextping = this_second+10;
2344
//Create the ping packet
2345
val.i=htonl(SOCKET_UDP2W_PROTOCOL_PING);
2346
memcpy(buf,val.c,4);
2348
val.i=htonl(sock->udp2w_port);
2349
memcpy(buf+4,val.c,4);
2351
//Actually send the ping
2352
written=sendto(sock->fd,
2355
(struct sockaddr *)&sock->udp_sa,
2356
sizeof(struct sockaddr_in));
2362
//Note the socket as dead if we cant send it
2363
sock->flags |= SOCKET_DEAD;
2369
//Now we look at if its expired, over 60 seconds since any communication
2370
if (sock->flags & SOCKET_CONNECTING)
2372
//Or a much smaller 8 seconds if we are trying to connect
2373
if (this_second>sock->udp2w_lastmsg+8)
2375
sock->flags |= SOCKET_DEAD;
2380
if (this_second>sock->udp2w_lastmsg+60)
2382
sock->flags |= SOCKET_DEAD;
2389
//This function handles reliable UDP resending packets. UDP does not
2390
//guarentee transmission, so when we send a reliable packet, we get a repsonse
2391
//from the other end. When that response comes through we can assume the
2392
//packet is ok. Until then, we keep resending it on a time that is based on
2393
//the average round trip packet time. This allows for congested networks
2394
static int process_resends(socketbuf *sock)
2396
struct timeval time_now,target_time;
2398
socket_udp_rdata *scan;
2400
socket_intchar udplen,udpdata;
2402
//Only do this for 2 way UDP sockets
2406
//If there are no outbound packets to confirm, nothing to do
2407
if (!sock->udp2w_routpacket)
2411
//Now we need to find the exact time, as well as find which ones need
2413
gettimeofday(&time_now,NULL);
2415
//Find how old a packet needs to be
2416
us=sock->udp2w_averound/5; //Twice as long as average for a resend,/10*2 = /5
2418
target_time.tv_sec=time_now.tv_sec-(us/1000000);
2419
target_time.tv_usec=time_now.tv_usec-(us%1000000);
2421
if (target_time.tv_usec<0)
2423
target_time.tv_usec+=1000000;
2424
target_time.tv_sec--;
2427
scan=sock->udp2w_rdata_out;
2431
//Loop through checking each packet
2433
if (target_time.tv_sec > scan->sendtime.tv_sec ||
2434
(target_time.tv_sec == scan->sendtime.tv_sec &&
2435
target_time.tv_usec > scan->sendtime.tv_usec))
2437
//This packet needs resending
2439
//Find the length the packet needs to be
2440
newlen=scan->length;
2442
if (sock->udp2w_infd)
2445
//Set this length into the buffer
2447
dynstringRawappend(sock->outdata,udplen.c,4);
2450
udpdata.i=htonl(SOCKET_UDP2W_PROTOCOL_RDATA);
2452
dynstringRawappend(sock->outdata,udpdata.c,4);
2455
if (sock->udp2w_infd)
2457
udpdata.i=htonl(sock->udp2w_port);
2458
dynstringRawappend(sock->outdata,udpdata.c,4);
2461
//Send the packet number
2462
udpdata.i=htonl(scan->packetnum);
2463
dynstringRawappend(sock->outdata,udpdata.c,4);
2466
dynstringRawappend(sock->outdata,scan->data,scan->length);
2468
//note the new send time
2469
scan->sendtime.tv_sec=time_now.tv_sec;
2470
scan->sendtime.tv_usec=time_now.tv_usec;
2475
if (scan==sock->udp2w_rdata_out)
2482
//This is the main function called to process user sockets. It handles
2483
//calls to both input and output as well as processing incoming sockets
2484
//and noting dead sockets as being dead. This is a program-called
2485
//function and should be called often.
2486
//Actual data is NOT returned from this function, this function simply
2487
//calls appropriate subfunctions which update the internal buffers of
2488
//sockets. It is the calling programs job to process this data.
2489
int socket_process_sockets(socket_processlist *list,long int timeout)
2491
socket_processlist *scan;
2493
fd_set readers,writers;
2494
struct timeval select_timeout;
2495
int count,selectnum;
2499
//Loop through each socket in the list we have been handed
2506
//If the socket is a 2 way UDP socket, process resends and pings
2507
process_resends(sock);
2508
process_pings(sock);
2511
//Now process outbound writes (that will include any resends that have
2514
if (sock->encrypted>1)
2515
socket_process_ssl(sock);
2518
socket_process_write(sock);
2531
//Loop through all sockets again
2536
//If the socket is alive
2539
sock->encrypted<2 &&
2541
!(sock->flags & SOCKET_DEAD))
2543
if (sock->flags & SOCKET_CONNECTING)
2545
//This is a socket in the connecting state. See if it has now
2549
//A connecting 2 way socket is one we need to send a
2550
//connection message to again
2551
socket_udp2way_connectmessage(sock);
2553
if (sock->udp2w_infd)
2555
//Now set its reader socket to look for a response
2556
FD_SET(sock->udp2w_infd,&readers);
2562
//This socket should be set as a writer, as this will change
2563
//when a stream socket connection state changes
2564
FD_SET(sock->fd,&writers);
2568
else if (sock->flags & SOCKET_CONNECTED)
2570
//This socket is alredy connected
2571
if (sock->udp2w_infd)
2573
//If tehre is a UDP reading socket, we must use that to read
2574
FD_SET(sock->udp2w_infd,&readers);
2579
//Set the main socket as a reader
2580
FD_SET(sock->fd,&readers);
2592
//No valid sockets were ready to read, no point in reading them
2595
//Set the timeout to be as requested by the caller
2596
select_timeout.tv_sec=timeout/1000000;
2597
select_timeout.tv_usec=timeout%1000000;
2599
//Now actually run the select
2600
selectnum=select(FD_SETSIZE,&readers,&writers,0,&select_timeout);
2603
//Select was an error, or had no returns, we have nothing new to do now
2609
//Loop through all sockets see what we can see
2617
sock->encrypted<2 &&
2619
!(sock->flags & SOCKET_DEAD))
2621
if (sock->flags & SOCKET_CONNECTING)
2623
//A connecting socket
2624
if (sock->udp2w_infd)
2626
//Its a 2 way UDP - if it had any data
2627
if (FD_ISSET(sock->udp2w_infd,&readers))
2628
//Then send this to be processed. This will handle the
2629
//connection data if that is what is received
2630
socket_udp2way_read(sock,1);
2634
//Nothing here for a UDP socket
2635
if (sock->protocol!=SOCKET_UDP)
2637
//If it has a writer, we simply assume it is done and
2638
//the first write will fail. Not very efficient but
2640
if (FD_ISSET(sock->fd,&writers))
2642
sock->flags &=~ SOCKET_CONNECTING;
2643
sock->flags |= SOCKET_CONNECTED;
2644
sock->flags |= SOCKET_DELAYED_NOW_CONNECTED;
2645
sock->connect_time=time(NULL);
2650
else if (sock->flags & SOCKET_CONNECTED)
2652
//This is a connected socket, handle it
2654
if (sock->udp2w_infd)
2656
//2 way UDP socket reader
2657
if (FD_ISSET(sock->udp2w_infd,&readers))
2658
//Handle its special data
2659
socket_udp2way_read(sock,1);
2663
if (FD_ISSET(sock->fd,&readers))
2665
//Any other socket, read it using the generic read function
2677
//We're done, return how many sockets were affected
2682
//This is a wrapper function for processing one single socket. It makes it
2683
//into a socketlist of one entry, and sends it to the previous
2684
//function for handling.
2685
int socket_process(socketbuf *sock,long int timeout)
2687
socket_processlist listofone;
2689
listofone.next=&listofone;
2690
listofone.prev=&listofone;
2691
listofone.sock=sock;
2693
return socket_process_sockets(&listofone,timeout);
2696
//Wrapper function to create a unix socket. It is assumed that wait is the
2697
//required functionality
2698
socketbuf *socket_create_unix(const char *path)
2700
return socket_create_unix_wait(path,1);
2703
//Wrapper function to create a TCPIP socket. It is assumed that wait is the
2704
//required functionality
2705
socketbuf *socket_create_inet_tcp(const char *host,int port)
2707
return socket_create_inet_tcp_wait(host,port,1);
2710
//Create a tcpip socket on a specific IP address
2711
socketbuf *socket_create_inet_tcp_listener_on_ip(const char *localip,int port)
2713
struct sockaddr_in sa;
2715
char hostname[HOST_NAME_MAX+1];
2719
struct in_addr inet_address;
2720
struct linger lingerval;
2727
//set the hostname. If this is passed in, use that, otherwise use gethostname
2728
memset(&sa,0,sizeof(struct sockaddr_in));
2730
strcpy(hostname,localip);
2732
gethostname(hostname,HOST_NAME_MAX);
2734
//Simply gethostbyname which handles all kinds of addresses
2735
hp=gethostbyname(hostname);
2738
//We couldnt resolve the host fail
2743
//Se specifically requested an IP address, so we use it, thus restricting
2744
//to just one interface. If we didnt specify the address then we skip
2745
//this section which in effect means that the socket will bind to all
2746
//IP addresses on the system
2747
memcpy((char *)&inet_address,hp->h_addr,sizeof(struct in_addr));
2748
if (inet_address.s_addr!=-1)
2749
sa.sin_addr.s_addr=inet_address.s_addr;
2751
sa.sin_family=hp->h_addrtype;
2752
sa.sin_port = htons(port);
2755
fd = socket(AF_INET,SOCK_STREAM,0);
2759
//We couldnt create the socket!
2764
//Set REUSEADDR so that if the system goes down it can go right
2765
//back up again. Otherwise it will block until all data is processed
2766
setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char *)&dummy,sizeof(dummy));
2768
//Linger so that data is sent when the socket closes
2769
lingerval.l_onoff=0;
2770
lingerval.l_linger=0;
2771
setsockopt(fd,SOL_SOCKET,SO_LINGER,(char *)&lingerval,
2772
sizeof(struct linger));
2777
if (ioctl(fd,FIONBIO,&dummy)<0)
2784
flags=fcntl(fd,F_GETFL,0);
2791
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK) < 0)
2797
# error no valid non-blocking method
2801
//Now bind the socket to the port
2802
if (bind(fd,(struct sockaddr *)&sa,sizeof(sa))<0)
2804
//We failed, maybe something else is already bound, maybe something
2805
//else, regardless, we're stuffed
2811
//Listen with the maximum number - this means we can have as many incoming
2812
//connections as the kernel is configured to handle (on the machine that
2813
//builds of course, it wont magically change itself from machine to machine)
2814
if (listen(fd,SOMAXCONN)<0)
2821
//Finally create the socket datastruct to hold the socket
2822
sock=socket_create(fd);
2823
sock->protocol=SOCKET_TCP;
2826
sock->flags |= (SOCKET_CONNECTED|SOCKET_LISTENER);
2827
sock->connect_time=time(NULL);
2832
//Create a listener on ALL sockets
2833
socketbuf *socket_create_inet_tcp_listener(int port)
2835
return socket_create_inet_tcp_listener_on_ip(NULL,port);
2838
//Create a UDP listener
2839
socketbuf *socket_create_inet_udp_listener_on_ip(const char *localip,int port)
2841
struct sockaddr_in sa;
2843
char hostname[HOST_NAME_MAX+1];
2847
struct in_addr inet_address;
2848
struct linger lingerval;
2855
memset(&sa,0,sizeof(struct sockaddr_in));
2857
//set the hostname. If this is passed in, use that, otherwise use gethostname
2859
strcpy(hostname,localip);
2861
gethostname(hostname,HOST_NAME_MAX);
2863
//Simply gethostbyname which handles all kinds of addresses
2864
hp=gethostbyname(hostname);
2867
//We couldnt resolve the host fail
2872
//We specifically requested an IP address, so we use it, thus restricting
2873
//to just one interface. If we didnt specify the address then we skip
2874
//this section which in effect means that the socket will bind to all
2875
//IP addresses on the system
2876
memcpy((char *)&inet_address,hp->h_addr,sizeof(struct in_addr));
2877
if (inet_address.s_addr!=-1)
2878
sa.sin_addr=inet_address;
2880
sa.sin_family=hp->h_addrtype;
2881
sa.sin_port = htons(port);
2884
fd = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
2888
//We couldnt create the socket!
2892
lingerval.l_onoff=0;
2893
lingerval.l_linger=0;
2894
setsockopt(fd,SOL_SOCKET,SO_LINGER,(char *)&lingerval,
2895
sizeof(struct linger));
2901
if (ioctl(fd,FIONBIO,&dummy)<0)
2908
flags=fcntl(fd,F_GETFL,0);
2915
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK) < 0)
2921
# error no valid non-blocking method
2926
if (bind(fd,(struct sockaddr *)&sa,sizeof(sa))<0)
2928
//We failed, maybe something else is already bound, maybe something
2929
//else, regardless, we're stuffed
2935
//Finally create the socket datastruct to hold the socket
2936
sock=socket_create(fd);
2937
sock->protocol=SOCKET_UDP;
2940
sock->flags |= (SOCKET_CONNECTED|SOCKET_LISTENER);
2941
sock->connect_time=time(NULL);
2946
//A wrapper function to bind a UDP listener on all interfaces
2947
socketbuf *socket_create_inet_udp_listener(int port)
2949
return socket_create_inet_udp_listener_on_ip(NULL,port);
2952
//Create a unix socket listener.
2953
socketbuf *socket_create_unix_listener(const char *path)
2957
struct sockaddr_un sa;
2958
struct linger lingerval;
2961
fd = socket(PF_UNIX,SOCK_STREAM,0);
2964
//Socket creation failed
2967
//Set the socket types
2968
sa.sun_family = AF_UNIX;
2969
strcpy(sa.sun_path,path);
2971
//Set this to linger so any data being processed will be finished
2972
lingerval.l_onoff=0;
2973
lingerval.l_linger=0;
2974
setsockopt(fd,SOL_SOCKET,SO_LINGER,(char *)&lingerval,
2975
sizeof(struct linger));
2981
if (ioctl(fd,FIONBIO,&dummy)<0)
2988
flags=fcntl(fd,F_GETFL,0);
2995
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK) < 0)
3001
# error no valid non-blocking method
3006
//Now bind to the location
3007
if (bind(fd,(struct sockaddr *)&sa,sizeof(sa)) < 0)
3009
//We failed. Maybe the file is already there...
3014
//Listen with the maximum number - this means we can have as many incoming
3015
//connections as the kernel is configured to handle (on the machine that
3016
//builds of course, it wont magically change itself from machine to machine)
3017
if (listen(fd,SOMAXCONN) < 0)
3025
//Finally create the socket datastruct to hold the socket
3026
sock=socket_create(fd);
3027
sock->protocol=SOCKET_UNIX;
3028
sock->path=(char *)malloc(strlen(path)+1);
3029
strcpy(sock->path,path);
3031
sock->flags |= (SOCKET_CONNECTED|SOCKET_LISTENER);
3032
sock->connect_time=time(NULL);
3037
//This is the function used by the calling program to see if any new
3038
//connections have come in on a listener socket
3039
socketbuf *socket_new(socketbuf *parent)
3041
socketbuf *returnval;
3043
//Destroy any sockets that have died in the connection process. This doesnt
3044
//get them all, just the first ones, until the one at the front is a live.
3045
//This assumes that this function is called often, and so dead connections
3046
//are cleaned up regularly.
3047
while (parent->new_children && socket_dead(parent->new_children))
3049
returnval=parent->new_children;
3051
//Unlink the dead socket
3052
parent->new_children=parent->new_children->new_child_next;
3054
if (parent->new_children==returnval)
3056
parent->new_children=NULL;
3057
returnval->new_child_next=NULL;
3058
returnval->new_child_prev=NULL;
3062
returnval->new_child_next->new_child_prev=returnval->new_child_prev;
3063
returnval->new_child_prev->new_child_next=returnval->new_child_next;
3066
socket_destroy(returnval);
3069
//Now look for new sockets
3070
if (parent->new_children)
3072
returnval=parent->new_children;
3074
//Unlink the first socket from the list of new connections
3075
parent->new_children=parent->new_children->new_child_next;
3077
if (parent->new_children==returnval)
3079
parent->new_children=NULL;
3080
returnval->new_child_next=NULL;
3081
returnval->new_child_prev=NULL;
3085
returnval->new_child_next->new_child_prev=returnval->new_child_prev;
3086
returnval->new_child_prev->new_child_next=returnval->new_child_next;
3089
//Now link it in to the list of connected children
3090
if (parent->connected_children)
3092
returnval->connected_child_next=parent->connected_children;
3093
returnval->connected_child_prev=
3094
parent->connected_children->connected_child_prev;
3095
returnval->connected_child_prev->connected_child_next=returnval;
3096
returnval->connected_child_next->connected_child_prev=returnval;
3100
parent->connected_children=returnval;
3101
returnval->connected_child_next=returnval;
3102
returnval->connected_child_prev=returnval;
3105
//Return the new socket
3113
//If the socket has just connected (fairly useless, legacy now)
3114
int socket_just_connected(socketbuf *sock)
3116
if (sock->flags & SOCKET_DELAYED_NOW_CONNECTED)
3118
sock->flags &=~ SOCKET_DELAYED_NOW_CONNECTED;
3125
//Return the portnumber
3126
int socket_get_port(socketbuf *sock)
3132
//Set debug mode on or off
3133
void socket_debug_off(socketbuf *sock)
3137
void socket_debug_on(socketbuf *sock)
3143
//Return the time the socket connected
3144
time_t socket_connecttime(socketbuf *sock)
3146
return sock->connect_time;
3149
//Set a flag into the sockets mode. The only flag right now is sequential
3150
//and only applies to 2 way UDP sockets
3151
int socket_mode_set(socketbuf *sock,unsigned int mode)
3157
//Remove a flag from a socket
3158
int socket_mode_unset(socketbuf *sock,unsigned int mode)
3164
//Get the sockets mode
3165
unsigned int socket_mode_get(socketbuf *sock)
3170
const char *socket_host_get(socketbuf *sock)
3177
void socket_set_encrypted(socketbuf *sock)
3179
static int ssl_initialised=0;
3181
if (!ssl_initialised)
3185
SSL_load_error_strings();
3189
if (sock->flags & SOCKET_LISTENER)
3190
socket_set_listener_encrypted(sock);
3191
else if (sock->flags & SOCKET_INCOMING)
3192
socket_set_server_encrypted(sock);
3194
socket_set_client_encrypted(sock);
3198
void socket_set_server_key(socketbuf *sock,const char *keyfile)
3200
sock->server_key_file=(char *)malloc(strlen(keyfile)+1);
3201
strcpy(sock->server_key_file,keyfile);
3204
void socket_set_server_cert(socketbuf *sock,const char *certfile)
3206
sock->server_cert_file=(char *)malloc(strlen(certfile)+1);
3207
strcpy(sock->server_cert_file,certfile);
3210
void socket_set_client_ca(socketbuf *sock,const char *cafile)
3212
sock->client_ca_file=(char *)malloc(strlen(cafile)+1);
3213
strcpy(sock->client_ca_file,cafile);
3218
//This moves the buffers from one socket to another, MOVING it, not
3219
//copying it. This is not a simple task as it needs to take into
3220
//account all buffers in the UDP resend queue to!
3221
void socket_relocate_data(socketbuf *from,socketbuf *to)
3223
socket_udp_rdata *scan,*target;
3225
//Transfer data in the resend queue to the new out queue. Do this first so it
3226
//goes back out in order
3227
while (from->udp2w_rdata_out)
3229
scan=from->udp2w_rdata_out;
3233
if (scan->packetnum < target->packetnum)
3236
if (scan==from->udp2w_rdata_out)
3240
//Add this data to the out queue
3241
socket_write_reliable(to,
3242
target->data,target->length);
3244
//Now unlink that target
3245
from->udp2w_rdata_out=socket_rdata_delete(from->udp2w_rdata_out,target);
3249
//Transfer the old outqueue to the new outqueue
3250
dynstringRawappend(to->outdata,(char *)(from->outdata->buf),from->outdata->len);
3251
from->outdata->len=0;
3253
//Transfer any unread inqueue to the new inqueue
3254
dynstringRawappend(to->indata,(char *)(from->indata->buf),from->indata->len);
3255
from->indata->len=0;
3262
/****************************************************************************
3263
** Extention for 2-way and reliable UDP **
3264
** This is NOT generally compatable, you need to run this socket code **
3266
****************************************************************************/
3268
//Send the connection message to a remote listener. This initialises the
3270
int socket_udp2way_connectmessage(socketbuf *sock)
3274
socket_intchar intval;
3275
char buf[HOST_NAME_MAX+60+1+12];
3277
//Now we construct new data to send
3278
//Data is as follows:
3281
//4 bytes: Local portnumber
3282
//4 bytes: The length of the unique identifier string
3283
// : The unique identifier string
3286
intval.i=htonl(SOCKET_UDP2W_PROTOCOL_CONNECTION);
3287
memcpy(buf,intval.c,4);
3289
intval.i=htonl(sock->udp2w_port);
3290
memcpy(buf+4,intval.c,4);
3292
datalen=strlen(sock->udp2w_unique);
3293
intval.i=htonl(datalen);
3294
memcpy(buf+8,intval.c,4);
3296
memcpy(buf+12,sock->udp2w_unique,datalen);
3298
//Send the data to the socket
3299
written=sendto(sock->fd,
3302
(struct sockaddr *)&sock->udp_sa,
3303
sizeof(struct sockaddr_in));
3309
//If the error is not EAGAIN, its dead
3310
sock->flags |= SOCKET_DEAD;
3315
//Return the number of bytes sent
3320
//This is sent as a reply, the connectmessage has been received, now we need to
3322
static int socket_udp2way_connectmessage_reply(socketbuf *sock)
3328
//Now we construct new data to send
3329
//4 bytes : protocol
3331
val.i=htonl(SOCKET_UDP2W_PROTOCOL_CONNECTION);
3332
memcpy(buf,val.c,4);
3335
written=sendto(sock->fd,
3338
(struct sockaddr *)&sock->udp_sa,
3339
sizeof(struct sockaddr_in));
3345
//This is a fatal error, kill the socket
3346
sock->flags |= SOCKET_DEAD;
3355
//This function creates a 2 way UDP socket connection to a remote host
3356
socketbuf *socket_create_inet_udp2way_wait(const char *host,int port,int wait)
3358
socketbuf *sock,*insock;
3360
struct timeval time_now;
3361
char hostname[HOST_NAME_MAX+1];
3363
//Simply - we create a socket outbound
3364
sock=socket_create_inet_udp_wait(host,port,wait);
3369
//Now create a listener, NOT on the same port but on a port that is
3370
//as close as we can make it. We dont do it on the same port as it is
3371
//possible that in a failover condition, the main socket may be bound
3372
//later, causing inability to failover servers
3378
//Create a listener on the new socket
3379
insock=socket_create_inet_udp_listener(inport);
3383
//We now have 2 socketbufs, but we really only want one - lets take the
3384
//actual inbound socket and put it in the first sockets data, then kill
3385
//the second set of data
3387
sock->udp2w_infd=insock->fd;
3388
sock->udp2w_port=inport;
3391
sock->udp2w_averound=2500000; /*Set it for a sloooooow network, it will
3392
modify itself if the network shows it is
3394
sock->udp2w_lastmsg=time(NULL);
3398
//Get rid of the unused listener data struct
3399
socket_destroy(insock);
3401
sock->flags|=SOCKET_CONNECTING;
3402
sock->flags&=~SOCKET_CONNECTED;
3403
//Send the init data
3405
//We CANNOT wait for the response, or it will never get there if the
3406
//client and server run on the same thread
3408
//Now we set a unique value, as we use UDP, so the other side knows WHO
3410
gethostname(hostname,HOST_NAME_MAX);
3412
gettimeofday(&time_now,NULL);
3414
//Create a unique name for this client. This will be unique anywhere unless
3415
//you have 2 connections on the same machine in the same microsecond. Pretty
3416
//fullproof I reckon
3417
sprintf(sock->udp2w_unique,"%s-%ld.%ld",hostname,
3418
time_now.tv_sec,time_now.tv_usec);
3420
//Send the connect protocol message to the remote server
3421
socket_udp2way_connectmessage(sock);
3426
//Create the 2 way listener on a specific IP address
3427
socketbuf *socket_create_inet_udp2way_listener_on_ip(const char *localip,
3432
//Create the basic UDP listener
3433
sock=socket_create_inet_udp_listener_on_ip(localip,port);
3435
//All we do extra is the 2 way UDP specific values
3439
sock->udp2w_averound=2500000;
3440
sock->udp2w_lastmsg=time(NULL);
3446
//Wrapper function, to set a 2 way UDP listener bound to all interfaces
3447
socketbuf *socket_create_inet_udp2way_listener(int port)
3449
return socket_create_inet_udp2way_listener_on_ip(NULL,port);
3452
//This function takes a bit of explaining.
3453
//UDP always sends data to the 'listener' socket, not to a socket specific to
3454
//the user. This means that all data comes in to the one socket and then needs
3455
//to be associated with a socket for THAT user
3456
//So, each packet contains the IP address and the portnumber of the sender
3457
//which allows unique identification. This function looks at all sockets
3458
//that are children of the listener, and finds the one that matches the host
3459
//and the portnumber of the sender.
3460
static socketbuf *socket_get_child_socketbuf(socketbuf *sock,
3461
char *host,int port)
3465
scan=sock->new_children;
3468
if (!strcmp(scan->host,host) && scan->port==port && !socket_dead(scan))
3470
scan=scan->new_child_next;
3471
if (scan==sock->new_children)
3475
scan=sock->connected_children;
3478
if (!strcmp(scan->host,host) && scan->port==port && !socket_dead(scan))
3480
scan=scan->connected_child_next;
3481
if (scan==sock->connected_children)
3488
//This works in the same way as above, but instead of using the
3489
//hostname it uses the sockaddr_in function as its host comparison. It
3490
//works in the same way but is slightly quicker as it uses an integer
3491
//== operation instead of a strcmp
3492
static socketbuf *socket_get_child_socketbuf_sa(socketbuf *sock,
3493
struct sockaddr_in *sa,
3498
scan=sock->new_children;
3501
if (scan->udp_sa.sin_addr.s_addr==sa->sin_addr.s_addr &&
3502
scan->port==port && !socket_dead(scan))
3505
scan=scan->new_child_next;
3506
if (scan==sock->new_children)
3510
scan=sock->connected_children;
3513
if (scan->udp_sa.sin_addr.s_addr==sa->sin_addr.s_addr &&
3514
scan->port==port && !socket_dead(scan))
3516
scan=scan->connected_child_next;
3517
if (scan==sock->connected_children)
3524
//This function is called when a 2 way UDP connection is received. This
3525
//means that we need to find out if we are already connected, and then
3526
//connect back to them if we arent. We must also allow for the fact that
3527
//someone may reconnect when we THINK they are already connected
3528
static socketbuf *socket_udp2way_listener_create_connection(socketbuf *sock,
3529
struct sockaddr_in *sa,
3535
socketbuf *returnval,*oldreturnval;
3543
//Create an outgoing socket back to the originator
3545
//Find their IP address
3546
inet_ntop(AF_INET,(void *)(&sa->sin_addr),host,19);
3548
//Find if anyone else is connected to this listener from that port
3549
returnval=socket_get_child_socketbuf(sock,host,port);
3552
//Note if we have no match already connected, this whole loop will not
3555
while (returnval && returnval!=oldreturnval)
3557
//We loop here onthe highly unlikely chance we already have 2
3558
//connections from the same port. This is impossible but just in case,
3559
//its a negligable overhead to be sure
3561
oldreturnval=returnval;
3562
/*First, check if we are already connected to THIS one*/
3564
if (returnval->udp2w_unique && strcmp(returnval->udp2w_unique,unique))
3566
//This is a different one, mark THAT one as dead, cos we cant
3567
//have 2 sockets coming from the same place, its impossible. The old
3569
returnval->flags |= SOCKET_DEAD;
3571
returnval=socket_get_child_socketbuf(sock,host,port);
3574
//We have no match, so we create a new outbound. NOTE: this means if the same
3575
//connection was made more than once, the socket is not duplicated
3579
fd=socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
3581
//No socket, no way to procede
3584
//Create the socketbuf around the fd
3585
returnval=socket_create(fd);
3587
//Set the udp_sa so we have an identifier for the other end
3588
memset(&returnval->udp_sa,0,sizeof(struct sockaddr_in));
3590
//Set the destination
3591
returnval->udp_sa.sin_family=AF_INET;
3592
returnval->udp_sa.sin_port=htons(port);
3593
returnval->udp_sa.sin_addr.s_addr=sa->sin_addr.s_addr;
3595
//Set the 2 way UDP stuff
3596
returnval->protocol=SOCKET_UDP;
3598
returnval->udp2w_averound=2500000;
3599
returnval->udp2w_lastmsg=time(NULL);
3600
strcpy(returnval->udp2w_unique,unique);
3602
returnval->mode=sock->mode;
3604
//Record the hostname too
3605
returnval->host=(char *)malloc(strlen(host)+1);
3606
strcpy(returnval->host,host);
3608
returnval->port=port;
3610
//Set non-blocking, so we can check for a data without freezing
3615
if (ioctl(fd,FIONBIO,&dummy)<0)
3622
flags=fcntl(fd,F_GETFL,0);
3630
if (fcntl(fd,F_SETFL,flags|O_NONBLOCK)<0)
3637
# error No valid non-blocking method - cannot build;
3638
# endif // O_NONBLOCK
3642
//Set the flags to connected
3643
returnval->flags |= (SOCKET_CONNECTED|SOCKET_INCOMING);
3645
returnval->parent=sock;
3647
//Link this in to the new children list as it needs to be acknowledged
3648
//by the calling program
3649
if (sock->new_children)
3651
returnval->new_child_next=sock->new_children;
3652
returnval->new_child_prev=returnval->new_child_next->new_child_prev;
3653
returnval->new_child_next->new_child_prev=returnval;
3654
returnval->new_child_prev->new_child_next=returnval;
3658
returnval->new_child_next=returnval;
3659
returnval->new_child_prev=returnval;
3660
sock->new_children=returnval;
3663
returnval->connect_time=time(NULL);
3666
//Send the reply to acknowledge the connection
3667
socket_udp2way_connectmessage_reply(returnval);
3672
//This function acknowledges the sending of a reliable data packet. This will
3673
//tell the sender that the packet has been accepted and can now be dropped.
3674
//If the sender does not receive this by the time the packet resend comes
3675
//around, the packet will be resent.
3676
static int socket_acknowledge_listener_udp_rpacket(socketbuf *sock,
3680
socket_intchar intval;
3683
//Now we construct new data to send
3686
//4 bytes: Packet number
3688
intval.i=htonl(SOCKET_UDP2W_PROTOCOL_RCONFIRM);
3689
memcpy(buf,intval.c,4);
3691
intval.i=htonl(packetnumber);
3692
memcpy(buf+4,intval.c,4);
3694
//Send to the socket
3695
written=sendto(sock->fd,
3698
(struct sockaddr *)&sock->udp_sa,
3699
sizeof(struct sockaddr_in));
3705
//If the send fails, the socket dies
3706
sock->flags |= SOCKET_DEAD;
3714
//This function handles all incoming data sent to a listener socket
3716
int socket_udp2way_listener_data_process(socketbuf *sock,
3717
struct sockaddr_in *sa,
3719
signed char *buf,int datalen)
3721
socket_intchar len,val;
3722
socket_udp_rdata *oldpacket,*packet;
3724
int type,port,packetnumber,uniquelen;
3725
char unique[HOST_NAME_MAX+60+1];
3726
struct timeval time_now;
3728
//There must always be at least 4 bytes, that is a protocol header
3732
memcpy(val.c,buf,4);
3735
//We have the protocol
3737
if (type==SOCKET_UDP2W_PROTOCOL_CONNECTION)
3739
//New connection messages need 12 bytes minimum
3740
//4 Bytes : Protocol
3741
//4 Bytes : Port number
3742
//4 Bytes : Length of the unique identifier
3743
// : Unique identifier
3747
memcpy(val.c,buf+4,4);
3749
//Now get the unique connection ID that we have
3750
memcpy(len.c,buf+8,4);
3751
uniquelen=ntohl(len.i);
3752
memcpy(unique,buf+12,uniquelen);
3753
unique[uniquelen]=0;
3755
//Now call the creat connection function to handle this message
3756
socket_udp2way_listener_create_connection(sock,sa,sa_len,ntohl(val.i),
3762
if (type==SOCKET_UDP2W_PROTOCOL_DATA
3765
//This is user data, it is NOT reliable so we just take it and use
3768
// 4 bytes : protocol
3769
// 4 bytes : originating port
3772
//This doesnt go on the listeners inbound, it goes on the clients
3774
//Get the port as the next byte
3775
memcpy(val.c,buf+4,4);
3778
//Locate the client from the ones connected to this listener
3779
client=socket_get_child_socketbuf_sa(sock,sa,port);
3782
//Note that this client has received a message - helps timeouts
3783
client->udp2w_lastmsg=time(NULL);
3785
//Store the data in this clients incoming data stream
3787
dynstringRawappend(client->indata,len.c,4);
3788
dynstringRawappend(client->indata,(char *)buf+8,datalen-8);
3793
if (type==SOCKET_UDP2W_PROTOCOL_RDATA
3796
//This is a RELIABLE data packet and requires handling specially
3798
// 4 bytes : protocol
3799
// 4 bytes : originating port
3800
// 4 bytes : packet number
3804
//This doesnt go on the listeners inbound, it goes on the clients
3808
//Get the port as the next byte
3809
memcpy(val.c,buf+4,4);
3812
//Locate the client associated with this message
3813
client=socket_get_child_socketbuf_sa(sock,sa,port);
3816
//Note that this client has received a message - helps timeouts
3817
client->udp2w_lastmsg=time(NULL);
3819
//get the packet number
3820
memcpy(val.c,buf+8,4);
3821
packetnumber=ntohl(val.i);
3823
//The packet number is important. The packets may need to be
3824
//stored in sequence. It may also be a packet we have had before,
3825
//as the acknowledgement does not always make it back.
3827
//We have in the socketbuf the next packet number we are expecting,
3828
//all packets earlier than this have been processed and forgotten
3831
if (packetnumber==client->udp2w_rinpacket)
3833
client->udp2w_rinpacket++;
3834
//Its the correct next packet - we can just send it to the buffer
3836
dynstringRawappend(client->indata,len.c,4);
3837
dynstringRawappend(client->indata,(char *)buf+12,
3840
else if (packetnumber<client->udp2w_rinpacket)
3842
//We've already got this one, ignore it
3844
else if (socket_rdata_locate_packetnum(client->udp2w_rdata_in,
3847
//This packet is one we have received and wating to be processed
3851
//This is one we dont have yet, and we also dont have its
3853
//There are 2 ways to handle this:
3854
// 1) Sequential mode:
3855
// We add it onto a queue and wait for the previous ones
3856
// 2) Non-sequential mode:
3857
// We deal with it now, but add it to the list anyway, so
3858
// we know its been dealt with.
3859
if (!(client->mode & SOCKET_MODE_UDP2W_SEQUENTIAL))
3861
//We store the packet, we note that it HAS been sent, so we
3862
//can switch between sequential and non-sequential modes
3863
//without losing track of the packets we've already processed
3864
client->udp2w_rdata_in=rdata_allocate(client->udp2w_rdata_in,
3869
//We arent sequential, so we just send it to the out buffer
3871
dynstringRawappend(client->indata,len.c,4);
3872
dynstringRawappend(client->indata,(char *)buf+12,
3876
//We are sequential, so all we do is add it to the list for
3878
client->udp2w_rdata_in=rdata_allocate(client->udp2w_rdata_in,
3884
//we may have now got a series of packets we can send, or at least
3885
//get rid of. So, we test this.
3887
//Check the next accepted packet is not on the received list
3888
oldpacket=socket_rdata_locate_packetnum(client->udp2w_rdata_in,
3889
client->udp2w_rinpacket);
3892
if (oldpacket->sent)
3894
//We are sequential, so this hasnt been sent yet
3895
len.i=oldpacket->length;
3896
dynstringRawappend(client->indata,len.c,4);
3897
dynstringRawappend(client->indata,oldpacket->data,
3901
//Now its 'in the past' delete it
3902
client->udp2w_rdata_in=
3903
socket_rdata_delete(client->udp2w_rdata_in,
3906
//Incriment the packet number
3907
client->udp2w_rinpacket++;
3910
oldpacket=socket_rdata_locate_packetnum(client->udp2w_rdata_in,
3911
client->udp2w_rinpacket);
3914
//acknowledge the packet we have just received
3915
socket_acknowledge_listener_udp_rpacket(client,packetnumber);
3921
if (type==SOCKET_UDP2W_PROTOCOL_RCONFIRM
3924
//This is the confirmation of a packet we sent in reliable mode
3926
// 4 bytes : protocol
3927
// 4 bytes : priginating port
3928
// 4 bytes : packet number
3930
//This doesnt confirm on the listeners port, but on the clients
3934
//Get the port as the next byte
3935
memcpy(val.c,buf+4,4);
3938
//Locate the client associated with this
3939
client=socket_get_child_socketbuf_sa(sock,sa,port);
3943
//Record their link is active
3944
client->udp2w_lastmsg=time(NULL);
3946
//Comes with a packet number
3947
memcpy(val.c,buf+8,4);
3948
packetnumber=ntohl(val.i);
3950
//Locate this packet in the list of packets we are remembering to
3952
packet=socket_rdata_locate_packetnum(client->udp2w_rdata_out,
3957
//rebalance the timings for knowing when to resend
3958
client->udp2w_averound=(long long)(client->udp2w_averound*0.9);
3960
gettimeofday(&time_now,NULL);
3962
client->udp2w_averound+=
3963
((time_now.tv_sec-packet->sendtime.tv_sec)*1000000);
3964
client->udp2w_averound+=
3965
(time_now.tv_usec-packet->sendtime.tv_usec);
3968
//We've not already been told of the receipt, so delete it
3969
client->udp2w_rdata_out=
3970
socket_rdata_delete(client->udp2w_rdata_out,
3979
if (type==SOCKET_UDP2W_PROTOCOL_PING)
3981
//This is a ping packet, low level 'keep the socket alive' protocol
3983
// 4 bytes : protocol
3984
// 4 bytes : originating portnumber
3989
//Get the port as the next byte
3990
memcpy(val.c,buf+4,4);
3993
//Find the correct client
3994
client=socket_get_child_socketbuf_sa(sock,sa,port);
3998
//Note we have received something
3999
client->udp2w_lastmsg=time(NULL);
4008
//This function acknowledges the sending of a reliable data packet. This will
4009
//tell the sender that the packet has been accepted and can now be dropped.
4010
//If the sender does not receive this by the time the packet resend comes
4011
//around, the packet will be resent.
4012
static int socket_acknowledge_reader_udp_rpacket(socketbuf *sock,int packetnumber)
4015
socket_intchar intval;
4018
//Now we construct new data to send
4021
//4 bytes: Our portnumber
4022
//4 bytes: Packet number
4024
intval.i=htonl(SOCKET_UDP2W_PROTOCOL_RCONFIRM);
4025
memcpy(buf,intval.c,4);
4027
intval.i=htonl(sock->udp2w_port);
4028
memcpy(buf+4,intval.c,4);
4030
intval.i=htonl(packetnumber);
4031
memcpy(buf+8,intval.c,4);
4033
//Send to the socket
4034
written=sendto(sock->fd,
4037
(struct sockaddr *)&sock->udp_sa,
4038
sizeof(struct sockaddr_in));
4044
//If the send fails, the socket dies
4045
sock->flags |= SOCKET_DEAD;
4053
//This is VERY similar to the listener reading, except as the data can ONLY
4054
//come from the other end of THIS socket (we are the client) then we dont
4055
//need the portnumber
4056
int socket_udp2way_reader_data_process(socketbuf *sock,
4057
signed char *buf,int datalen)
4059
socket_intchar len,val;
4061
socket_udp_rdata *packet,*oldpacket;
4063
struct timeval time_now;
4065
//There must always be at least 4 bytes, that is a protocol header
4069
memcpy(val.c,buf,4);
4072
//We have the protocol
4074
if (type==SOCKET_UDP2W_PROTOCOL_CONNECTION)
4076
//The server has acknowledged our connection, no more needed, we are
4079
sock->flags&=~SOCKET_CONNECTING;
4080
sock->flags|=SOCKET_CONNECTED;
4085
if (type==SOCKET_UDP2W_PROTOCOL_DATA
4088
//This is user data, it is NOT reliable so we just take it and use
4091
//Add it to the users data buffer
4093
dynstringRawappend(sock->indata,len.c,4);
4094
dynstringRawappend(sock->indata,(char *)buf+4,datalen-4);
4099
if (type==SOCKET_UDP2W_PROTOCOL_RDATA
4102
//This is a RELIABLE data packet and requires handling specially
4104
// 4 bytes : protocol
4105
// 4 bytes : packet number
4108
//Comes with a packet number
4109
memcpy(val.c,buf+4,4);
4110
packetnumber=ntohl(val.i);
4112
//The packet number is important. The packets may need to be
4113
//stored in sequence. It may also be a packet we have had before,
4114
//as the acknowledgement does not always make it back.
4116
//We have in the socketbuf the next packet number we are expecting,
4117
//all packets earlier than this have been processed and forgotten
4120
if (packetnumber==sock->udp2w_rinpacket)
4122
//Its the correct next packet - we can just send it to the buffer
4124
sock->udp2w_rinpacket++;
4127
dynstringRawappend(sock->indata,len.c,4);
4128
dynstringRawappend(sock->indata,(char *)buf+8,datalen-8);
4130
else if (packetnumber<sock->udp2w_rinpacket)
4132
//We've already got this one, do nothing
4134
else if (socket_rdata_locate_packetnum(sock->udp2w_rdata_in,
4137
//This is one we already have in the queue - do nothing
4141
//This is one we dont have yet, and we also dont have its
4143
//There are 2 ways to handle this:
4144
// 1) Sequential mode:
4145
// We add it onto a queue and wait for the previous ones
4146
// 2) Non-sequential mode:
4147
// We deal with it now, but add it to the list anyway, so
4148
// we know its been dealt with.
4150
if (!(sock->mode & SOCKET_MODE_UDP2W_SEQUENTIAL))
4152
//We store the packet, we note that it HAS been sent, so we
4153
//can switch between sequential and non-sequential modes
4154
//without losing track of the packets we've already processed
4155
sock->udp2w_rdata_in=rdata_allocate(sock->udp2w_rdata_in,
4160
//We arent sequential, so we just send it to the out buffer
4162
dynstringRawappend(sock->indata,len.c,4);
4163
dynstringRawappend(sock->indata,(char *)buf+8,datalen-8);
4166
//We are sequential, so all we do is add it to the list for
4168
sock->udp2w_rdata_in=rdata_allocate(sock->udp2w_rdata_in,
4174
//we may have now got a series of packets we can send, or at least
4175
//get rid of. So, we test this.
4177
//Check the next accepted packet is not on the received list
4178
oldpacket=socket_rdata_locate_packetnum(sock->udp2w_rdata_in,
4179
sock->udp2w_rinpacket);
4182
if (!oldpacket->sent)
4184
//We are sequential, so this hasnt been sent yet
4185
len.i=oldpacket->length;
4186
dynstringRawappend(sock->indata,len.c,4);
4187
dynstringRawappend(sock->indata,oldpacket->data,
4191
//Now its 'in the past' delete it
4192
sock->udp2w_rdata_in=socket_rdata_delete(sock->udp2w_rdata_in,
4195
//Incriment the packet number
4196
sock->udp2w_rinpacket++;
4199
oldpacket=socket_rdata_locate_packetnum(sock->udp2w_rdata_in,
4200
sock->udp2w_rinpacket);
4203
//acknowledge the packet we have just received
4204
socket_acknowledge_reader_udp_rpacket(sock,packetnumber);
4209
if (type==SOCKET_UDP2W_PROTOCOL_RCONFIRM
4213
//This is the confirmation of a packet we sent in reliable mode
4215
// 4 bytes : protocol
4216
// 4 bytes : packet number
4218
//Comes with a packet number
4219
memcpy(val.c,buf+4,4);
4220
packetnumber=ntohl(val.i);
4222
//Locate this packet in the list of packets we are remembering to
4224
packet=socket_rdata_locate_packetnum(sock->udp2w_rdata_out,
4228
//rebalance the timings, so we know better when to resend
4229
sock->udp2w_averound=(long long)(sock->udp2w_averound*0.9);
4231
gettimeofday(&time_now,NULL);
4233
sock->udp2w_averound+=
4234
((time_now.tv_sec-packet->sendtime.tv_sec)*1000000);
4235
sock->udp2w_averound+=(time_now.tv_usec-packet->sendtime.tv_usec);
4237
//We've not already been told of the receipt, so delete it
4238
sock->udp2w_rdata_out=socket_rdata_delete(sock->udp2w_rdata_out,
4245
if (type==SOCKET_UDP2W_PROTOCOL_PING)
4247
//This has already done its job by making something happen on the link