summaryrefslogtreecommitdiff
path: root/server/src/tcpsocket.cc
blob: 6fc521f5e0e75ab77a806e1ae490316bca6a169d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/***************************************************************************
 *            tcpsocket.cc
 *
 *  Thu Oct 19 10:24:25 CEST 2006
 *  Copyright  2006 Bent Bisballe Nyeng
 *  deva@aasimon.org
 ****************************************************************************/

/*
 *  This file is part of Artefact.
 *
 *  Artefact is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Artefact is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Artefact; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */
#include "tcpsocket.h"

#include "debug.h"

#include "tostring.h"

// for gethostbyname
#include <netdb.h>

// for inet_addr
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// for connect, listen, bind and accept
#include <sys/types.h>
#include <sys/socket.h>

// For socket
#include <sys/types.h>
#include <sys/socket.h>

// For TCP
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

// For inet_ntoa
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// For close
#include <unistd.h>

#include <string.h>
#include <errno.h>
#include <stdio.h>

// For ioctl
#include <sys/ioctl.h>

// For socket and friends
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>

// For fcntl
#include <unistd.h>
#include <fcntl.h>

TCPSocket::TCPSocket()
  throw(TCPSocketException)
{
  if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
    throw TCPSocketException(strerror(errno));
  }
  isconnected = false;
}

TCPSocket::~TCPSocket()
{
  disconnect();
}


static int _listen(int sockfd, int backlog){return listen(sockfd, backlog);}
void TCPSocket::listen(unsigned short int port)
  throw(TCPListenException)
{

  if(sock == -1) {
    throw TCPListenException("Socket not initialized.");
  }

  if(isconnected) {
    throw TCPListenException("Socket already connected.");
  }

  struct sockaddr_in socketaddr;
  memset((char *) &socketaddr, sizeof(socketaddr), 0);
  socketaddr.sin_family = AF_INET;
  socketaddr.sin_port = htons(port);
  socketaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  
  if(bind(sock, (struct sockaddr*)&socketaddr, sizeof(socketaddr)) == -1) {
    throw TCPListenException(std::string("bind failed - ") + strerror(errno));
  }

  if(_listen(sock, 5) == -1) {
    throw TCPListenException(std::string("listen failed - ") + strerror(errno));
  }

  isconnected = true;
}


static int _accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{return accept(sockfd, addr, addrlen);}
TCPSocket TCPSocket::accept()
  throw(TCPAcceptException)
{
  TCPSocket child;

  if(sock == -1) {
    throw TCPAcceptException("Socket not initialized.");
  }

  if(!isconnected) {
    throw TCPAcceptException("Socket not connected.");
  }

  // accept new connection and get its connection descriptor
  struct sockaddr_in ssocketaddr;
  int csalen = sizeof(ssocketaddr);

  child.disconnect(); // We need to close the existing socket
  child.sock = _accept(sock, (struct sockaddr*)&ssocketaddr, (socklen_t*)&csalen);

  if (child.sock == -1) {
    throw TCPAcceptException(std::string("accept failed - ") + strerror(errno));
  }

  child.isconnected = true;
  return child;
}


static int _connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen)
{return connect(sockfd, serv_addr, addrlen);}
void TCPSocket::connect(std::string addr, unsigned short int port)
  throw(TCPConnectException)
  
{
  if(isconnected) {
    throw TCPConnectException("Socket already connected.", "", "");
  }

#ifndef BYPASS_STATICALLOCATIONS
  // Do DNS lookup
  char *ip;
  struct in_addr **addr_list;
  struct hostent *he;
  he = gethostbyname(addr.c_str());
  if(!he || !he->h_length) {
    throw TCPConnectException(addr, toString(port),
                              std::string("host lookup failed: ") + hstrerror(h_errno));
  }

  addr_list = (struct in_addr **)he->h_addr_list;
  //  Get first value. We know for sure that there are at least one.
  ip = inet_ntoa(*addr_list[0]);
#else/*BYPASS_STATICALLOCATIONS*/
  char *ip = "127.0.0.1";
#endif/*BYPASS_STATICALLOCATIONS*/

  struct sockaddr_in socketaddr;
  memset((char *) &socketaddr, sizeof(socketaddr), 0);
  socketaddr.sin_family = AF_INET;
  socketaddr.sin_port = htons(port);
  socketaddr.sin_addr.s_addr = inet_addr(ip);

  if(_connect(sock, (struct sockaddr*)&socketaddr, sizeof(socketaddr))) {
    throw TCPConnectException(addr, toString(port), hstrerror(h_errno));
  }

  isconnected = true;
}

void TCPSocket::disconnect()
{
  if(sock != -1) {
    close(sock);
    sock = -1;
  }
  isconnected = false;
}

bool TCPSocket::connected()
{
  return sock != -1 && isconnected;
}

int TCPSocket::read(char *buf, int size)
  throw(TCPReadException)
{
  int res = 0;

  if(sock == -1) {
    throw TCPReadException("Socket not initialized.");
  }

  if(!isconnected) {
    throw TCPReadException("Socket is not connected.");
  }

  /*
  if( (res = recv(sock, buf, size, MSG_WAITALL)) == -1 ) {
    throw TCPReadException(strerror(errno));
  }
  */

  // Wait until something is ready to be read ( peek'a'loop ).
  errno = EAGAIN;
  while( recv(sock, buf, 1, MSG_PEEK) == -1 && errno == EAGAIN) {
    sleep(1);
  }

  // Now read it
  if( (res = recv(sock, buf, size, MSG_DONTWAIT)) == -1 ) {
    throw TCPReadException(strerror(errno));
  }

  return res;
}

int TCPSocket::write(char *data, int size)
  throw(TCPWriteException)
{
  if(sock == -1) {
    throw TCPWriteException("Socket not initialized.");
  }

  if(!isconnected) {
    throw TCPWriteException("Socket is not connected.");
  }

  int res;
  if( (res = send(sock, data, size, MSG_WAITALL)) == -1 ) {
    throw TCPWriteException(strerror(errno));
  }

  return res;
}

std::string TCPSocket::srcaddr()
  throw(TCPNameException)
{
  std::string addr;

#ifndef BYPASS_STATICALLOCATIONS
  struct sockaddr_in name;
  socklen_t namelen = sizeof(name);
  if(getpeername(sock, (sockaddr*)&name, &namelen) == -1) {
    throw TCPNameException(strerror(errno));
  }

  addr = inet_ntoa(name.sin_addr);
#else/*BYPASS_STATICALLOCATIONS*/
  addr = "127.0.0.1";
#endif/*BYPASS_STATICALLOCATIONS*/

  return addr;
}

std::string TCPSocket::dstaddr()
  throw(TCPNameException)
{
  std::string addr;

#ifndef BYPASS_STATICALLOCATIONS
  struct sockaddr_in name;
  socklen_t namelen = sizeof(name);
  if(getsockname(sock, (sockaddr*)&name, &namelen) == -1) {
    throw TCPNameException(strerror(errno));
  }
  
  addr = inet_ntoa(name.sin_addr);
#else/*BYPASS_STATICALLOCATIONS*/
  addr = "127.0.0.1";
#endif/*BYPASS_STATICALLOCATIONS*/

  return addr;
}

#ifdef TEST_TCPSOCKET

int main()
{
  char buf[32];

  switch(fork()) {
  case -1: // error
    fprintf(stderr, "Could not fork: %s\n", strerror(errno));
    return 1;
        
  case 0: // child
    try {
      TCPSocket client;
      sleep(1); // We need to wait for the listen socket to be created.
      client.connect("localhost", 12345);
      sprintf(buf, "hello");
      client.write(buf, sizeof(buf));
      printf("Sent: [%s]\n", buf);
    } catch( Exception &e ) {
      fprintf(stderr, "%s\n", e.what());
      return 1;
    }
    break;
        
  default: // parent
    try {
      TCPSocket listen_sock;
      listen_sock.listen(12345);
      TCPSocket sock = listen_sock.accept();
      sock.read(buf, sizeof(buf));
      printf("Got: [%s]\n", buf);
      if(std::string(buf) != "hello") return 1;
    } catch( Exception &e ) {
      fprintf(stderr, "%s\n", e.what());
      return 1;
    }
    break;
  }

  return 0;
}

#endif/*TEST_TCPSOCKET*/