SUMO - Simulation of Urban MObility
socket.cpp
Go to the documentation of this file.
1 /************************************************************************
2  ** This file is part of the network simulator Shawn. **
3  ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project **
4  ** Shawn is free software; you can redistribute it and/or modify it **
5  ** under the terms of the BSD License. Refer to the shawn-licence.txt **
6  ** file in the root of the Shawn source tree for further details. **
7  ************************************************************************/
8 
9 #ifdef SHAWN
10  #include <apps/tcpip/socket.h>
11  #include <sys/simulation/simulation_controller.h>
12 #else
13  #include "socket.h"
14 #endif
15 
16 #ifdef BUILD_TCPIP
17 
18 
19 #ifndef WIN32
20  #include <sys/types.h>
21  #include <sys/socket.h>
22  #include <netinet/in.h>
23  #include <netinet/tcp.h>
24  #include <arpa/inet.h>
25  #include <netdb.h>
26  #include <errno.h>
27  #include <fcntl.h>
28  #include <unistd.h>
29 #else
30  #ifdef ERROR
31  #undef ERROR
32  #endif
33 
34  #include <winsock2.h>
35  #include <ws2tcpip.h>
36 
37  #ifndef vsnprintf
38  #define vsnprintf _vsnprintf
39  #endif
40 
41 #endif
42 
43 #include <cstdio>
44 #include <cstring>
45 #include <cstdarg>
46 #include <cassert>
47 #include <string>
48 #include <vector>
49 #include <string>
50 #include <algorithm>
51 #include <string.h>
52 
53 
54 #ifdef SHAWN
55  extern "C" void init_tcpip( shawn::SimulationController& sc )
56  {
57  // std::cout << "tcpip init" << std::endl;
58  }
59 #endif
60 
61 namespace tcpip
62 {
63  const int Socket::lengthLen = 4;
64 
65 #ifdef WIN32
66  bool Socket::init_windows_sockets_ = true;
67  bool Socket::windows_sockets_initialized_ = false;
68  int Socket::instance_count_ = 0;
69 #endif
70 
71  // ----------------------------------------------------------------------
72  Socket::
73  Socket(std::string host, int port)
74  : host_( host ),
75  port_( port ),
76  socket_(-1),
77  server_socket_(-1),
78  blocking_(true),
79  verbose_(false)
80  {
81  init();
82  }
83 
84  // ----------------------------------------------------------------------
85  Socket::
87  : host_(""),
88  port_( port ),
89  socket_(-1),
90  server_socket_(-1),
91  blocking_(true),
92  verbose_(false)
93  {
94  init();
95  }
96 
97  // ----------------------------------------------------------------------
98  void
99  Socket::
101  {
102 #ifdef WIN32
103  instance_count_++;
104 
105  if( init_windows_sockets_ && !windows_sockets_initialized_ )
106  {
107  WSAData wsaData;
108  if( WSAStartup(MAKEWORD(1, 1), &wsaData) != 0 )
109  BailOnSocketError("Unable to init WSA Sockets");
110  windows_sockets_initialized_ = true;
111  }
112 #endif
113  }
114 
115  // ----------------------------------------------------------------------
116  Socket::
118  {
119  // Close first an existing client connection ...
120  close();
121 #ifdef WIN32
122  instance_count_--;
123 #endif
124 
125  // ... then the server socket
126  if( server_socket_ >= 0 )
127  {
128 #ifdef WIN32
129  ::closesocket( server_socket_ );
130 #else
132 #endif
133  server_socket_ = -1;
134  }
135 
136 #ifdef WIN32
137  if( server_socket_ == -1 && socket_ == -1
138  && init_windows_sockets_ && instance_count_ == 0 )
139  WSACleanup();
140  windows_sockets_initialized_ = false;
141 #endif
142  }
143 
144  // ----------------------------------------------------------------------
145  void
146  Socket::
147  BailOnSocketError( std::string context)
148  const throw( SocketException )
149  {
150 #ifdef WIN32
151  int e = WSAGetLastError();
152  std::string msg = GetWinsockErrorString( e );
153 #else
154  std::string msg = strerror( errno );
155 #endif
156  throw SocketException( context + ": " + msg );
157  }
158 
159  // ----------------------------------------------------------------------
160  int
161  Socket::
163  {
164  return port_;
165  }
166 
167 
168  // ----------------------------------------------------------------------
169  bool
170  Socket::
171  datawaiting(int sock)
172  const throw()
173  {
174  fd_set fds;
175  FD_ZERO( &fds );
176  FD_SET( (unsigned int)sock, &fds );
177 
178  struct timeval tv;
179  tv.tv_sec = 0;
180  tv.tv_usec = 0;
181 
182  int r = select( sock+1, &fds, NULL, NULL, &tv);
183 
184  if (r < 0)
185  BailOnSocketError("tcpip::Socket::datawaiting @ select");
186 
187  if( FD_ISSET( sock, &fds ) )
188  return true;
189  else
190  return false;
191  }
192 
193  // ----------------------------------------------------------------------
194  bool
195  Socket::
196  atoaddr( std::string address, struct sockaddr_in& addr)
197  {
198  int status;
199  struct addrinfo *servinfo; // will point to the results
200 
201  struct addrinfo hints;
202  memset(&hints, 0, sizeof hints); // make sure the struct is empty
203  hints.ai_family = AF_INET; // restrict to IPv4?
204  hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
205  hints.ai_flags = AI_PASSIVE; // fill in my IP for me
206 
207  if ((status = getaddrinfo(address.c_str(), NULL, &hints, &servinfo)) != 0) {
208  return false;
209  }
210 
211  bool valid = false;
212 
213  for (struct addrinfo *p = servinfo; p != NULL; p = p->ai_next) {
214  if (p->ai_family == AF_INET) { // IPv4
215  addr = *(struct sockaddr_in *)p->ai_addr;
216  addr.sin_port = htons((unsigned short)port_);
217  valid = true;
218  break;
219  }
220  }
221 
222  freeaddrinfo(servinfo); // free the linked list
223 
224  return valid;
225  }
226 
227 
228  // ----------------------------------------------------------------------
229  void
230  Socket::
232  throw( SocketException )
233  {
234  if( socket_ >= 0 )
235  return;
236 
237  struct sockaddr_in client_addr;
238 #ifdef WIN32
239  int addrlen = sizeof(client_addr);
240 #else
241  socklen_t addrlen = sizeof(client_addr);
242 #endif
243 
244  if( server_socket_ < 0 )
245  {
246  struct sockaddr_in self;
247 
248  //Create the server socket
249  server_socket_ = static_cast<int>(socket( AF_INET, SOCK_STREAM, 0 ));
250  if( server_socket_ < 0 )
251  BailOnSocketError("tcpip::Socket::accept() @ socket");
252 
253  //"Address already in use" error protection
254  {
255 
256  #ifdef WIN32
257  //setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseaddr, sizeof(reuseaddr));
258  // No address reuse in Windows!!!
259  #else
260  int reuseaddr = 1;
261  setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
262  #endif
263  }
264 
265  // Initialize address/port structure
266  memset(&self, 0, sizeof(self));
267  self.sin_family = AF_INET;
268  self.sin_port = htons((unsigned short)port_);
269  self.sin_addr.s_addr = htonl(INADDR_ANY);
270 
271  // Assign a port number to the socket
272  if ( bind(server_socket_, (struct sockaddr*)&self, sizeof(self)) != 0 )
273  BailOnSocketError("tcpip::Socket::accept() Unable to create listening socket");
274 
275 
276  // Make it a "listening socket"
277  if ( listen(server_socket_, 10) == -1 )
278  BailOnSocketError("tcpip::Socket::accept() Unable to listen on server socket");
279 
280  // Make the newly created socket blocking or not
282  }
283 
284  socket_ = static_cast<int>(::accept(server_socket_, (struct sockaddr*)&client_addr, &addrlen));
285 
286  if( socket_ >= 0 )
287  {
288  int x = 1;
289  setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (const char*)&x, sizeof(x));
290  }
291  }
292 
293  // ----------------------------------------------------------------------
294  void
295  Socket::
296  set_blocking(bool blocking)
297  throw(SocketException )
298  {
299  blocking_ = blocking;
300 
301  if( server_socket_ > 0 )
302  {
303 #ifdef WIN32
304  ULONG NonBlock = blocking_ ? 0 : 1;
305  if (ioctlsocket(server_socket_, FIONBIO, &NonBlock) == SOCKET_ERROR)
306  BailOnSocketError("tcpip::Socket::set_blocking() Unable to initialize non blocking I/O");
307 #else
308  long arg = fcntl(server_socket_, F_GETFL, NULL);
309  if (blocking_)
310  {
311  arg &= ~O_NONBLOCK;
312  } else {
313  arg |= O_NONBLOCK;
314  }
315  fcntl(server_socket_, F_SETFL, arg);
316 #endif
317  }
318 
319  }
320 
321  // ----------------------------------------------------------------------
322  void
323  Socket::
325  throw( SocketException )
326  {
327  sockaddr_in address;
328 
329  if( !atoaddr( host_.c_str(), address) )
330  BailOnSocketError("tcpip::Socket::connect() @ Invalid network address");
331 
332  socket_ = static_cast<int>(socket( PF_INET, SOCK_STREAM, 0 ));
333  if( socket_ < 0 )
334  BailOnSocketError("tcpip::Socket::connect() @ socket");
335 
336  if( ::connect( socket_, (sockaddr const*)&address, sizeof(address) ) < 0 )
337  BailOnSocketError("tcpip::Socket::connect() @ connect");
338 
339  if( socket_ >= 0 )
340  {
341  int x = 1;
342  setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (const char*)&x, sizeof(x));
343  }
344  }
345 
346  // ----------------------------------------------------------------------
347  void
348  Socket::
350  {
351  // Close client-connection
352  if( socket_ >= 0 )
353  {
354 #ifdef WIN32
355  ::closesocket( socket_ );
356 #else
357  ::close( socket_ );
358 #endif
359 
360  socket_ = -1;
361  }
362  }
363 
364  // ----------------------------------------------------------------------
365  void
366  Socket::
367  send( const std::vector<unsigned char> &buffer)
368  throw( SocketException )
369  {
370  if( socket_ < 0 )
371  return;
372 
373  printBufferOnVerbose(buffer, "Send");
374 
375  size_t numbytes = buffer.size();
376  unsigned char const *bufPtr = &buffer[0];
377  while( numbytes > 0 )
378  {
379 #ifdef WIN32
380  int bytesSent = ::send( socket_, (const char*)bufPtr, static_cast<int>(numbytes), 0 );
381 #else
382  int bytesSent = ::send( socket_, bufPtr, numbytes, 0 );
383 #endif
384  if( bytesSent < 0 )
385  BailOnSocketError( "send failed" );
386 
387  numbytes -= bytesSent;
388  bufPtr += bytesSent;
389  }
390  }
391 
392 
393 
394  // ----------------------------------------------------------------------
395 
396  void
397  Socket::
398  sendExact( const Storage &b)
399  throw( SocketException )
400  {
401  int length = static_cast<int>(b.size());
402  Storage length_storage;
403  length_storage.writeInt(lengthLen + length);
404 
405  // Sending length_storage and b independently would probably be possible and
406  // avoid some copying here, but both parts would have to go through the
407  // TCP/IP stack on their own which probably would cost more performance.
408  std::vector<unsigned char> msg;
409  msg.insert(msg.end(), length_storage.begin(), length_storage.end());
410  msg.insert(msg.end(), b.begin(), b.end());
411  send(msg);
412  }
413 
414 
415  // ----------------------------------------------------------------------
416  size_t
417  Socket::
418  recvAndCheck(unsigned char * const buffer, std::size_t len)
419  const
420  {
421 #ifdef WIN32
422  const int bytesReceived = recv( socket_, (char*)buffer, static_cast<int>(len), 0 );
423 #else
424  const int bytesReceived = static_cast<int>(recv( socket_, buffer, len, 0 ));
425 #endif
426  if( bytesReceived == 0 )
427  throw SocketException( "tcpip::Socket::recvAndCheck @ recv: peer shutdown" );
428  if( bytesReceived < 0 )
429  BailOnSocketError( "tcpip::Socket::recvAndCheck @ recv" );
430 
431  return static_cast<size_t>(bytesReceived);
432  }
433 
434 
435  // ----------------------------------------------------------------------
436  void
437  Socket::
438  receiveComplete(unsigned char * buffer, size_t len)
439  const
440  {
441  while (len > 0)
442  {
443  const size_t bytesReceived = recvAndCheck(buffer, len);
444  len -= bytesReceived;
445  buffer += bytesReceived;
446  }
447  }
448 
449 
450  // ----------------------------------------------------------------------
451  void
452  Socket::
453  printBufferOnVerbose(const std::vector<unsigned char> buffer, const std::string &label)
454  const
455  {
456  if (verbose_)
457  {
458  std::cerr << label << " " << buffer.size() << " bytes via tcpip::Socket: [";
459  // cache end iterator for performance
460  const std::vector<unsigned char>::const_iterator end = buffer.end();
461  for (std::vector<unsigned char>::const_iterator it = buffer.begin(); end != it; ++it)
462  std::cerr << " " << static_cast<int>(*it) << " ";
463  std::cerr << "]" << std::endl;
464  }
465  }
466 
467 
468  // ----------------------------------------------------------------------
469  std::vector<unsigned char>
470  Socket::
471  receive(int bufSize)
472  throw( SocketException )
473  {
474  std::vector<unsigned char> buffer;
475 
476  if( socket_ < 0 )
477  connect();
478 
479  if( !datawaiting( socket_) )
480  return buffer;
481 
482  buffer.resize(bufSize);
483  const size_t bytesReceived = recvAndCheck(&buffer[0], bufSize);
484 
485  buffer.resize(bytesReceived);
486 
487  printBufferOnVerbose(buffer, "Rcvd");
488 
489  return buffer;
490  }
491 
492  // ----------------------------------------------------------------------
493 
494 
495  bool
496  Socket::
498  throw( SocketException )
499  {
500  // buffer for received bytes
501  // According to the C++ standard elements of a std::vector are stored
502  // contiguously. Explicitly &buffer[n] == &buffer[0] + n for 0 <= n < buffer.size().
503  std::vector<unsigned char> buffer(lengthLen);
504 
505  // receive length of TraCI message
506  receiveComplete(&buffer[0], lengthLen);
507  Storage length_storage(&buffer[0], lengthLen);
508  const int totalLen = length_storage.readInt();
509  assert(totalLen > lengthLen);
510 
511  // extent buffer
512  buffer.resize(totalLen);
513 
514  // receive remaining TraCI message
515  receiveComplete(&buffer[lengthLen], totalLen - lengthLen);
516 
517  // copy message content into passed Storage
518  msg.reset();
519  msg.writePacket(&buffer[lengthLen], totalLen - lengthLen);
520 
521  printBufferOnVerbose(buffer, "Rcvd Storage with");
522 
523  return true;
524  }
525 
526 
527  // ----------------------------------------------------------------------
528  bool
529  Socket::
531  const
532  {
533  return socket_ >= 0;
534  }
535 
536  // ----------------------------------------------------------------------
537  bool
538  Socket::
540  throw()
541  {
542  return blocking_;
543  }
544 
545 
546 #ifdef WIN32
547  // ----------------------------------------------------------------------
548  std::string
549  Socket::
550  GetWinsockErrorString(int err)
551  const
552  {
553 
554  switch( err)
555  {
556  case 0: return "No error";
557  case WSAEINTR: return "Interrupted system call";
558  case WSAEBADF: return "Bad file number";
559  case WSAEACCES: return "Permission denied";
560  case WSAEFAULT: return "Bad address";
561  case WSAEINVAL: return "Invalid argument";
562  case WSAEMFILE: return "Too many open sockets";
563  case WSAEWOULDBLOCK: return "Operation would block";
564  case WSAEINPROGRESS: return "Operation now in progress";
565  case WSAEALREADY: return "Operation already in progress";
566  case WSAENOTSOCK: return "Socket operation on non-socket";
567  case WSAEDESTADDRREQ: return "Destination address required";
568  case WSAEMSGSIZE: return "Message too long";
569  case WSAEPROTOTYPE: return "Protocol wrong type for socket";
570  case WSAENOPROTOOPT: return "Bad protocol option";
571  case WSAEPROTONOSUPPORT: return "Protocol not supported";
572  case WSAESOCKTNOSUPPORT: return "Socket type not supported";
573  case WSAEOPNOTSUPP: return "Operation not supported on socket";
574  case WSAEPFNOSUPPORT: return "Protocol family not supported";
575  case WSAEAFNOSUPPORT: return "Address family not supported";
576  case WSAEADDRINUSE: return "Address already in use";
577  case WSAEADDRNOTAVAIL: return "Can't assign requested address";
578  case WSAENETDOWN: return "Network is down";
579  case WSAENETUNREACH: return "Network is unreachable";
580  case WSAENETRESET: return "Net Socket reset";
581  case WSAECONNABORTED: return "Software caused tcpip::Socket abort";
582  case WSAECONNRESET: return "Socket reset by peer";
583  case WSAENOBUFS: return "No buffer space available";
584  case WSAEISCONN: return "Socket is already connected";
585  case WSAENOTCONN: return "Socket is not connected";
586  case WSAESHUTDOWN: return "Can't send after socket shutdown";
587  case WSAETOOMANYREFS: return "Too many references, can't splice";
588  case WSAETIMEDOUT: return "Socket timed out";
589  case WSAECONNREFUSED: return "Socket refused";
590  case WSAELOOP: return "Too many levels of symbolic links";
591  case WSAENAMETOOLONG: return "File name too long";
592  case WSAEHOSTDOWN: return "Host is down";
593  case WSAEHOSTUNREACH: return "No route to host";
594  case WSAENOTEMPTY: return "Directory not empty";
595  case WSAEPROCLIM: return "Too many processes";
596  case WSAEUSERS: return "Too many users";
597  case WSAEDQUOT: return "Disc quota exceeded";
598  case WSAESTALE: return "Stale NFS file handle";
599  case WSAEREMOTE: return "Too many levels of remote in path";
600  case WSASYSNOTREADY: return "Network system is unavailable";
601  case WSAVERNOTSUPPORTED: return "Winsock version out of range";
602  case WSANOTINITIALISED: return "WSAStartup not yet called";
603  case WSAEDISCON: return "Graceful shutdown in progress";
604  case WSAHOST_NOT_FOUND: return "Host not found";
605  case WSANO_DATA: return "No host data of that type was found";
606  }
607 
608  return "unknown";
609  }
610 
611 #endif // WIN32
612 
613 } // namespace tcpip
614 
615 #endif // BUILD_TCPIP
616 
617 /*-----------------------------------------------------------------------
618 * Source $Source: $
619 * Version $Revision: 645 $
620 * Date $Date: 2012-04-27 14:03:33 +0200 (Fri, 27 Apr 2012) $
621 *-----------------------------------------------------------------------
622 * $Log: $
623 *-----------------------------------------------------------------------*/
Definition: socket.cpp:61
StorageType::const_iterator end() const
Definition: storage.h:118
void BailOnSocketError(std::string) const
Definition: socket.cpp:147
bool receiveExact(Storage &)
Receive a complete TraCI message from Socket::socket_.
Definition: socket.cpp:497
int server_socket_
Definition: socket.h:136
std::vector< unsigned char > receive(int bufSize=2048)
Receive up to bufSize available bytes from Socket::socket_.
Definition: socket.cpp:471
void accept()
Wait for a incoming connection to port_.
Definition: socket.cpp:231
bool blocking_
Definition: socket.h:137
static const int lengthLen
Length of the message length part of a TraCI message.
Definition: socket.h:115
Socket(std::string host, int port)
Constructor that prepare to connect to host:port.
Definition: socket.cpp:73
bool has_client_connection() const
Definition: socket.cpp:530
virtual void writeInt(int)
void connect()
Connects to host_:port_.
Definition: socket.cpp:324
std::string host_
Definition: socket.h:133
void receiveComplete(unsigned char *const buffer, std::size_t len) const
Receive len bytes from Socket::socket_.
Definition: socket.cpp:438
virtual int readInt()
void printBufferOnVerbose(const std::vector< unsigned char > buffer, const std::string &label) const
Print label and buffer to stderr if Socket::verbose_ is set.
Definition: socket.cpp:453
~Socket()
Destructor.
Definition: socket.cpp:117
void send(const std::vector< unsigned char > &buffer)
Definition: socket.cpp:367
void sendExact(const Storage &)
Definition: socket.cpp:398
bool is_blocking()
Definition: socket.cpp:539
StorageType::const_iterator begin() const
Definition: storage.h:117
bool atoaddr(std::string, struct sockaddr_in &addr)
Definition: socket.cpp:196
int port()
Definition: socket.cpp:162
void init()
Definition: socket.cpp:100
bool datawaiting(int sock) const
Definition: socket.cpp:171
bool verbose_
Definition: socket.h:139
int socket_
Definition: socket.h:135
void set_blocking(bool)
Definition: socket.cpp:296
void close()
Definition: socket.cpp:349
size_t recvAndCheck(unsigned char *const buffer, std::size_t len) const
Receive up to len available bytes from Socket::socket_.
Definition: socket.cpp:418