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