Eclipse 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  // ----------------------------------------------------------------------
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  // ----------------------------------------------------------------------
86  Socket(int port)
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
100  init()
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  int
119  {
120  Socket dummy(0); // just to trigger initialization on Windows and cleanup on end
121  // Create socket to find a random free port that can be handed to the app
122  int sock = static_cast<int>(socket( AF_INET, SOCK_STREAM, 0 ));
123  struct sockaddr_in self;
124  memset(&self, 0, sizeof(self));
125  self.sin_family = AF_INET;
126  self.sin_port = htons(0);
127  self.sin_addr.s_addr = htonl(INADDR_ANY);
128 
129  socklen_t address_len = sizeof(self);
130  // bind with port==0 assigns free port
131  if ( bind(sock, (struct sockaddr*) &self, address_len) < 0)
132  BailOnSocketError("tcpip::Socket::getFreeSocketPort() Unable to bind socket");
133  // get the assigned port with getsockname
134  if ( getsockname(sock, (struct sockaddr*) &self, &address_len) < 0)
135  BailOnSocketError("tcpip::Socket::getFreeSocketPort() Unable to get socket name");
136  const int port = ntohs(self.sin_port);
137 #ifdef WIN32
138  ::closesocket( sock );
139 #else
140  ::close( sock );
141 #endif
142  return port;
143  }
144 
145 
146  // ----------------------------------------------------------------------
148  ~Socket()
149  {
150  // Close first an existing client connection ...
151  close();
152 #ifdef WIN32
153  instance_count_--;
154 #endif
155 
156  // ... then the server socket
157  if( server_socket_ >= 0 )
158  {
159 #ifdef WIN32
160  ::closesocket( server_socket_ );
161 #else
163 #endif
164  server_socket_ = -1;
165  }
166 
167 #ifdef WIN32
168  if( server_socket_ == -1 && socket_ == -1
169  && init_windows_sockets_ && instance_count_ == 0 )
170  WSACleanup();
171  windows_sockets_initialized_ = false;
172 #endif
173  }
174 
175  // ----------------------------------------------------------------------
176  void
178  BailOnSocketError( std::string context)
179  {
180 #ifdef WIN32
181  int e = WSAGetLastError();
182  std::string msg = GetWinsockErrorString( e );
183 #else
184  std::string msg = strerror( errno );
185 #endif
186  throw SocketException( context + ": " + msg );
187  }
188 
189  // ----------------------------------------------------------------------
190  int
192  port()
193  {
194  return port_;
195  }
196 
197 
198  // ----------------------------------------------------------------------
199  bool
201  datawaiting(int sock)
202  const
203  {
204  fd_set fds;
205  FD_ZERO( &fds );
206  FD_SET( (unsigned int)sock, &fds );
207 
208  struct timeval tv;
209  tv.tv_sec = 0;
210  tv.tv_usec = 0;
211 
212  int r = select( sock+1, &fds, nullptr, nullptr, &tv);
213 
214  if (r < 0)
215  BailOnSocketError("tcpip::Socket::datawaiting @ select");
216 
217  if( FD_ISSET( sock, &fds ) )
218  return true;
219  else
220  return false;
221  }
222 
223  // ----------------------------------------------------------------------
224  bool
226  atoaddr( std::string address, struct sockaddr_in& addr)
227  {
228  int status;
229  struct addrinfo *servinfo; // will point to the results
230 
231  struct addrinfo hints;
232  memset(&hints, 0, sizeof hints); // make sure the struct is empty
233  hints.ai_family = AF_INET; // restrict to IPv4?
234  hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
235  hints.ai_flags = AI_PASSIVE; // fill in my IP for me
236 
237  if ((status = getaddrinfo(address.c_str(), nullptr, &hints, &servinfo)) != 0) {
238  return false;
239  }
240 
241  bool valid = false;
242 
243  for (struct addrinfo *p = servinfo; p != nullptr; p = p->ai_next) {
244  if (p->ai_family == AF_INET) { // IPv4
245  addr = *(struct sockaddr_in *)p->ai_addr;
246  addr.sin_port = htons((unsigned short)port_);
247  valid = true;
248  break;
249  }
250  }
251 
252  freeaddrinfo(servinfo); // free the linked list
253 
254  return valid;
255  }
256 
257 
258  // ----------------------------------------------------------------------
259  Socket*
261  accept(const bool create)
262  {
263  if( socket_ >= 0 )
264  return nullptr;
265 
266  struct sockaddr_in client_addr;
267 #ifdef WIN32
268  int addrlen = sizeof(client_addr);
269 #else
270  socklen_t addrlen = sizeof(client_addr);
271 #endif
272 
273  if( server_socket_ < 0 )
274  {
275  struct sockaddr_in self;
276 
277  //Create the server socket
278  server_socket_ = static_cast<int>(socket( AF_INET, SOCK_STREAM, 0 ));
279  if( server_socket_ < 0 )
280  BailOnSocketError("tcpip::Socket::accept() @ socket");
281 
282  //"Address already in use" error protection
283  {
284 
285  #ifdef WIN32
286  //setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseaddr, sizeof(reuseaddr));
287  // No address reuse in Windows!!!
288  #else
289  int reuseaddr = 1;
290  setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
291  #endif
292  }
293 
294  // Initialize address/port structure
295  memset(&self, 0, sizeof(self));
296  self.sin_family = AF_INET;
297  self.sin_port = htons((unsigned short)port_);
298  self.sin_addr.s_addr = htonl(INADDR_ANY);
299 
300  // Assign a port number to the socket
301  if ( bind(server_socket_, (struct sockaddr*)&self, sizeof(self)) != 0 )
302  BailOnSocketError("tcpip::Socket::accept() Unable to create listening socket");
303 
304 
305  // Make it a "listening socket"
306  if ( listen(server_socket_, 10) == -1 )
307  BailOnSocketError("tcpip::Socket::accept() Unable to listen on server socket");
308 
309  // Make the newly created socket blocking or not
311  }
312 
313  socket_ = static_cast<int>(::accept(server_socket_, (struct sockaddr*)&client_addr, &addrlen));
314 
315  if( socket_ >= 0 )
316  {
317  int x = 1;
318  setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (const char*)&x, sizeof(x));
319  if (create) {
320  Socket* result = new Socket(0);
321  result->socket_ = socket_;
322  socket_ = -1;
323  return result;
324  }
325  }
326  return nullptr;
327  }
328 
329  // ----------------------------------------------------------------------
330  void
332  set_blocking(bool blocking)
333  {
334  blocking_ = blocking;
335 
336  if( server_socket_ > 0 )
337  {
338 #ifdef WIN32
339  ULONG NonBlock = blocking_ ? 0 : 1;
340  if (ioctlsocket(server_socket_, FIONBIO, &NonBlock) == SOCKET_ERROR)
341  BailOnSocketError("tcpip::Socket::set_blocking() Unable to initialize non blocking I/O");
342 #else
343  long arg = fcntl(server_socket_, F_GETFL, NULL);
344  if (blocking_)
345  {
346  arg &= ~O_NONBLOCK;
347  } else {
348  arg |= O_NONBLOCK;
349  }
350  fcntl(server_socket_, F_SETFL, arg);
351 #endif
352  }
353 
354  }
355 
356  // ----------------------------------------------------------------------
357  void
359  connect()
360  {
361  sockaddr_in address;
362 
363  if( !atoaddr( host_.c_str(), address) )
364  BailOnSocketError("tcpip::Socket::connect() @ Invalid network address");
365 
366  socket_ = static_cast<int>(socket( PF_INET, SOCK_STREAM, 0 ));
367  if( socket_ < 0 )
368  BailOnSocketError("tcpip::Socket::connect() @ socket");
369 
370  if( ::connect( socket_, (sockaddr const*)&address, sizeof(address) ) < 0 )
371  BailOnSocketError("tcpip::Socket::connect() @ connect");
372 
373  if( socket_ >= 0 )
374  {
375  int x = 1;
376  setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (const char*)&x, sizeof(x));
377  }
378  }
379 
380  // ----------------------------------------------------------------------
381  void
383  close()
384  {
385  // Close client-connection
386  if( socket_ >= 0 )
387  {
388 #ifdef WIN32
389  ::closesocket( socket_ );
390 #else
391  ::close( socket_ );
392 #endif
393 
394  socket_ = -1;
395  }
396  }
397 
398  // ----------------------------------------------------------------------
399  void
401  send( const std::vector<unsigned char> &buffer)
402  {
403  if( socket_ < 0 )
404  return;
405 
406  printBufferOnVerbose(buffer, "Send");
407 
408  size_t numbytes = buffer.size();
409  unsigned char const *bufPtr = &buffer[0];
410  while( numbytes > 0 )
411  {
412 #ifdef WIN32
413  int bytesSent = ::send( socket_, (const char*)bufPtr, static_cast<int>(numbytes), 0 );
414 #else
415  int bytesSent = ::send( socket_, bufPtr, numbytes, 0 );
416 #endif
417  if( bytesSent < 0 )
418  BailOnSocketError( "send failed" );
419 
420  numbytes -= bytesSent;
421  bufPtr += bytesSent;
422  }
423  }
424 
425 
426 
427  // ----------------------------------------------------------------------
428 
429  void
431  sendExact( const Storage &b)
432  {
433  int length = static_cast<int>(b.size());
434  Storage length_storage;
435  length_storage.writeInt(lengthLen + length);
436 
437  // Sending length_storage and b independently would probably be possible and
438  // avoid some copying here, but both parts would have to go through the
439  // TCP/IP stack on their own which probably would cost more performance.
440  std::vector<unsigned char> msg;
441  msg.insert(msg.end(), length_storage.begin(), length_storage.end());
442  msg.insert(msg.end(), b.begin(), b.end());
443  send(msg);
444  }
445 
446 
447  // ----------------------------------------------------------------------
448  size_t
450  recvAndCheck(unsigned char * const buffer, std::size_t len)
451  const
452  {
453 #ifdef WIN32
454  const int bytesReceived = recv( socket_, (char*)buffer, static_cast<int>(len), 0 );
455 #else
456  const int bytesReceived = static_cast<int>(recv( socket_, buffer, len, 0 ));
457 #endif
458  if( bytesReceived == 0 )
459  throw SocketException( "tcpip::Socket::recvAndCheck @ recv: peer shutdown" );
460  if( bytesReceived < 0 )
461  BailOnSocketError( "tcpip::Socket::recvAndCheck @ recv" );
462 
463  return static_cast<size_t>(bytesReceived);
464  }
465 
466 
467  // ----------------------------------------------------------------------
468  void
470  receiveComplete(unsigned char * buffer, size_t len)
471  const
472  {
473  while (len > 0)
474  {
475  const size_t bytesReceived = recvAndCheck(buffer, len);
476  len -= bytesReceived;
477  buffer += bytesReceived;
478  }
479  }
480 
481 
482  // ----------------------------------------------------------------------
483  void
485  printBufferOnVerbose(const std::vector<unsigned char> buffer, const std::string &label)
486  const
487  {
488  if (verbose_)
489  {
490  std::cerr << label << " " << buffer.size() << " bytes via tcpip::Socket: [";
491  // cache end iterator for performance
492  const std::vector<unsigned char>::const_iterator end = buffer.end();
493  for (std::vector<unsigned char>::const_iterator it = buffer.begin(); end != it; ++it)
494  std::cerr << " " << static_cast<int>(*it) << " ";
495  std::cerr << "]" << std::endl;
496  }
497  }
498 
499 
500  // ----------------------------------------------------------------------
501  std::vector<unsigned char>
503  receive(int bufSize)
504  {
505  std::vector<unsigned char> buffer;
506 
507  if( socket_ < 0 )
508  connect();
509 
510  if( !datawaiting( socket_) )
511  return buffer;
512 
513  buffer.resize(bufSize);
514  const size_t bytesReceived = recvAndCheck(&buffer[0], bufSize);
515 
516  buffer.resize(bytesReceived);
517 
518  printBufferOnVerbose(buffer, "Rcvd");
519 
520  return buffer;
521  }
522 
523  // ----------------------------------------------------------------------
524 
525 
526  bool
528  receiveExact( Storage &msg )
529  {
530  // buffer for received bytes
531  // According to the C++ standard elements of a std::vector are stored
532  // contiguously. Explicitly &buffer[n] == &buffer[0] + n for 0 <= n < buffer.size().
533  std::vector<unsigned char> buffer(lengthLen);
534 
535  // receive length of TraCI message
536  receiveComplete(&buffer[0], lengthLen);
537  Storage length_storage(&buffer[0], lengthLen);
538  const int totalLen = length_storage.readInt();
539  assert(totalLen > lengthLen);
540 
541  // extent buffer
542  buffer.resize(totalLen);
543 
544  // receive remaining TraCI message
545  receiveComplete(&buffer[lengthLen], totalLen - lengthLen);
546 
547  // copy message content into passed Storage
548  msg.reset();
549  msg.writePacket(&buffer[lengthLen], totalLen - lengthLen);
550 
551  printBufferOnVerbose(buffer, "Rcvd Storage with");
552 
553  return true;
554  }
555 
556 
557  // ----------------------------------------------------------------------
558  bool
561  const
562  {
563  return socket_ >= 0;
564  }
565 
566  // ----------------------------------------------------------------------
567  bool
569  is_blocking()
570  {
571  return blocking_;
572  }
573 
574 
575 #ifdef WIN32
576  // ----------------------------------------------------------------------
577  std::string
578  Socket::
579  GetWinsockErrorString(int err)
580  {
581 
582  switch( err)
583  {
584  case 0: return "No error";
585  case WSAEINTR: return "Interrupted system call";
586  case WSAEBADF: return "Bad file number";
587  case WSAEACCES: return "Permission denied";
588  case WSAEFAULT: return "Bad address";
589  case WSAEINVAL: return "Invalid argument";
590  case WSAEMFILE: return "Too many open sockets";
591  case WSAEWOULDBLOCK: return "Operation would block";
592  case WSAEINPROGRESS: return "Operation now in progress";
593  case WSAEALREADY: return "Operation already in progress";
594  case WSAENOTSOCK: return "Socket operation on non-socket";
595  case WSAEDESTADDRREQ: return "Destination address required";
596  case WSAEMSGSIZE: return "Message too long";
597  case WSAEPROTOTYPE: return "Protocol wrong type for socket";
598  case WSAENOPROTOOPT: return "Bad protocol option";
599  case WSAEPROTONOSUPPORT: return "Protocol not supported";
600  case WSAESOCKTNOSUPPORT: return "Socket type not supported";
601  case WSAEOPNOTSUPP: return "Operation not supported on socket";
602  case WSAEPFNOSUPPORT: return "Protocol family not supported";
603  case WSAEAFNOSUPPORT: return "Address family not supported";
604  case WSAEADDRINUSE: return "Address already in use";
605  case WSAEADDRNOTAVAIL: return "Can't assign requested address";
606  case WSAENETDOWN: return "Network is down";
607  case WSAENETUNREACH: return "Network is unreachable";
608  case WSAENETRESET: return "Net Socket reset";
609  case WSAECONNABORTED: return "Software caused tcpip::Socket abort";
610  case WSAECONNRESET: return "Socket reset by peer";
611  case WSAENOBUFS: return "No buffer space available";
612  case WSAEISCONN: return "Socket is already connected";
613  case WSAENOTCONN: return "Socket is not connected";
614  case WSAESHUTDOWN: return "Can't send after socket shutdown";
615  case WSAETOOMANYREFS: return "Too many references, can't splice";
616  case WSAETIMEDOUT: return "Socket timed out";
617  case WSAECONNREFUSED: return "Socket refused";
618  case WSAELOOP: return "Too many levels of symbolic links";
619  case WSAENAMETOOLONG: return "File name too long";
620  case WSAEHOSTDOWN: return "Host is down";
621  case WSAEHOSTUNREACH: return "No route to host";
622  case WSAENOTEMPTY: return "Directory not empty";
623  case WSAEPROCLIM: return "Too many processes";
624  case WSAEUSERS: return "Too many users";
625  case WSAEDQUOT: return "Disc quota exceeded";
626  case WSAESTALE: return "Stale NFS file handle";
627  case WSAEREMOTE: return "Too many levels of remote in path";
628  case WSASYSNOTREADY: return "Network system is unavailable";
629  case WSAVERNOTSUPPORTED: return "Winsock version out of range";
630  case WSANOTINITIALISED: return "WSAStartup not yet called";
631  case WSAEDISCON: return "Graceful shutdown in progress";
632  case WSAHOST_NOT_FOUND: return "Host not found";
633  case WSANO_DATA: return "No host data of that type was found";
634  }
635 
636  return "unknown";
637  }
638 
639 #endif // WIN32
640 
641 } // namespace tcpip
642 
643 #endif // BUILD_TCPIP
644 
645 /*-----------------------------------------------------------------------
646 * Source $Source: $
647 * Version $Revision: 645 $
648 * Date $Date: 2012-04-27 14:03:33 +0200 (Fri, 27 Apr 2012) $
649 *-----------------------------------------------------------------------
650 * $Log: $
651 *-----------------------------------------------------------------------*/
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:485
bool receiveExact(Storage &)
Receive a complete TraCI message from Socket::socket_.
Definition: socket.cpp:528
void init()
Definition: socket.cpp:100
std::vector< unsigned char > receive(int bufSize=2048)
Receive up to bufSize available bytes from Socket::socket_.
Definition: socket.cpp:503
bool blocking_
Definition: socket.h:123
bool datawaiting(int sock) const
Definition: socket.cpp:201
size_t recvAndCheck(unsigned char *const buffer, std::size_t len) const
Receive up to len available bytes from Socket::socket_.
Definition: socket.cpp:450
static void BailOnSocketError(std::string context)
Definition: socket.cpp:178
static int getFreeSocketPort()
Returns an free port on the system.
Definition: socket.cpp:118
bool verbose_
Definition: socket.h:125
bool is_blocking()
Definition: socket.cpp:569
int server_socket_
Definition: socket.h:122
~Socket()
Destructor.
Definition: socket.cpp:148
bool atoaddr(std::string, struct sockaddr_in &addr)
Definition: socket.cpp:226
void sendExact(const Storage &)
Definition: socket.cpp:431
int socket_
Definition: socket.h:121
bool has_client_connection() const
Definition: socket.cpp:560
void connect()
Connects to host_:port_.
Definition: socket.cpp:359
static const int lengthLen
Length of the message length part of a TraCI message.
Definition: socket.h:101
std::string host_
Definition: socket.h:119
int port()
Definition: socket.cpp:192
void set_blocking(bool)
Definition: socket.cpp:332
Socket * accept(const bool create=false)
Wait for a incoming connection to port_.
Definition: socket.cpp:261
void receiveComplete(unsigned char *const buffer, std::size_t len) const
Receive len bytes from Socket::socket_.
Definition: socket.cpp:470
void send(const std::vector< unsigned char > &buffer)
Definition: socket.cpp:401
Socket(std::string host, int port)
Constructor that prepare to connect to host:port.
Definition: socket.cpp:73
void close()
Definition: socket.cpp:383
virtual void writePacket(unsigned char *packet, int length)
Definition: storage.cpp:372
StorageType::const_iterator begin() const
Definition: storage.h:121
virtual void writeInt(int)
Definition: storage.cpp:321
StorageType::const_iterator end() const
Definition: storage.h:122
void reset()
Definition: storage.cpp:85
StorageType::size_type size() const
Definition: storage.h:119
virtual int readInt()
Definition: storage.cpp:311
static std::string strerror()
Definition: socket.cpp:62