From ef0cacf2508418915d3f64b04003be3c13fed3cc Mon Sep 17 00:00:00 2001 From: Michael Prokop Date: Mon, 2 Jan 2012 11:07:01 +0100 Subject: [PATCH] Imported Upstream version 0.3.4 --- ChangeLog | 14 +- README | 3 +- doc/anytun-config.8 | 21 +- doc/anytun-controld.8 | 19 +- doc/anytun-showtables.8 | 21 +- doc/anytun.8 | 21 +- etc/init.d/anytun | 4 +- src/anyrtpproxy/anyrtpproxy.cpp | 242 ++++++++++------------ src/anyrtpproxy/callIdQueue.cpp | 10 +- src/anyrtpproxy/callIdQueue.h | 19 +- src/anyrtpproxy/commandHandler.cpp | 90 ++++---- src/anyrtpproxy/commandHandler.h | 36 ++-- src/anyrtpproxy/connectionList.cpp | 26 +-- src/anyrtpproxy/connectionList.h | 30 +-- src/anyrtpproxy/options.cpp | 73 ++++--- src/anyrtpproxy/options.h | 49 ++--- src/anyrtpproxy/portWindow.cpp | 34 +-- src/anyrtpproxy/portWindow.h | 22 +- src/anyrtpproxy/rtpSession.cpp | 8 +- src/anyrtpproxy/rtpSession.h | 82 ++++---- src/anyrtpproxy/rtpSessionTable.cpp | 28 +-- src/anyrtpproxy/rtpSessionTable.h | 47 +++-- src/anyrtpproxy/syncRtpCommand.cpp | 14 +- src/anyrtpproxy/syncRtpCommand.h | 23 +-- src/anytun-config.cpp | 56 +++-- src/anytun-controld.cpp | 83 ++++---- src/anytun-showtables.cpp | 118 +++++------ src/anytun.cpp | 339 +++++++++++++++--------------- src/anytunError.cpp | 2 +- src/anytunError.h | 4 +- src/authAlgo.cpp | 63 +++--- src/authAlgo.h | 8 +- src/authAlgoFactory.cpp | 23 ++- src/authAlgoFactory.h | 4 +- src/bsd/tunDevice.cpp | 115 ++++++----- src/buffer.cpp | 136 ++++++------ src/buffer.h | 34 +-- src/cipher.cpp | 64 +++--- src/cipher.h | 54 ++--- src/cipherFactory.cpp | 17 +- src/cipherFactory.h | 2 +- src/configure | 32 +-- src/connectionList.cpp | 79 +++---- src/connectionList.h | 49 ++--- src/connectionParam.cpp | 4 +- src/connectionParam.h | 46 ++--- src/cryptinit.hpp | 34 +-- src/datatypes.h | 33 +-- src/deviceConfig.hpp | 44 ++-- src/encryptedPacket.cpp | 115 ++++++----- src/encryptedPacket.h | 41 ++-- src/endian.h | 2 +- src/keyDerivation.cpp | 104 +++++----- src/keyDerivation.h | 89 ++++---- src/keyDerivationFactory.cpp | 17 +- src/keyDerivationFactory.h | 2 +- src/linux/tunDevice.cpp | 89 ++++---- src/log.cpp | 39 ++-- src/log.h | 17 +- src/logTargets.cpp | 277 +++++++++++++++---------- src/logTargets.h | 31 +-- src/networkAddress.cpp | 168 ++++++++------- src/networkAddress.h | 91 ++++---- src/networkPrefix.cpp | 28 +-- src/networkPrefix.h | 27 ++- src/nullDaemon.cpp | 10 +- src/nullDaemon.h | 2 +- src/options.cpp | 212 +++++++++++-------- src/options.h | 31 +-- src/packetSource.cpp | 42 ++-- src/packetSource.h | 20 +- src/plainPacket.cpp | 111 +++++----- src/plainPacket.h | 24 +-- src/posix/posixDaemon.cpp | 107 ++++++---- src/posix/posixDaemon.h | 2 +- src/posix/signalHandler.hpp | 18 +- src/posix/sysExec.hpp | 62 +++--- src/resolver.cpp | 89 ++++---- src/resolver.h | 17 +- src/routingTable.cpp | 164 ++++++++------- src/routingTable.h | 55 ++--- src/routingTree.hpp | 47 ++--- src/routingTreeNode.cpp | 44 ++-- src/routingTreeNode.h | 16 +- src/seqWindow.cpp | 73 ++++--- src/seqWindow.h | 32 +-- src/signalController.cpp | 45 ++-- src/signalController.h | 15 +- src/syncBuffer.cpp | 2 +- src/syncBuffer.h | 34 +-- src/syncClient.cpp | 131 ++++++------ src/syncClient.h | 14 +- src/syncCommand.cpp | 36 ++-- src/syncCommand.h | 53 +++-- src/syncConnectionCommand.cpp | 18 +- src/syncConnectionCommand.h | 27 ++- src/syncOnConnect.hpp | 47 ++--- src/syncQueue.cpp | 30 +-- src/syncQueue.h | 37 ++-- src/syncRouteCommand.cpp | 14 +- src/syncRouteCommand.h | 31 ++- src/syncServer.cpp | 33 +-- src/syncServer.h | 10 +- src/syncTcpConnection.cpp | 6 +- src/syncTcpConnection.h | 15 +- src/sysExec.cpp | 4 +- src/sysExec.h | 40 ++-- src/threadUtils.hpp | 27 ++- src/tunDevice.h | 40 ++-- src/win32/registryKey.cpp | 27 ++- src/win32/registryKey.h | 8 +- src/win32/signalHandler.hpp | 5 +- src/win32/signalServiceHandler.hpp | 2 +- src/win32/sysExec.hpp | 322 +++++++++++++++-------------- src/win32/tunDevice.cpp | 103 ++++----- src/win32/winService.cpp | 402 ++++++++++++++++++------------------ src/win32/winService.h | 10 +- version | 2 +- 118 files changed, 3301 insertions(+), 2983 deletions(-) diff --git a/ChangeLog b/ChangeLog index 88a0095..f1fc68d 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,14 +1,21 @@ -20**.**.** -- Version ? +2011.12.30 -- Version 0.3.4 + +* Service Release: several build fixes for newer versions of + libboost and gcc +* formatting cleanups + +2010.2.16 -- Version 0.3.3 * Security fix: packet length check errors -* fixed droping of priveleges on FreeBSD +* fixed dropping of priveleges on FreeBSD * added sysExec for Windows * added multi socket support which allows simultanous usage of IPv4 and IPv6 even on operating systems without V4_MAPPED address support +* added workaround for signalhandling on Debian GNU/kFreebsd * added -v|--version option * added prebuilt manpage to release tarball (less build deps) - + 2009.12.02 -- Version 0.3.2 * added 64bit build target to windows build system @@ -17,6 +24,7 @@ * moved to new svn location 2009.10.28 -- Version 0.3.1 svn852 + * switched to GPLv3 or higher * Changed Windows TAP driver version to support 64-bit windows * fixed some memory errors diff --git a/README b/README index 60ef964..2ba23a5 100644 --- a/README +++ b/README @@ -104,6 +104,7 @@ Notes: because openssl had no SHA256 implementation prior to this version - on FreeBSD you have to use gmake instead of make + - the FreeBSD port has some issues concering daemonizing and signal handling Installing ---------- @@ -117,7 +118,7 @@ Uninstalling # sudo make remove -This removes everytthing except for the config files +This removes everything except for the config files # sudo make purge diff --git a/doc/anytun-config.8 b/doc/anytun-config.8 index 7947a65..706e72c 100644 --- a/doc/anytun-config.8 +++ b/doc/anytun-config.8 @@ -1,13 +1,22 @@ '\" t .\" Title: anytun-config .\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.75.1 -.\" Date: 02/16/2010 -.\" Manual: anytun-config user manual -.\" Source: anytun 0.3.3 +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 12/30/2011 +.\" Manual: \ \& +.\" Source: \ \& .\" Language: English .\" -.TH "ANYTUN\-CONFIG" "8" "02/16/2010" "anytun 0.3.3" "anytun-config user manual" +.TH "ANYTUN\-CONFIG" "8" "12/30/2011" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- @@ -121,7 +130,7 @@ the multiplex id to use\&. default: 0 .RS 4 seqence window size -Sometimes, packets arrive out of order on the receiver side\&. This option defines the size of a list of received packets\' sequence numbers\&. If, according to this list, a received packet has been previously received or has been transmitted in the past, and is therefore not in the list anymore, this is interpreted as a replay attack and the packet is dropped\&. A value of 0 deactivates this list and, as a consequence, the replay protection employed by filtering packets according to their secuence number\&. By default the sequence window is disabled and therefore a window size of 0 is used\&. +Sometimes, packets arrive out of order on the receiver side\&. This option defines the size of a list of received packets\*(Aq sequence numbers\&. If, according to this list, a received packet has been previously received or has been transmitted in the past, and is therefore not in the list anymore, this is interpreted as a replay attack and the packet is dropped\&. A value of 0 deactivates this list and, as a consequence, the replay protection employed by filtering packets according to their secuence number\&. By default the sequence window is disabled and therefore a window size of 0 is used\&. .RE .PP \fB\-k, \-\-kd\(emprf \fR\fB\fI\fR\fR diff --git a/doc/anytun-controld.8 b/doc/anytun-controld.8 index 8273d3e..36b8585 100644 --- a/doc/anytun-controld.8 +++ b/doc/anytun-controld.8 @@ -1,13 +1,22 @@ '\" t .\" Title: anytun-controld .\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.75.1 -.\" Date: 02/16/2010 -.\" Manual: anytun-controld user manual -.\" Source: anytun 0.3.3 +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 12/30/2011 +.\" Manual: \ \& +.\" Source: \ \& .\" Language: English .\" -.TH "ANYTUN\-CONTROLD" "8" "02/16/2010" "anytun 0.3.3" "anytun-controld user manual" +.TH "ANYTUN\-CONTROLD" "8" "12/30/2011" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- diff --git a/doc/anytun-showtables.8 b/doc/anytun-showtables.8 index 0f0e598..39346be 100644 --- a/doc/anytun-showtables.8 +++ b/doc/anytun-showtables.8 @@ -1,13 +1,22 @@ '\" t .\" Title: anytun-showtables .\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.75.1 -.\" Date: 02/16/2010 -.\" Manual: anytun-showtables user manual -.\" Source: anytun 0.3.3 +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 12/30/2011 +.\" Manual: \ \& +.\" Source: \ \& .\" Language: English .\" -.TH "ANYTUN\-SHOWTABLES" "8" "02/16/2010" "anytun 0.3.3" "anytun-showtables user manual" +.TH "ANYTUN\-SHOWTABLES" "8" "12/30/2011" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- @@ -39,7 +48,7 @@ Print routing table stored in local file .RS 4 .\} .nf -# perl \-ne \'chomp; print\' < routingtable | \&./anytun\-showtables +# perl \-ne \*(Aqchomp; print\*(Aq < routingtable | \&./anytun\-showtables .fi .if n \{\ .RE diff --git a/doc/anytun.8 b/doc/anytun.8 index 9a167c6..964392a 100644 --- a/doc/anytun.8 +++ b/doc/anytun.8 @@ -1,13 +1,22 @@ '\" t .\" Title: anytun .\" Author: [see the "AUTHORS" section] -.\" Generator: DocBook XSL Stylesheets v1.75.1 -.\" Date: 02/16/2010 -.\" Manual: anytun user manual -.\" Source: anytun 0.3.3 +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 12/30/2011 +.\" Manual: \ \& +.\" Source: \ \& .\" Language: English .\" -.TH "ANYTUN" "8" "02/16/2010" "anytun 0.3.3" "anytun user manual" +.TH "ANYTUN" "8" "12/30/2011" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- @@ -253,7 +262,7 @@ Each anycast tunnel endpoint needs a uniqe sender id (1, 2, 3, \&...)\&. It is n .RS 4 seqence window size -Sometimes, packets arrive out of order on the receiver side\&. This option defines the size of a list of received packets\' sequence numbers\&. If, according to this list, a received packet has been previously received or has been transmitted in the past, and is therefore not in the list anymore, this is interpreted as a replay attack and the packet is dropped\&. A value of 0 deactivates this list and, as a consequence, the replay protection employed by filtering packets according to their secuence number\&. By default the sequence window is disabled and therefore a window size of 0 is used\&. +Sometimes, packets arrive out of order on the receiver side\&. This option defines the size of a list of received packets\*(Aq sequence numbers\&. If, according to this list, a received packet has been previously received or has been transmitted in the past, and is therefore not in the list anymore, this is interpreted as a replay attack and the packet is dropped\&. A value of 0 deactivates this list and, as a consequence, the replay protection employed by filtering packets according to their secuence number\&. By default the sequence window is disabled and therefore a window size of 0 is used\&. .RE .PP \fB\-k, \-\-kd\(emprf \fR\fB\fI\fR\fR diff --git a/etc/init.d/anytun b/etc/init.d/anytun index 9fc4d4a..6905c67 100755 --- a/etc/init.d/anytun +++ b/etc/init.d/anytun @@ -1,8 +1,8 @@ #! /bin/sh ### BEGIN INIT INFO # Provides: anytun -# Required-Start: $network $named $syslog -# Required-Stop: +# Required-Start: $remote_fs $network $named $syslog +# Required-Stop: $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start anycast tunneling daemon at boot time diff --git a/src/anyrtpproxy/anyrtpproxy.cpp b/src/anyrtpproxy/anyrtpproxy.cpp index 7c5514c..1daf35b 100644 --- a/src/anyrtpproxy/anyrtpproxy.cpp +++ b/src/anyrtpproxy/anyrtpproxy.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -66,64 +66,62 @@ void listener(RtpSession::proto::socket* sock1, RtpSession::proto::socket* sock2 { cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") started"; - try - { - Buffer buf(u_int32_t(MAX_PACKET_SIZE)); + try { + Buffer buf(uint32_t(MAX_PACKET_SIZE)); RtpSession::proto::endpoint remote_end; while(1) { buf.setLength(MAX_PACKET_SIZE); - u_int32_t len=0; - if(dir == 1) - len = 0;//sock1->recvFromNonBlocking(buf.getBuf(), buf.getLength(), remote_end, 1000); - else if(dir == 2) - len = 0; //sock2->recvFromNonBlocking(buf.getBuf(), buf.getLength(), remote_end, 1000); - else break; + uint32_t len=0; + if(dir == 1) { + len = 0; //sock1->recvFromNonBlocking(buf.getBuf(), buf.getLength(), remote_end, 1000); + } else if(dir == 2) { + len = 0; //sock2->recvFromNonBlocking(buf.getBuf(), buf.getLength(), remote_end, 1000); + } else { break; } RtpSession& session = gRtpSessionTable.getSession(call_id); if(session.isDead()) { - cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") session is dead, exiting"; + cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") session is dead, exiting"; break; } - if(!len) + if(!len) { continue; + } buf.setLength(len); - - if((dir == 1 && remote_end != session.getRemoteEnd1()) || - (dir == 2 && remote_end != session.getRemoteEnd2())) - { + + if((dir == 1 && remote_end != session.getRemoteEnd1()) || + (dir == 2 && remote_end != session.getRemoteEnd2())) { if(gOpt.getNat() || - (!gOpt.getNoNatOnce() && ((dir == 1 && !session.getSeen1()) || - (dir == 2 && !session.getSeen2())))) - { + (!gOpt.getNoNatOnce() && ((dir == 1 && !session.getSeen1()) || + (dir == 2 && !session.getSeen2())))) { cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") setting remote host to " << remote_end; - if(dir == 1) + if(dir == 1) { session.setRemoteEnd1(remote_end); - if(dir == 2) + } + if(dir == 2) { session.setRemoteEnd2(remote_end); - + } + if(!gOpt.getNat()) { // with nat enabled sync is not needed SyncRtpCommand sc(call_id); queue->push(sc); } - } - else + } else { continue; - } + } + } session.setSeen1(); session.setSeen2(); - if(dir == 1) + if(dir == 1) { sock2->send_to(boost::asio::buffer(buf.getBuf(), buf.getLength()), session.getRemoteEnd2()); - else if(dir == 2) + } else if(dir == 2) { sock1->send_to(boost::asio::buffer(buf.getBuf(), buf.getLength()), session.getRemoteEnd1()); - else break; - } - } - catch(std::exception &e) - { + } else { break; } + } + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERR) << "listener(" << call_id << "/" << dir << ") exiting because: " << e.what(); } *running = false; @@ -150,21 +148,19 @@ void listenerManager(void* p) SyncQueue* queue_ = reinterpret_cast(p); std::map listenerMap; - while(1) - { - try - { + while(1) { + try { std::string call_id = gCallIdQueue.front(); // waits for semaphor and returns next call_id gCallIdQueue.pop(); RtpSession& session = gRtpSessionTable.getSession(call_id); - if(!session.isComplete()) + if(!session.isComplete()) { continue; + } std::map::iterator it; it = listenerMap.find(call_id); - if(it == listenerMap.end()) // listener Threads not existing yet - { + if(it == listenerMap.end()) { // listener Threads not existing yet ListenerData* ld = new ListenerData(); ld->sock1_.open(session.getLocalEnd1().protocol()); @@ -181,8 +177,7 @@ void listenerManager(void* p) continue; } - if(!it->second->running1_ && !it->second->running2_) - { + if(!it->second->running1_ && !it->second->running2_) { cLog.msg(Log::PRIO_NOTICE) << "listenerManager both threads for '" << call_id << "' exited, cleaning up"; if(it->second->thread1_) { it->second->thread1_->join(); @@ -197,10 +192,8 @@ void listenerManager(void* p) gRtpSessionTable.delSession(call_id); continue; } - // TODO: reinit if session changed - } - catch(std::exception &e) - { + // TODO: reinit if session changed + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERR) << "listenerManager restarting after exception: " << e.what(); usleep(500); // in case of an hard error don't block cpu (this is ugly) } @@ -210,33 +203,28 @@ void listenerManager(void* p) void chrootAndDrop(string const& chrootdir, string const& username) { - if (getuid() != 0) - { - std::cerr << "this program has to be run as root in order to run in a chroot" << std::endl; - exit(-1); - } - - struct passwd *pw = getpwnam(username.c_str()); - if(pw) { - if(chroot(chrootdir.c_str())) - { + if(getuid() != 0) { + std::cerr << "this program has to be run as root in order to run in a chroot" << std::endl; + exit(-1); + } + + struct passwd* pw = getpwnam(username.c_str()); + if(pw) { + if(chroot(chrootdir.c_str())) { std::cerr << "can't chroot to " << chrootdir << std::endl; exit(-1); - } + } std::cout << "we are in chroot jail (" << chrootdir << ") now" << std::endl; chdir("/"); - if (initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid)) - { - std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; - exit(-1); - } + if(initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid)) { + std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; + exit(-1); + } std::cout << "dropped user to " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; - } - else - { + } else { std::cerr << "unknown user " << username << std::endl; exit(-1); - } + } } void daemonize() @@ -244,65 +232,62 @@ void daemonize() pid_t pid; pid = fork(); - if(pid) exit(0); + if(pid) { exit(0); } setsid(); pid = fork(); - if(pid) exit(0); - -// std::cout << "running in background now..." << std::endl; + if(pid) { exit(0); } + + // std::cout << "running in background now..." << std::endl; int fd; -// for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors - for (fd=0;fd<=2;fd++) // close all file descriptors + // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors + for(fd=0; fd<=2; fd++) { // close all file descriptors close(fd); + } fd=open("/dev/null",O_RDWR); // stdin dup(fd); // stdout dup(fd); // stderr - umask(027); + umask(027); } class ThreadParam { public: - ThreadParam(SyncQueue & queue_,OptionConnectTo & connto_) + ThreadParam(SyncQueue& queue_,OptionConnectTo& connto_) : queue(queue_),connto(connto_) - {}; - SyncQueue & queue; - OptionConnectTo & connto; + {}; + SyncQueue& queue; + OptionConnectTo& connto; }; void syncConnector(void* p) { - ThreadParam* param = reinterpret_cast(p); + ThreadParam* param = reinterpret_cast(p); - SyncClient sc ( param->connto.host, param->connto.port); - sc.run(); + SyncClient sc(param->connto.host, param->connto.port); + sc.run(); } -void syncListener(SyncQueue * queue) +void syncListener(SyncQueue* queue) { - try - { + try { boost::asio::io_service io_service; - SyncTcpConnection::proto::resolver resolver(io_service); - SyncTcpConnection::proto::endpoint e; - if(gOpt.getLocalSyncAddr()!="") - { - SyncTcpConnection::proto::resolver::query query(gOpt.getLocalSyncAddr(), gOpt.getLocalSyncPort()); - e = *resolver.resolve(query); - } else { - SyncTcpConnection::proto::resolver::query query(gOpt.getLocalSyncPort()); - e = *resolver.resolve(query); - } + SyncTcpConnection::proto::resolver resolver(io_service); + SyncTcpConnection::proto::endpoint e; + if(gOpt.getLocalSyncAddr()!="") { + SyncTcpConnection::proto::resolver::query query(gOpt.getLocalSyncAddr(), gOpt.getLocalSyncPort()); + e = *resolver.resolve(query); + } else { + SyncTcpConnection::proto::resolver::query query(gOpt.getLocalSyncPort()); + e = *resolver.resolve(query); + } SyncServer server(io_service,e); - server.onConnect=boost::bind(syncOnConnect,_1); - queue->setSyncServerPtr(&server); + server.onConnect=boost::bind(syncOnConnect,_1); + queue->setSyncServerPtr(&server); io_service.run(); - } - catch (std::exception& e) - { + } catch(std::exception& e) { std::string addr = gOpt.getLocalSyncAddr() == "" ? "*" : gOpt.getLocalSyncAddr(); cLog.msg(Log::PRIO_ERR) << "sync: cannot bind to " << addr << ":" << gOpt.getLocalSyncPort() << " (" << e.what() << ")" << std::endl; @@ -312,9 +297,8 @@ void syncListener(SyncQueue * queue) int main(int argc, char* argv[]) { -// std::cout << "anyrtpproxy" << std::endl; - if(!gOpt.parse(argc, argv)) - { + // std::cout << "anyrtpproxy" << std::endl; + if(!gOpt.parse(argc, argv)) { gOpt.printUsage(); exit(-1); } @@ -330,17 +314,19 @@ int main(int argc, char* argv[]) } } - if(gOpt.getChroot()) + if(gOpt.getChroot()) { chrootAndDrop(gOpt.getChrootDir(), gOpt.getUsername()); - if(gOpt.getDaemonize()) + } + if(gOpt.getDaemonize()) { daemonize(); + } if(pidFile.is_open()) { pid_t pid = getpid(); pidFile << pid; pidFile.close(); } - + SignalController sig; sig.init(); @@ -350,38 +336,38 @@ int main(int argc, char* argv[]) boost::thread listenerManagerThread(boost::bind(listenerManager,&queue)); -// #ifndef ANYTUN_NOSYNC -// boost::thread * syncListenerThread; -// if(gOpt.getLocalSyncPort() != "") -// syncListenerThread = new boost::thread(boost::bind(syncListener,&queue)); - -// std::list connectThreads; -// for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it) { -// ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it); -// connectThreads.push_back(new boost::thread(boost::bind(syncConnector,point))); -// } -// #endif + // #ifndef ANYTUN_NOSYNC + // boost::thread * syncListenerThread; + // if(gOpt.getLocalSyncPort() != "") + // syncListenerThread = new boost::thread(boost::bind(syncListener,&queue)); + + // std::list connectThreads; + // for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it) { + // ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it); + // connectThreads.push_back(new boost::thread(boost::bind(syncConnector,point))); + // } + // #endif -// pthread_t syncListenerThread; + // pthread_t syncListenerThread; -// ConnectToList connect_to = gOpt.getConnectTo(); -// ThreadParam p( queue,*(new OptionConnectTo())); -// if ( gOpt.getLocalSyncPort()) -// pthread_create(&syncListenerThread, NULL, syncListener, &p); + // ConnectToList connect_to = gOpt.getConnectTo(); + // ThreadParam p( queue,*(new OptionConnectTo())); + // if ( gOpt.getLocalSyncPort()) + // pthread_create(&syncListenerThread, NULL, syncListener, &p); -// std::list connectThreads; -// for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it) -// { -// connectThreads.push_back(pthread_t()); -// ThreadParam * point = new ThreadParam(queue,*it); -// pthread_create(& connectThreads.back(), NULL, syncConnector, point); -// } + // std::list connectThreads; + // for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it) + // { + // connectThreads.push_back(pthread_t()); + // ThreadParam * point = new ThreadParam(queue,*it); + // pthread_create(& connectThreads.back(), NULL, syncConnector, point); + // } - PortWindow port_window(gOpt.getRtpStartPort(),gOpt.getRtpEndPort()); + PortWindow port_window(gOpt.getRtpStartPort(),gOpt.getRtpEndPort()); CommandHandler cmd(queue, gOpt.getControlInterface().addr_, gOpt.getControlInterface().port_,port_window); - + int ret = sig.run(); return ret; } diff --git a/src/anyrtpproxy/callIdQueue.cpp b/src/anyrtpproxy/callIdQueue.cpp index de48bab..514abf6 100644 --- a/src/anyrtpproxy/callIdQueue.cpp +++ b/src/anyrtpproxy/callIdQueue.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,9 +40,10 @@ CallIdQueue& CallIdQueue::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new CallIdQueue(); - + } + return *inst; } @@ -52,8 +53,9 @@ CallIdQueue::CallIdQueue() CallIdQueue::~CallIdQueue() { - while(!callids_.empty()) + while(!callids_.empty()) { pop(); + } } std::string& CallIdQueue::front() diff --git a/src/anyrtpproxy/callIdQueue.h b/src/anyrtpproxy/callIdQueue.h index 2cea155..4d6f7fc 100644 --- a/src/anyrtpproxy/callIdQueue.h +++ b/src/anyrtpproxy/callIdQueue.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -41,8 +41,8 @@ class CallIdQueue { public: - static CallIdQueue& instance(); - + static CallIdQueue& instance(); + std::string& front(); void push(std::string c); void pop(); @@ -51,15 +51,18 @@ private: CallIdQueue(); ~CallIdQueue(); - void operator=(const CallIdQueue &src); - CallIdQueue(const CallIdQueue &src); + void operator=(const CallIdQueue& src); + CallIdQueue(const CallIdQueue& src); static CallIdQueue* inst; static ::Mutex instMutex; - class instanceCleaner { - public: ~instanceCleaner() { - if(CallIdQueue::inst != 0) + class instanceCleaner + { + public: + ~instanceCleaner() { + if(CallIdQueue::inst != 0) { delete CallIdQueue::inst; + } } }; friend class instanceCleaner; diff --git a/src/anyrtpproxy/commandHandler.cpp b/src/anyrtpproxy/commandHandler.cpp index db0ca4d..a8f1df8 100644 --- a/src/anyrtpproxy/commandHandler.cpp +++ b/src/anyrtpproxy/commandHandler.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -50,23 +50,23 @@ #define MAX_COMMAND_LENGTH 1000 -CommandHandler::CommandHandler(SyncQueue& q, std::string lp,PortWindow & pw) : thread_(boost::bind(run,this)), - queue_(q), running_(true), control_sock_(io_service_), - local_address_(""), local_port_(lp),port_window_(pw) +CommandHandler::CommandHandler(SyncQueue& q, std::string lp,PortWindow& pw) : thread_(boost::bind(run,this)), + queue_(q), running_(true), control_sock_(io_service_), + local_address_(""), local_port_(lp),port_window_(pw) { proto::resolver resolver(io_service_); - proto::resolver::query query(local_port_); + proto::resolver::query query(local_port_); proto::endpoint e = *resolver.resolve(query); control_sock_.open(e.protocol()); control_sock_.bind(e); } -CommandHandler::CommandHandler(SyncQueue& q, string la, std::string lp, PortWindow & pw) : thread_(boost::bind(run,this)), - queue_(q), running_(true), control_sock_(io_service_), - local_address_(la), local_port_(lp),port_window_(pw) +CommandHandler::CommandHandler(SyncQueue& q, string la, std::string lp, PortWindow& pw) : thread_(boost::bind(run,this)), + queue_(q), running_(true), control_sock_(io_service_), + local_address_(la), local_port_(lp),port_window_(pw) { proto::resolver resolver(io_service_); - proto::resolver::query query(local_address_, local_port_); + proto::resolver::query query(local_address_, local_port_); proto::endpoint e = *resolver.resolve(query); control_sock_.open(e.protocol()); control_sock_.bind(e); @@ -76,14 +76,12 @@ void CommandHandler::run(void* s) { CommandHandler* self = reinterpret_cast(s); - Buffer buf(u_int32_t(MAX_COMMAND_LENGTH)); - try - { + Buffer buf(uint32_t(MAX_COMMAND_LENGTH)); + try { proto::endpoint remote_end; int len; - while(1) - { + while(1) { buf.setLength(MAX_COMMAND_LENGTH); len = self->control_sock_.receive_from(boost::asio::buffer(buf.getBuf(), buf.getLength()), remote_end); @@ -95,9 +93,7 @@ void CommandHandler::run(void* s) self->control_sock_.send_to(boost::asio::buffer(ret.c_str(), ret.length()), remote_end); } - } - catch(std::exception& e) - { + } catch(std::exception& e) { self->running_ = false; } self->running_ = false; @@ -133,8 +129,7 @@ std::string CommandHandler::handle(std::string command) params.push_back(tmp); } - switch(std::toupper(cmd[0])) - { + switch(std::toupper(cmd[0])) { case CMD_REQUEST: if(params.size() < 4) { oss << RET_ERR_SYNTAX; break; } oss << handleRequest(cmd.erase(0,1), params[0], params[1], params[2], params[3], (params.size() < 5) ? "" : params[4]); @@ -168,24 +163,21 @@ std::string CommandHandler::handle(std::string command) string CommandHandler::handleRequest(string modifiers, string call_id, string addr, string port, string from_tag, string to_tag) { - std::cout << "received request[" << modifiers << "] command ('" << call_id << "','" << addr << "','" << port + std::cout << "received request[" << modifiers << "] command ('" << call_id << "','" << addr << "','" << port << "','" << from_tag << "','" << to_tag << "')" << std::endl; - try - { + try { RtpSession::proto::resolver resolver(io_service_); bool is_new; RtpSession& session = gRtpSessionTable.getOrNewSession(call_id, is_new); - if(is_new) - { - u_int16_t port1 = port_window_.newPort(); // TODO: get next available port - u_int16_t port2 = port_window_.newPort(); // TODO: get next available port - if( !port1 || !port2) - { - if( port1) port_window_.freePort(port1); - if( port2) port_window_.freePort(port2); - throw std::runtime_error("no free port found"); - } + if(is_new) { + uint16_t port1 = port_window_.newPort(); // TODO: get next available port + uint16_t port2 = port_window_.newPort(); // TODO: get next available port + if(!port1 || !port2) { + if(port1) { port_window_.freePort(port1); } + if(port2) { port_window_.freePort(port2); } + throw std::runtime_error("no free port found"); + } std::stringstream ps1, ps2; ps1 << port1; ps2 << port2; @@ -196,8 +188,7 @@ string CommandHandler::handleRequest(string modifiers, string call_id, string ad e1 = *resolver.resolve(query1); RtpSession::proto::resolver::query query2(ps2.str()); e2 = *resolver.resolve(query2); - } - else { + } else { RtpSession::proto::resolver::query query1(gOpt.getLocalAddr(),ps1.str()); e1 = *resolver.resolve(query1); RtpSession::proto::resolver::query query2(gOpt.getLocalAddr(),ps2.str()); @@ -213,20 +204,17 @@ string CommandHandler::handleRequest(string modifiers, string call_id, string ad ostringstream oss; oss << session.getLocalEnd2().port(); return oss.str(); - } - catch(std::exception& e) - { + } catch(std::exception& e) { return RET_ERR_UNKNOWN; // TODO: change to corret error value } } string CommandHandler::handleResponse(string modifiers, string call_id, string addr, string port, string from_tag, string to_tag) { - std::cout << "received response[" << modifiers << "] command ('" << call_id << "','" << addr << "','" << port + std::cout << "received response[" << modifiers << "] command ('" << call_id << "','" << addr << "','" << port << "','" << from_tag << "','" << to_tag << "')" << std::endl; - try - { + try { RtpSession& session = gRtpSessionTable.getSession(call_id); RtpSession::proto::resolver resolver(io_service_); RtpSession::proto::resolver::query query(addr,port); @@ -238,9 +226,7 @@ string CommandHandler::handleResponse(string modifiers, string call_id, string a ostringstream oss; oss << session.getLocalEnd1().port(); return oss.str(); - } - catch(std::exception& e) - { + } catch(std::exception& e) { return RET_ERR_UNKNOWN; // TODO: change to corret error value } } @@ -249,39 +235,37 @@ string CommandHandler::handleDelete(string call_id, string from_tag, string to_t { std::cout << "received delete command ('" << call_id << "','" << from_tag << "','" << to_tag << "')" << std::endl; - try - { + try { RtpSession& session = gRtpSessionTable.getSession(call_id); session.isDead(true); SyncRtpCommand sc(call_id); queue_.push(sc); return RET_OK; - } - catch(std::exception& e) - { + } catch(std::exception& e) { return RET_ERR_UNKNOWN; // TODO: change to corret error value } } string CommandHandler::handleVersion() { - std::cout << "received version command" << std::endl; + std::cout << "received version command" << std::endl; return BASE_VERSION; } string CommandHandler::handleVersionF(string date_code) { - std::cout << "received version[F] command ('" << date_code << "')" << std::endl; - if(!date_code.compare(SUP_VERSION)) + std::cout << "received version[F] command ('" << date_code << "')" << std::endl; + if(!date_code.compare(SUP_VERSION)) { return "1"; - + } + return "0"; } string CommandHandler::handleInfo() { - std::cout << "received info command, ignoring" << std::endl; + std::cout << "received info command, ignoring" << std::endl; return RET_OK; } diff --git a/src/anyrtpproxy/commandHandler.h b/src/anyrtpproxy/commandHandler.h index 6634f14..954efc7 100644 --- a/src/anyrtpproxy/commandHandler.h +++ b/src/anyrtpproxy/commandHandler.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -46,31 +46,31 @@ class CommandHandler public: typedef boost::asio::ip::udp proto; - CommandHandler(SyncQueue& q, std::string lp, PortWindow &); - CommandHandler(SyncQueue& q, std::string la, std::string lp, PortWindow &); - + CommandHandler(SyncQueue& q, std::string lp, PortWindow&); + CommandHandler(SyncQueue& q, std::string la, std::string lp, PortWindow&); + bool isRunning(); - #define CMD_REQUEST 'U' - #define CMD_RESPONSE 'L' - #define CMD_DELETE 'D' - #define CMD_VERSION 'V' - #define CMD_INFO 'I' +#define CMD_REQUEST 'U' +#define CMD_RESPONSE 'L' +#define CMD_DELETE 'D' +#define CMD_VERSION 'V' +#define CMD_INFO 'I' - #define RET_OK "0" - #define RET_ERR_SYNTAX "E1" - #define RET_ERR_UNKNOWN "E2" +#define RET_OK "0" +#define RET_ERR_SYNTAX "E1" +#define RET_ERR_UNKNOWN "E2" - #define BASE_VERSION "20040107" - #define SUP_VERSION "20050322" +#define BASE_VERSION "20040107" +#define SUP_VERSION "20050322" private: - CommandHandler(const CommandHandler &c); - void operator=(const CommandHandler &c); + CommandHandler(const CommandHandler& c); + void operator=(const CommandHandler& c); static void run(void* s); std::string handle(std::string command); - + std::string handleRequest(std::string modifiers, std::string call_id, std::string addr, std::string port, std::string from_tag, std::string to_tag); std::string handleResponse(std::string modifiers, std::string call_id, std::string addr, std::string port, std::string from_tag, std::string to_tag); std::string handleDelete(std::string call_id, std::string from_tag, std::string to_tag); @@ -86,7 +86,7 @@ private: proto::socket control_sock_; std::string local_address_; std::string local_port_; - PortWindow& port_window_; + PortWindow& port_window_; }; diff --git a/src/anyrtpproxy/connectionList.cpp b/src/anyrtpproxy/connectionList.cpp index 4c274e8..afda1d8 100644 --- a/src/anyrtpproxy/connectionList.cpp +++ b/src/anyrtpproxy/connectionList.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -38,15 +38,15 @@ ConnectionList::ConnectionList() ConnectionList::~ConnectionList() { -} +} -void ConnectionList::addConnection(ConnectionParam &conn, u_int16_t mux ) +void ConnectionList::addConnection(ConnectionParam& conn, uint16_t mux) { } const ConnectionMap::iterator ConnectionList::getEnd() { - return connections_.end(); + return connections_.end(); } ConnectionMap::iterator ConnectionList::getBeginUnlocked() @@ -59,30 +59,30 @@ ConnectionMap::iterator ConnectionList::getEndUnlocked() return connections_.end(); } -const ConnectionMap::iterator ConnectionList::getConnection(u_int16_t mux) +const ConnectionMap::iterator ConnectionList::getConnection(uint16_t mux) { - Lock lock(mutex_); - ConnectionMap::iterator it = connections_.find(mux); - return it; + Lock lock(mutex_); + ConnectionMap::iterator it = connections_.find(mux); + return it; } -ConnectionParam & ConnectionList::getOrNewConnectionUnlocked(u_int16_t mux) +ConnectionParam& ConnectionList::getOrNewConnectionUnlocked(uint16_t mux) { - ConnectionMap::iterator it = connections_.find(mux); - return it->second; + ConnectionMap::iterator it = connections_.find(mux); + return it->second; } void ConnectionList::clear() { Lock lock(mutex_); - connections_.clear(); + connections_.clear(); } bool ConnectionList::empty() { Lock lock(mutex_); - return connections_.empty(); + return connections_.empty(); } Mutex& ConnectionList::getMutex() diff --git a/src/anyrtpproxy/connectionList.h b/src/anyrtpproxy/connectionList.h index a30f6d5..8df0781 100644 --- a/src/anyrtpproxy/connectionList.h +++ b/src/anyrtpproxy/connectionList.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -39,27 +39,27 @@ #include "../datatypes.h" #include "../connectionParam.h" #include "../networkAddress.h" -typedef std::map ConnectionMap; +typedef std::map ConnectionMap; class ConnectionList { public: - ConnectionList(); - ~ConnectionList(); - void addConnection(ConnectionParam &conn, u_int16_t mux); - const ConnectionMap::iterator getConnection(u_int16_t mux); - const ConnectionMap::iterator getEnd(); - ConnectionMap::iterator getEndUnlocked(); - ConnectionMap::iterator getBeginUnlocked(); - ConnectionParam & getOrNewConnectionUnlocked(u_int16_t mux); - bool empty(); - void clear(); + ConnectionList(); + ~ConnectionList(); + void addConnection(ConnectionParam& conn, uint16_t mux); + const ConnectionMap::iterator getConnection(uint16_t mux); + const ConnectionMap::iterator getEnd(); + ConnectionMap::iterator getEndUnlocked(); + ConnectionMap::iterator getBeginUnlocked(); + ConnectionParam& getOrNewConnectionUnlocked(uint16_t mux); + bool empty(); + void clear(); Mutex& getMutex(); private: - ConnectionList(const ConnectionList &s); - void operator=(const ConnectionList &s); - ConnectionMap connections_; + ConnectionList(const ConnectionList& s); + void operator=(const ConnectionList& s); + ConnectionMap connections_; Mutex mutex_; }; diff --git a/src/anyrtpproxy/options.cpp b/src/anyrtpproxy/options.cpp index e651770..218fd56 100644 --- a/src/anyrtpproxy/options.cpp +++ b/src/anyrtpproxy/options.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,9 +45,10 @@ Options& Options::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new Options(); - + } + return *inst; } @@ -56,34 +57,37 @@ void Host::splitAndSetAddrPort(std::string addr_port) if(addr_port.length() >= 2 && addr_port[0] == ':' && addr_port[1] != ':') { addr_ = ""; addr_port.erase(0,1); - std::stringstream tmp_stream(addr_port); + std::stringstream tmp_stream(addr_port); tmp_stream >> port_; return; } size_t pos = addr_port.find_first_of("["); - if(pos != std::string::npos && pos != 0) - return; // an [ was found but not at the beginning + if(pos != std::string::npos && pos != 0) { + return; // an [ was found but not at the beginning + } bool hasPort = false; if(pos != std::string::npos) { addr_port.erase(pos, 1); pos = addr_port.find_first_of("]"); - if(pos == std::string::npos) - return; // no trailing ] although an leading [ was found + if(pos == std::string::npos) { + return; // no trailing ] although an leading [ was found + } if(pos < addr_port.length()-2) { - if(addr_port[pos+1] != ':') - return; // wrong port delimieter + if(addr_port[pos+1] != ':') { + return; // wrong port delimieter + } addr_port[pos+1] = '/'; hasPort = true; + } else if(pos != addr_port.length()-1) { + return; // to few characters left } - else if(pos != addr_port.length()-1) - return; // to few characters left addr_port.erase(pos, 1); } @@ -92,12 +96,12 @@ void Host::splitAndSetAddrPort(std::string addr_port) std::stringstream tmp_stream(addr_port); getline(tmp_stream, addr_, '/'); - if(!tmp_stream.good()) + if(!tmp_stream.good()) { return; + } tmp_stream >> port_; - } - else { + } else { addr_ = addr_port; port_ = "2323"; // default sync port } @@ -114,11 +118,11 @@ Options::Options() : control_interface_("0.0.0.0", "22222") daemonize_ = true; pid_file_ = ""; local_addr_ = ""; - local_sync_port_ = ""; - rtp_start_port_ = 34000; - rtp_end_port_ = 35000; - no_nat_once_ = false; - nat_ = false; + local_sync_port_ = ""; + rtp_start_port_ = 34000; + rtp_end_port_ = 35000; + no_nat_once_ = false; + nat_ = false; } Options::~Options() @@ -205,13 +209,13 @@ bool Options::parse(int argc, char* argv[]) progname_ = argv[0]; std::queue host_port_queue; argc--; - for(int i=1; argc > 0; ++i) - { + for(int i=1; argc > 0; ++i) { std::string str(argv[i]); argc--; - if(str == "-h" || str == "--help") + if(str == "-h" || str == "--help") { return false; + } PARSE_BOOL_PARAM("-t","--chroot", chroot_) PARSE_BOOL_PARAM("-n","--nat", nat_) PARSE_BOOL_PARAM("-o","--no-nat-once", no_nat_once_) @@ -222,30 +226,31 @@ bool Options::parse(int argc, char* argv[]) PARSE_SCALAR_PARAM("-i","--interface", local_addr_) PARSE_STRING_PARAM("-s","--control", control_interface_) PARSE_SCALAR_PARAM2("-p","--port-range", rtp_start_port_, rtp_end_port_) - PARSE_CSLIST_PARAM("-M","--sync-hosts", host_port_queue) + PARSE_CSLIST_PARAM("-M","--sync-hosts", host_port_queue) PARSE_SCALAR_PARAM("-S","--sync-port", local_sync_port_) PARSE_SCALAR_PARAM("-I","--sync-interface", local_sync_addr_) - else + else { return false; + } } - while(!host_port_queue.empty()) - { + while(!host_port_queue.empty()) { std::stringstream tmp_stream(host_port_queue.front()); OptionConnectTo oct; getline(tmp_stream,oct.host,':'); - if(!tmp_stream.good()) + if(!tmp_stream.good()) { return false; + } tmp_stream >> oct.port; host_port_queue.pop(); connect_to_.push_back(oct); } - + return sanityCheck(); } bool Options::sanityCheck() { - if(control_interface_.port_ == "") control_interface_.port_ = "22222"; + if(control_interface_.port_ == "") { control_interface_.port_ = "22222"; } return true; } @@ -379,23 +384,23 @@ Options& Options::setLocalSyncPort(std::string l) return *this; } -u_int16_t Options::getRtpStartPort() +uint16_t Options::getRtpStartPort() { return rtp_start_port_; } -Options& Options::setRtpStartPort(u_int16_t l) +Options& Options::setRtpStartPort(uint16_t l) { rtp_start_port_ = l; return *this; } -u_int16_t Options::getRtpEndPort() +uint16_t Options::getRtpEndPort() { return rtp_end_port_; } -Options& Options::setRtpEndPort(u_int16_t l) +Options& Options::setRtpEndPort(uint16_t l) { rtp_end_port_ = l; return *this; diff --git a/src/anyrtpproxy/options.h b/src/anyrtpproxy/options.h index 679dace..cf32c87 100644 --- a/src/anyrtpproxy/options.h +++ b/src/anyrtpproxy/options.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -37,8 +37,7 @@ #include #include -typedef struct OptionConnectTo -{ +typedef struct OptionConnectTo { std::string host; std::string port; }; @@ -51,16 +50,15 @@ public: Host(std::string addr, std::string port) : addr_(addr), port_(port) {} Host(std::string addr_port) { splitAndSetAddrPort(addr_port); - } - std::string toString() const - { + } + std::string toString() const { std::ostringstream oss; oss << addr_ << ":" << port_; return oss.str(); } - + std::string addr_; - std::string port_; + std::string port_; protected: void splitAndSetAddrPort(std::string addr_port); @@ -89,28 +87,31 @@ public: std::string getLocalAddr(); Options& setLocalAddr(std::string l); std::string getLocalSyncAddr(); - Options& setLocalSyncAddr(std::string l); + Options& setLocalSyncAddr(std::string l); std::string getLocalSyncPort(); - Options& setLocalSyncPort(std::string l); - u_int16_t getRtpStartPort(); - Options& setRtpStartPort(u_int16_t l); - u_int16_t getRtpEndPort(); - Options& setRtpEndPort(u_int16_t l); + Options& setLocalSyncPort(std::string l); + uint16_t getRtpStartPort(); + Options& setRtpStartPort(uint16_t l); + uint16_t getRtpEndPort(); + Options& setRtpEndPort(uint16_t l); ConnectToList getConnectTo(); private: Options(); ~Options(); - Options(const Options &l); - void operator=(const Options &l); + Options(const Options& l); + void operator=(const Options& l); bool sanityCheck(); static Options* inst; static ::Mutex instMutex; - class instanceCleaner { - public: ~instanceCleaner() { - if(Options::inst != 0) + class instanceCleaner + { + public: + ~instanceCleaner() { + if(Options::inst != 0) { delete Options::inst; + } } }; friend class instanceCleaner; @@ -125,12 +126,12 @@ private: std::string chroot_dir_; std::string pid_file_; bool daemonize_; - std::string local_sync_addr_; - std::string local_sync_port_; + std::string local_sync_addr_; + std::string local_sync_port_; std::string local_addr_; - u_int16_t rtp_start_port_; - u_int16_t rtp_end_port_; - ConnectToList connect_to_; + uint16_t rtp_start_port_; + uint16_t rtp_end_port_; + ConnectToList connect_to_; Host control_interface_; }; diff --git a/src/anyrtpproxy/portWindow.cpp b/src/anyrtpproxy/portWindow.cpp index 3e07662..3ef1767 100644 --- a/src/anyrtpproxy/portWindow.cpp +++ b/src/anyrtpproxy/portWindow.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -32,7 +32,7 @@ #include "portWindow.h" -PortWindow::PortWindow(u_int16_t start, u_int16_t end) : start_port_(start), end_port_(end) +PortWindow::PortWindow(uint16_t start, uint16_t end) : start_port_(start), end_port_(end) { } @@ -46,37 +46,41 @@ PortWindow::PortSet::size_type PortWindow::getLength() return ports_.size(); } -bool PortWindow::hasPort(u_int16_t port) +bool PortWindow::hasPort(uint16_t port) { Lock lock(mutex_); PortSet::const_iterator it=ports_.find(port); - if(it == ports_.end()) + if(it == ports_.end()) { return false; + } return true; } -bool PortWindow::freePort(u_int16_t port) +bool PortWindow::freePort(uint16_t port) { Lock lock(mutex_); PortSet::iterator it=ports_.find(port); - if(it == ports_.end()) + if(it == ports_.end()) { return false; - ports_.erase(it); + } + ports_.erase(it); return true; } -u_int16_t PortWindow::newPort() +uint16_t PortWindow::newPort() { Lock lock(mutex_); - u_int16_t port= start_port_; - while (port=end_port_) - return 0; - ports_.insert(port); - return port; + uint16_t port= start_port_; + while(port=end_port_) { + return 0; + } + ports_.insert(port); + return port; } void PortWindow::clear() diff --git a/src/anyrtpproxy/portWindow.h b/src/anyrtpproxy/portWindow.h index b5a667f..d552ae1 100644 --- a/src/anyrtpproxy/portWindow.h +++ b/src/anyrtpproxy/portWindow.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,26 +40,26 @@ class PortWindow { public: - typedef std::set PortSet; + typedef std::set PortSet; - PortWindow(u_int16_t,u_int16_t); + PortWindow(uint16_t,uint16_t); ~PortWindow(); PortSet::size_type getLength(); - bool hasPort(u_int16_t); - bool freePort(u_int16_t); - u_int16_t newPort(); + bool hasPort(uint16_t); + bool freePort(uint16_t); + uint16_t newPort(); void clear(); private: - u_int16_t start_port_; - u_int16_t end_port_; + uint16_t start_port_; + uint16_t end_port_; ::Mutex mutex_; - PortSet ports_; + PortSet ports_; - PortWindow(const PortWindow &s); - void operator=(const PortWindow &s); + PortWindow(const PortWindow& s); + void operator=(const PortWindow& s); }; #endif diff --git a/src/anyrtpproxy/rtpSession.cpp b/src/anyrtpproxy/rtpSession.cpp index 93333ac..3afba33 100644 --- a/src/anyrtpproxy/rtpSession.cpp +++ b/src/anyrtpproxy/rtpSession.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -34,9 +34,9 @@ #include "callIdQueue.h" -RtpSession::RtpSession(const std::string& call_id) : in_sync_(false), call_id_(call_id) , dead_(false), complete_(false), - seen1_(false), seen2_(false) -{ +RtpSession::RtpSession(const std::string& call_id) : in_sync_(false), call_id_(call_id) , dead_(false), complete_(false), + seen1_(false), seen2_(false) +{ } void RtpSession::reinit() diff --git a/src/anyrtpproxy/rtpSession.h b/src/anyrtpproxy/rtpSession.h index cac5115..cfdd36c 100644 --- a/src/anyrtpproxy/rtpSession.h +++ b/src/anyrtpproxy/rtpSession.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,7 +45,7 @@ class RtpSession public: typedef boost::asio::ip::udp proto; - RtpSession(const std::string& call_id); + RtpSession(const std::string& call_id); bool isDead(); bool isDead(bool d); @@ -63,71 +63,71 @@ public: proto::endpoint getRemoteEnd2(); RtpSession& setRemoteEnd2(proto::endpoint e); - RtpSession& setSeen1(); + RtpSession& setSeen1(); bool getSeen1(); - RtpSession& setSeen2(); + RtpSession& setSeen2(); bool getSeen2(); private: - RtpSession(const RtpSession & src); - + RtpSession(const RtpSession& src); + void reinit(); //TODO: check if this is ok friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { + void serialize(Archive& ar, const unsigned int version) { Lock lock(mutex_); - // address of local_end1 and local_end2 are always equal - std::string local_addr(local_end1_.address().to_string()); - u_int16_t local_port1 = local_end1_.port(); - u_int16_t local_port2 = local_end2_.port(); - - std::string remote_addr1(remote_end1_.address().to_string()); - u_int16_t remote_port1 = remote_end1_.port(); - std::string remote_addr2(remote_end2_.address().to_string()); - u_int16_t remote_port2 = remote_end2_.port(); - - ar & dead_; - ar & complete_; - ar & local_addr; - ar & local_port1; - ar & local_port2; - ar & remote_addr1; - ar & remote_port1; - ar & remote_addr2; - ar & remote_port2; - ar & seen1_; - ar & seen2_; - - proto::endpoint local_end1(boost::asio::ip::address::from_string(local_addr), local_port1); + // address of local_end1 and local_end2 are always equal + std::string local_addr(local_end1_.address().to_string()); + uint16_t local_port1 = local_end1_.port(); + uint16_t local_port2 = local_end2_.port(); + + std::string remote_addr1(remote_end1_.address().to_string()); + uint16_t remote_port1 = remote_end1_.port(); + std::string remote_addr2(remote_end2_.address().to_string()); + uint16_t remote_port2 = remote_end2_.port(); + + ar& dead_; + ar& complete_; + ar& local_addr; + ar& local_port1; + ar& local_port2; + ar& remote_addr1; + ar& remote_port1; + ar& remote_addr2; + ar& remote_port2; + ar& seen1_; + ar& seen2_; + + proto::endpoint local_end1(boost::asio::ip::address::from_string(local_addr), local_port1); local_end1_ = local_end1; - proto::endpoint local_end2(boost::asio::ip::address::from_string(local_addr), local_port2); - local_end2_ = local_end2; + proto::endpoint local_end2(boost::asio::ip::address::from_string(local_addr), local_port2); + local_end2_ = local_end2; - proto::endpoint remote_end1(boost::asio::ip::address::from_string(remote_addr1), remote_port1); - remote_end1_ = remote_end1; - proto::endpoint remote_end2(boost::asio::ip::address::from_string(remote_addr2), remote_port2); - remote_end2_ = remote_end2; + proto::endpoint remote_end1(boost::asio::ip::address::from_string(remote_addr1), remote_port1); + remote_end1_ = remote_end1; + proto::endpoint remote_end2(boost::asio::ip::address::from_string(remote_addr2), remote_port2); + remote_end2_ = remote_end2; - if(complete_ && !dead_) + if(complete_ && !dead_) { reinit(); + } in_sync_ = true; - } + } bool in_sync_; - ::Mutex mutex_; + ::Mutex mutex_; const std::string& call_id_; bool dead_; bool complete_; proto::endpoint local_end1_, local_end2_; proto::endpoint remote_end1_, remote_end2_; - bool seen1_,seen2_; //has at least 1 packet been recieved? + bool seen1_,seen2_; //has at least 1 packet been recieved? }; diff --git a/src/anyrtpproxy/rtpSessionTable.cpp b/src/anyrtpproxy/rtpSessionTable.cpp index 934cf8c..de7b031 100644 --- a/src/anyrtpproxy/rtpSessionTable.cpp +++ b/src/anyrtpproxy/rtpSessionTable.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,8 +43,9 @@ RtpSessionTable& RtpSessionTable::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new RtpSessionTable(); + } return *inst; } @@ -55,31 +56,33 @@ RtpSessionTable::RtpSessionTable() RtpSessionTable::~RtpSessionTable() { -} +} -void RtpSessionTable::delSession(const std::string & call_id) +void RtpSessionTable::delSession(const std::string& call_id) { Lock lock(mutex_); RtpSessionMap::iterator it = map_.find(call_id); - if(it!=map_.end()) + if(it!=map_.end()) { delete it->second; + } map_.erase(it); } -RtpSession& RtpSessionTable::getOrNewSession(const std::string & call_id, bool& is_new) +RtpSession& RtpSessionTable::getOrNewSession(const std::string& call_id, bool& is_new) { Lock lock(mutex_); return getOrNewSessionUnlocked(call_id, is_new); } -RtpSession& RtpSessionTable::getOrNewSessionUnlocked(const std::string & call_id, bool& is_new) +RtpSession& RtpSessionTable::getOrNewSessionUnlocked(const std::string& call_id, bool& is_new) { is_new = false; RtpSessionMap::iterator it = map_.find(call_id); - if(it!=map_.end()) + if(it!=map_.end()) { return *(it->second); + } is_new = true; std::pair ret = map_.insert(RtpSessionMap::value_type(call_id, NULL)); @@ -87,11 +90,12 @@ RtpSession& RtpSessionTable::getOrNewSessionUnlocked(const std::string & call_id return *(ret.first->second); } -RtpSession& RtpSessionTable::getSession(const std::string & call_id) +RtpSession& RtpSessionTable::getSession(const std::string& call_id) { RtpSessionMap::iterator it = map_.find(call_id); - if(it!=map_.end()) + if(it!=map_.end()) { return *(it->second); + } throw std::runtime_error("session not found"); } @@ -109,13 +113,13 @@ RtpSessionMap::iterator RtpSessionTable::getEndUnlocked() void RtpSessionTable::clear() { Lock lock(mutex_); - map_.clear(); + map_.clear(); } bool RtpSessionTable::empty() { Lock lock(mutex_); - return map_.empty(); + return map_.empty(); } Mutex& RtpSessionTable::getMutex() diff --git a/src/anyrtpproxy/rtpSessionTable.h b/src/anyrtpproxy/rtpSessionTable.h index 49a062f..79be6cc 100644 --- a/src/anyrtpproxy/rtpSessionTable.h +++ b/src/anyrtpproxy/rtpSessionTable.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,31 +43,34 @@ typedef std::map RtpSessionMap; class RtpSessionTable { public: - static RtpSessionTable& instance(); - RtpSessionTable(); - ~RtpSessionTable(); - void delSession(const std::string & call_id); - bool empty(); - void clear(); + static RtpSessionTable& instance(); + RtpSessionTable(); + ~RtpSessionTable(); + void delSession(const std::string& call_id); + bool empty(); + void clear(); ::Mutex& getMutex(); - RtpSessionMap::iterator getBeginUnlocked(); - RtpSessionMap::iterator getEndUnlocked(); - RtpSession& getOrNewSession(const std::string & call_id, bool& isnew); - RtpSession& getOrNewSessionUnlocked(const std::string & call_id, bool& isnew); - RtpSession& getSession(const std::string & call_id); + RtpSessionMap::iterator getBeginUnlocked(); + RtpSessionMap::iterator getEndUnlocked(); + RtpSession& getOrNewSession(const std::string& call_id, bool& isnew); + RtpSession& getOrNewSessionUnlocked(const std::string& call_id, bool& isnew); + RtpSession& getSession(const std::string& call_id); private: static ::Mutex instMutex; - static RtpSessionTable* inst; - class instanceCleaner { - public: ~instanceCleaner() { - if(RtpSessionTable::inst != 0) - delete RtpSessionTable::inst; - } - }; - RtpSessionTable(const RtpSessionTable &s); - void operator=(const RtpSessionTable &s); - RtpSessionMap map_; + static RtpSessionTable* inst; + class instanceCleaner + { + public: + ~instanceCleaner() { + if(RtpSessionTable::inst != 0) { + delete RtpSessionTable::inst; + } + } + }; + RtpSessionTable(const RtpSessionTable& s); + void operator=(const RtpSessionTable& s); + RtpSessionMap map_; ::Mutex mutex_; }; diff --git a/src/anyrtpproxy/syncRtpCommand.cpp b/src/anyrtpproxy/syncRtpCommand.cpp index 10dfbf4..e1d5147 100644 --- a/src/anyrtpproxy/syncRtpCommand.cpp +++ b/src/anyrtpproxy/syncRtpCommand.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -32,16 +32,16 @@ #include "syncRtpCommand.h" SyncRtpCommand::SyncRtpCommand() -{ +{ } -SyncRtpCommand::SyncRtpCommand( const std::string & addr ) -:callid_(addr) -{ +SyncRtpCommand::SyncRtpCommand(const std::string& addr) + :callid_(addr) +{ } -std::string SyncRtpCommand::getCallId() const +std::string SyncRtpCommand::getCallId() const { - return callid_; + return callid_; } diff --git a/src/anyrtpproxy/syncRtpCommand.h b/src/anyrtpproxy/syncRtpCommand.h index 7b4c186..31b333c 100644 --- a/src/anyrtpproxy/syncRtpCommand.h +++ b/src/anyrtpproxy/syncRtpCommand.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,22 +40,21 @@ class SyncRtpCommand { public: - SyncRtpCommand(const std::string & ); - SyncRtpCommand(); - std::string getCallId() const; + SyncRtpCommand(const std::string&); + SyncRtpCommand(); + std::string getCallId() const; private: - SyncRtpCommand(const SyncRtpCommand &); - std::string callid_; + SyncRtpCommand(const SyncRtpCommand&); + std::string callid_; friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - Lock lock(gRtpSessionTable.getMutex()); - ar & callid_; + void serialize(Archive& ar, const unsigned int version) { + Lock lock(gRtpSessionTable.getMutex()); + ar& callid_; bool is_new; - ar & gRtpSessionTable.getOrNewSessionUnlocked(callid_, is_new); - }; + ar& gRtpSessionTable.getOrNewSessionUnlocked(callid_, is_new); + }; }; diff --git a/src/anytun-config.cpp b/src/anytun-config.cpp index d09f1e8..4f61353 100644 --- a/src/anytun-config.cpp +++ b/src/anytun-config.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -51,15 +51,15 @@ -void createConnection(const PacketSourceEndpoint & remote_end, ConnectionList & cl, u_int16_t seqSize, SyncQueue & queue, mux_t mux, Semaphore& sem) +void createConnection(const PacketSourceEndpoint& remote_end, ConnectionList& cl, uint16_t seqSize, SyncQueue& queue, mux_t mux, Semaphore& sem) { - SeqWindow * seq = new SeqWindow(seqSize); + SeqWindow* seq = new SeqWindow(seqSize); seq_nr_t seq_nr_ = 0; - KeyDerivation * kd = KeyDerivationFactory::create(gOpt.getKdPrf()); + KeyDerivation* kd = KeyDerivationFactory::create(gOpt.getKdPrf()); kd->init(gOpt.getKey(), gOpt.getSalt(), gOpt.getPassphrase()); kd->setRole(gOpt.getRole()); cLog.msg(Log::PRIO_NOTICE) << "added connection remote host " << remote_end; - ConnectionParam connparam ((*kd), (*seq), seq_nr_, remote_end); + ConnectionParam connparam((*kd), (*seq), seq_nr_, remote_end); cl.addConnection(connparam, mux); std::ostringstream sout; @@ -71,24 +71,23 @@ void createConnection(const PacketSourceEndpoint & remote_end, ConnectionList & NetworkList routes = gOpt.getRoutes(); NetworkList::const_iterator rit; - for(rit = routes.begin(); rit != routes.end(); ++rit) - { + for(rit = routes.begin(); rit != routes.end(); ++rit) { NetworkAddress addr(rit->net_addr.c_str()); NetworkPrefix prefix(addr, rit->prefix_length); - + gRoutingTable.addRoute(prefix, mux); - + std::ostringstream sout2; boost::archive::text_oarchive oa2(sout2); const SyncCommand scom2(prefix); - + oa2 << scom2; std::cout << std::setw(5) << std::setfill('0') << sout2.str().size()<< ' ' << sout2.str() << std::endl; - } + } sem.up(); } -void createConnectionResolver(PacketSourceResolverIt& it, ConnectionList & cl, u_int16_t seqSize, SyncQueue & queue, mux_t mux, Semaphore& sem) +void createConnectionResolver(PacketSourceResolverIt& it, ConnectionList& cl, uint16_t seqSize, SyncQueue& queue, mux_t mux, Semaphore& sem) { createConnection(*it, cl, seqSize, queue, mux, sem); } @@ -102,38 +101,37 @@ void createConnectionError(const std::exception& e, Semaphore& sem, int& ret) int main(int argc, char* argv[]) { - try - { - if(!gOpt.parse(argc, argv)) + try { + if(!gOpt.parse(argc, argv)) { exit(0); + } StringList targets = gOpt.getLogTargets(); - for(StringList::const_iterator it = targets.begin();it != targets.end(); ++it) + for(StringList::const_iterator it = targets.begin(); it != targets.end(); ++it) { cLog.addTarget(*it); - } - catch(syntax_error& e) - { + } + } catch(syntax_error& e) { std::cerr << e << std::endl; gOpt.printUsage(); exit(-1); } - gOpt.parse_post(); // print warnings + gOpt.parse_post(); // print warnings gResolver.init(); - ConnectionList cl; - SyncQueue queue; + ConnectionList cl; + SyncQueue queue; Semaphore sem; int ret = 0; - UDPPacketSource::proto::endpoint endpoint; - // allow emtpy endpoint!!! - gResolver.resolveUdp(gOpt.getRemoteAddr(), gOpt.getRemotePort(), - boost::bind(createConnectionResolver, _1, boost::ref(cl), gOpt.getSeqWindowSize(), boost::ref(queue), gOpt.getMux(), boost::ref(sem)), - boost::bind(createConnectionError, _1, boost::ref(sem), boost::ref(ret)), - gOpt.getResolvAddrType()); - sem.down(); + UDPPacketSource::proto::endpoint endpoint; + // allow emtpy endpoint!!! + gResolver.resolveUdp(gOpt.getRemoteAddr(), gOpt.getRemotePort(), + boost::bind(createConnectionResolver, _1, boost::ref(cl), gOpt.getSeqWindowSize(), boost::ref(queue), gOpt.getMux(), boost::ref(sem)), + boost::bind(createConnectionError, _1, boost::ref(sem), boost::ref(ret)), + gOpt.getResolvAddrType()); + sem.down(); return ret; } diff --git a/src/anytun-controld.cpp b/src/anytun-controld.cpp index 767db53..c4813ca 100644 --- a/src/anytun-controld.cpp +++ b/src/anytun-controld.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -51,26 +51,22 @@ std::list config_; -void syncOnConnect(SyncTcpConnection * connptr) +void syncOnConnect(SyncTcpConnection* connptr) { - for(std::list::const_iterator it=config_.begin(); it!=config_.end();++it) - { + for(std::list::const_iterator it=config_.begin(); it!=config_.end(); ++it) { connptr->Send(*it); } } void syncListener() { - boost::asio::io_service io_service; - try - { + boost::asio::io_service io_service; + try { SyncServer server(gOpt.getBindToAddr(), gOpt.getBindToPort(), boost::bind(syncOnConnect, _1)); server.run(); - } - catch(std::runtime_error& e) { + } catch(std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "sync listener thread died due to an uncaught runtime_error: " << e.what(); - } - catch(std::exception& e) { + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERROR) << "sync listener thread died due to an uncaught exception: " << e.what(); } } @@ -78,73 +74,70 @@ void syncListener() int main(int argc, char* argv[]) { DaemonService service; - try - { - try - { - if(!gOpt.parse(argc, argv)) + try { + try { + if(!gOpt.parse(argc, argv)) { exit(0); + } StringList targets = gOpt.getLogTargets(); - for(StringList::const_iterator it = targets.begin();it != targets.end(); ++it) + for(StringList::const_iterator it = targets.begin(); it != targets.end(); ++it) { cLog.addTarget(*it); - } - catch(syntax_error& e) - { + } + } catch(syntax_error& e) { std::cerr << e << std::endl; gOpt.printUsage(); exit(-1); } - - cLog.msg(Log::PRIO_NOTICE) << "anytun-controld started..."; + + cLog.msg(Log::PRIO_NOTICE) << "anytun-controld started..."; gOpt.parse_post(); // print warnings - std::ifstream file( gOpt.getFileName().c_str() ); - if( file.is_open() ) - { - std::string line; - while (!file.eof()) { - getline (file,line); + std::ifstream file(gOpt.getFileName().c_str()); + if(file.is_open()) { + std::string line; + while(!file.eof()) { + getline(file,line); config_.push_back(line); - } + } file.close(); } else { std::cout << "ERROR: unable to open file!" << std::endl; exit(-1); } - + service.initPrivs(gOpt.getUsername(), gOpt.getGroupname()); - if(gOpt.getDaemonize()) + if(gOpt.getDaemonize()) { service.daemonize(); + } - if(gOpt.getChrootDir() != "") + if(gOpt.getChrootDir() != "") { service.chroot(gOpt.getChrootDir()); + } service.dropPrivs(); gSignalController.init(service); gResolver.init(); - boost::thread * syncListenerThread; + boost::thread* syncListenerThread; syncListenerThread = new boost::thread(boost::bind(syncListener)); - + int ret = gSignalController.run(); - + return ret; - } - catch(std::runtime_error& e) - { - if(service.isDaemonized()) + } catch(std::runtime_error& e) { + if(service.isDaemonized()) { cLog.msg(Log::PRIO_ERROR) << "uncaught runtime error, exiting: " << e.what(); - else + } else { std::cout << "uncaught runtime error, exiting: " << e.what() << std::endl; - } - catch(std::exception& e) - { - if(service.isDaemonized()) + } + } catch(std::exception& e) { + if(service.isDaemonized()) { cLog.msg(Log::PRIO_ERROR) << "uncaught exception, exiting: " << e.what(); - else + } else { std::cout << "uncaught exception, exiting: " << e.what() << std::endl; + } } } diff --git a/src/anytun-showtables.cpp b/src/anytun-showtables.cpp index ff851c9..7e1e6ae 100644 --- a/src/anytun-showtables.cpp +++ b/src/anytun-showtables.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -51,86 +51,78 @@ void output() { - ConnectionList &cl(gConnectionList); - if( !cl.empty() ) - { - ConnectionMap::iterator it = cl.getBeginUnlocked(); - mux_t mux = it->first; - ConnectionParam &conn( it->second ); - std::cout << "Client " << mux << ": " ; - if( conn.remote_end_==PacketSourceEndpoint()) - { - std::cout<< "not registered"; - } else { - std::cout<< conn.remote_end_; - } - std::cout << std::endl; + ConnectionList& cl(gConnectionList); + if(!cl.empty()) { + ConnectionMap::iterator it = cl.getBeginUnlocked(); + mux_t mux = it->first; + ConnectionParam& conn(it->second); + std::cout << "Client " << mux << ": " ; + if(conn.remote_end_==PacketSourceEndpoint()) { + std::cout<< "not registered"; + } else { + std::cout<< conn.remote_end_; + } + std::cout << std::endl; //std::cout << "Connection: Keyderivation-Type: " << conn.kd_.printType() << std::endl; cl.clear(); - } else { - network_address_type_t types[] = {ipv4,ipv6,ethernet}; - for (int types_idx=0; types_idx<3; types_idx++) - { - network_address_type_t type = types[types_idx]; - if( !gRoutingTable.empty(type) ) - { - RoutingMap::iterator it = gRoutingTable.getBeginUnlocked(type); - NetworkPrefix pref( it->first ); - std::cout << "Route: " << pref.toString() << "/" << (int)pref.getNetworkPrefixLength() << " -> "; - mux_t mux = it->second; - std::cout << mux << std::endl; - gRoutingTable.clear(type); - } - } - } + } else { + network_address_type_t types[] = {ipv4,ipv6,ethernet}; + for(int types_idx=0; types_idx<3; types_idx++) { + network_address_type_t type = types[types_idx]; + if(!gRoutingTable.empty(type)) { + RoutingMap::iterator it = gRoutingTable.getBeginUnlocked(type); + NetworkPrefix pref(it->first); + std::cout << "Route: " << pref.toString() << "/" << (int)pref.getNetworkPrefixLength() << " -> "; + mux_t mux = it->second; + std::cout << mux << std::endl; + gRoutingTable.clear(type); + } + } + } } -void readExactly(size_t toread, std::iostream & result) +void readExactly(size_t toread, std::iostream& result) { size_t hasread = 0; - while (toread > hasread && std::cin.good()) - { - char a[1]; - std::cin.read(a,1); - result.write(a,1); - hasread++; + while(toread > hasread && std::cin.good()) { + char a[1]; + std::cin.read(a,1); + result.write(a,1); + hasread++; } } void readAndProcessOne() { size_t message_lenght ; - std::stringstream message_lenght_stream; - readExactly(5,message_lenght_stream); - message_lenght_stream >> message_lenght; - std::stringstream void_stream; - readExactly(1,void_stream); //skip space - if (!message_lenght) - return; - std::stringstream sync_command_stream; - readExactly(message_lenght, sync_command_stream); - //std::cout << message_lenght << std::endl; - //std::cout << sync_command_stream.str()<< std::endl; - boost::archive::text_iarchive ia(sync_command_stream); - SyncCommand scom(gConnectionList); - ia >> scom; + std::stringstream message_lenght_stream; + readExactly(5,message_lenght_stream); + message_lenght_stream >> message_lenght; + std::stringstream void_stream; + readExactly(1,void_stream); //skip space + if(!message_lenght) { + return; + } + std::stringstream sync_command_stream; + readExactly(message_lenght, sync_command_stream); + //std::cout << message_lenght << std::endl; + //std::cout << sync_command_stream.str()<< std::endl; + boost::archive::text_iarchive ia(sync_command_stream); + SyncCommand scom(gConnectionList); + ia >> scom; } int main(int argc, char* argv[]) { int ret = 0; - while( std::cin.good() ) - { - try - { - readAndProcessOne(); - } - catch(std::exception& e) - { - std::cout << "uncaught exception, exiting: " << e.what() << std::endl; - } - output(); + while(std::cin.good()) { + try { + readAndProcessOne(); + } catch(std::exception& e) { + std::cout << "uncaught exception, exiting: " << e.what() << std::endl; + } + output(); } return ret; } diff --git a/src/anytun.cpp b/src/anytun.cpp index 1ac9397..d125ee9 100644 --- a/src/anytun.cpp +++ b/src/anytun.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -84,18 +84,18 @@ bool disableRouting = false; void createConnection(const PacketSourceEndpoint& remote_end, window_size_t seqSize, mux_t mux) { - SeqWindow* seq = new SeqWindow(seqSize); - seq_nr_t seq_nr_=0; - KeyDerivation * kd = KeyDerivationFactory::create(gOpt.getKdPrf()); + SeqWindow* seq = new SeqWindow(seqSize); + seq_nr_t seq_nr_=0; + KeyDerivation* kd = KeyDerivationFactory::create(gOpt.getKdPrf()); kd->init(gOpt.getKey(), gOpt.getSalt(), gOpt.getPassphrase()); kd->setRole(gOpt.getRole()); cLog.msg(Log::PRIO_NOTICE) << "added connection remote host " << remote_end; - ConnectionParam connparam ((*kd), (*seq), seq_nr_, remote_end); - gConnectionList.addConnection(connparam,mux); + ConnectionParam connparam((*kd), (*seq), seq_nr_, remote_end); + gConnectionList.addConnection(connparam,mux); #ifndef ANYTUN_NOSYNC - SyncCommand sc (gConnectionList,mux); - gSyncQueue.push(sc); + SyncCommand sc(gConnectionList,mux); + gSyncQueue.push(sc); #endif } @@ -118,16 +118,13 @@ void syncConnector(const OptionHost& connto) void syncListener() { - try - { + try { SyncServer server(gOpt.getLocalSyncAddr(), gOpt.getLocalSyncPort(), boost::bind(syncOnConnect, _1)); gSyncQueue.setSyncServerPtr(&server); server.run(); - } - catch(std::runtime_error& e) { + } catch(std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "sync listener thread died due to an uncaught runtime_error: " << e.what(); - } - catch(std::exception& e) { + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERROR) << "sync listener thread died due to an uncaught exception: " << e.what(); } } @@ -136,88 +133,91 @@ void syncListener() void sender(TunDevice* dev, PacketSource* src) { if(!dev || !src) { - cLog.msg(Log::PRIO_ERROR) << "sender thread died because either dev or src pointer is null"; + cLog.msg(Log::PRIO_ERROR) << "sender thread died because either dev or src pointer is null"; return; } - try - { + try { std::auto_ptr c(CipherFactory::create(gOpt.getCipher(), KD_OUTBOUND)); - std::auto_ptr a(AuthAlgoFactory::create(gOpt.getAuthAlgo(), KD_OUTBOUND) ); - + std::auto_ptr a(AuthAlgoFactory::create(gOpt.getAuthAlgo(), KD_OUTBOUND)); + PlainPacket plain_packet(MAX_PACKET_LENGTH); EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH, gOpt.getAuthTagLength()); - - u_int16_t mux = gOpt.getMux(); + + uint16_t mux = gOpt.getMux(); PacketSourceEndpoint emptyEndpoint; while(1) { plain_packet.setLength(MAX_PACKET_LENGTH); encrypted_packet.withAuthTag(false); encrypted_packet.setLength(MAX_PACKET_LENGTH); - - // read packet from device + + // read packet from device int len = dev->read(plain_packet.getPayload(), plain_packet.getPayloadLength()); - if(len < 0) - continue; // silently ignore device read errors, this is probably no good idea... + if(len < 0) { + continue; // silently ignore device read errors, this is probably no good idea... + } - if(static_cast(len) < PlainPacket::getHeaderLength()) - continue; // ignore short packets + if(static_cast(len) < PlainPacket::getHeaderLength()) { + continue; // ignore short packets + } plain_packet.setPayloadLength(len); - // set payload type - if(dev->getType() == TYPE_TUN) + // set payload type + if(dev->getType() == TYPE_TUN) { plain_packet.setPayloadType(PAYLOAD_TYPE_TUN); - else if(dev->getType() == TYPE_TAP) + } else if(dev->getType() == TYPE_TAP) { plain_packet.setPayloadType(PAYLOAD_TYPE_TAP); - else + } else { plain_packet.setPayloadType(0); - - if(gConnectionList.empty()) + } + + if(gConnectionList.empty()) { continue; - //std::cout << "got Packet for plain "< "< "<second; - + if(cit==gConnectionList.getEnd()) { + continue; //no connection + } + ConnectionParam& conn = cit->second; + if(conn.remote_end_ == emptyEndpoint) { //cLog.msg(Log::PRIO_INFO) << "no remote address set"; continue; } - // encrypt packet + // encrypt packet c->encrypt(conn.kd_, plain_packet, encrypted_packet, conn.seq_nr_, gOpt.getSenderId(), mux); - + encrypted_packet.setHeader(conn.seq_nr_, gOpt.getSenderId(), mux); conn.seq_nr_++; - - // add authentication tag + + // add authentication tag a->generate(conn.kd_, encrypted_packet); try { src->send(encrypted_packet.getBuf(), encrypted_packet.getLength(), conn.remote_end_); - } catch (std::exception& /*e*/) { - //TODO: do something here - //cLog.msg(Log::PRIO_ERROR) << "could not send data: " << e.what(); - } + } catch(std::exception& /*e*/) { + //TODO: do something here + //cLog.msg(Log::PRIO_ERROR) << "could not send data: " << e.what(); + } } - } - catch(std::runtime_error& e) { + } catch(std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "sender thread died due to an uncaught runtime_error: " << e.what(); - } - catch(std::exception& e) { + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERROR) << "sender thread died due to an uncaught exception: " << e.what(); } } @@ -225,98 +225,100 @@ void sender(TunDevice* dev, PacketSource* src) void receiver(TunDevice* dev, PacketSource* src) { if(!dev || !src) { - cLog.msg(Log::PRIO_ERROR) << "receiver thread died because either dev or src pointer is null"; + cLog.msg(Log::PRIO_ERROR) << "receiver thread died because either dev or src pointer is null"; return; } - try - { + try { std::auto_ptr c(CipherFactory::create(gOpt.getCipher(), KD_INBOUND)); std::auto_ptr a(AuthAlgoFactory::create(gOpt.getAuthAlgo(), KD_INBOUND)); - - u_int32_t auth_tag_length = gOpt.getAuthTagLength(); + + uint32_t auth_tag_length = gOpt.getAuthTagLength(); EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH, auth_tag_length); PlainPacket plain_packet(MAX_PACKET_LENGTH); - + while(1) { PacketSourceEndpoint remote_end; plain_packet.setLength(MAX_PACKET_LENGTH); encrypted_packet.withAuthTag(false); encrypted_packet.setLength(MAX_PACKET_LENGTH); - - // read packet from socket + + // read packet from socket int len; try { len = src->recv(encrypted_packet.getBuf(), encrypted_packet.getLength(), remote_end); - } catch (std::exception& /*e*/) { - //TODO: do something here - //cLog.msg(Log::PRIO_ERROR) << "could not recive packet "<< e.what(); - continue; - } - if(len < 0) - continue; // silently ignore socket recv errors, this is probably no good idea... - - if(static_cast(len) < (EncryptedPacket::getHeaderLength() + auth_tag_length)) - continue; // ignore short packets + } catch(std::exception& /*e*/) { + //TODO: do something here + //cLog.msg(Log::PRIO_ERROR) << "could not recive packet "<< e.what(); + continue; + } + if(len < 0) { + continue; // silently ignore socket recv errors, this is probably no good idea... + } + + if(static_cast(len) < (EncryptedPacket::getHeaderLength() + auth_tag_length)) { + continue; // ignore short packets + } encrypted_packet.setLength(len); - + mux_t mux = encrypted_packet.getMux(); - // autodetect peer - if( gConnectionList.empty() && gOpt.getRemoteAddr() == "") { + // autodetect peer + if(gConnectionList.empty() && gOpt.getRemoteAddr() == "") { cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_end; createConnection(remote_end, gOpt.getSeqWindowSize(),mux); } - + ConnectionMap::iterator cit = gConnectionList.getConnection(mux); - if (cit == gConnectionList.getEnd()) + if(cit == gConnectionList.getEnd()) { continue; - ConnectionParam & conn = cit->second; - - // check whether auth tag is ok or not + } + ConnectionParam& conn = cit->second; + + // check whether auth tag is ok or not if(!a->checkTag(conn.kd_, encrypted_packet)) { cLog.msg(Log::PRIO_NOTICE) << "wrong Authentication Tag!"; continue; - } + } - // Replay Protection + // Replay Protection if(conn.seq_window_.checkAndAdd(encrypted_packet.getSenderId(), encrypted_packet.getSeqNr())) { - cLog.msg(Log::PRIO_NOTICE) << "Replay attack from " << conn.remote_end_ + cLog.msg(Log::PRIO_NOTICE) << "Replay attack from " << conn.remote_end_ << " seq:"<< encrypted_packet.getSeqNr() << " sid: "<< encrypted_packet.getSenderId(); continue; } - - //Allow dynamic IP changes - //TODO: add command line option to turn this off - if (remote_end != conn.remote_end_) { + + //Allow dynamic IP changes + //TODO: add command line option to turn this off + if(remote_end != conn.remote_end_) { cLog.msg(Log::PRIO_NOTICE) << "connection "<< mux << " autodetected remote host ip changed " << remote_end; conn.remote_end_=remote_end; #ifndef ANYTUN_NOSYNC - SyncCommand sc (gConnectionList,mux); + SyncCommand sc(gConnectionList,mux); gSyncQueue.push(sc); #endif - } - // ignore zero length packets - if(encrypted_packet.getPayloadLength() <= PlainPacket::getHeaderLength()) + } + // ignore zero length packets + if(encrypted_packet.getPayloadLength() <= PlainPacket::getHeaderLength()) { continue; + } - // decrypt packet + // decrypt packet c->decrypt(conn.kd_, encrypted_packet, plain_packet); - - // check payload_type - if((dev->getType() == TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN4 && - plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN6) || - (dev->getType() == TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP)) + + // check payload_type + if((dev->getType() == TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN4 && + plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN6) || + (dev->getType() == TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP)) { continue; - - // write it on the device + } + + // write it on the device dev->write(plain_packet.getPayload(), plain_packet.getLength()); } - } - catch(std::runtime_error& e) { + } catch(std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "receiver thread died due to an uncaught runtime_error: " << e.what(); - } - catch(std::exception& e) { + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERROR) << "receiver thread died due to an uncaught exception: " << e.what(); } } @@ -324,9 +326,9 @@ void receiver(TunDevice* dev, PacketSource* src) void startSendRecvThreads(TunDevice* dev, PacketSource* src) { src->waitUntilReady(); - + boost::thread(boost::bind(sender, dev, src)); - boost::thread(boost::bind(receiver, dev, src)); + boost::thread(boost::bind(receiver, dev, src)); } @@ -336,23 +338,18 @@ int main(int argc, char* argv[]) try { if(argc > 1) { if(std::string(argv[1]) == "install") { - WinService::install(); + WinService::install(); return 0; - } - else if(std::string(argv[1]) == "uninstall") { - WinService::uninstall(); + } else if(std::string(argv[1]) == "uninstall") { + WinService::uninstall(); return 0; } } WinService::start(); return 0; - } - catch(std::runtime_error& e) - { + } catch(std::runtime_error& e) { std::cout << "caught runtime error, exiting: " << e.what() << std::endl; - } - catch(std::exception& e) - { + } catch(std::exception& e) { std::cout << "caught exception, exiting: " << e.what() << std::endl; } } @@ -363,20 +360,18 @@ int real_main(int argc, char* argv[], WinService& service) int main(int argc, char* argv[]) { DaemonService service; -#endif - try - { - try - { - if(!gOpt.parse(argc, argv)) +#endif + try { + try { + if(!gOpt.parse(argc, argv)) { exit(0); + } StringList targets = gOpt.getLogTargets(); - for(StringList::const_iterator it = targets.begin();it != targets.end(); ++it) + for(StringList::const_iterator it = targets.begin(); it != targets.end(); ++it) { cLog.addTarget(*it); - } - catch(syntax_error& e) - { + } + } catch(syntax_error& e) { std::cerr << e << std::endl; gOpt.printUsage(); exit(-1); @@ -385,17 +380,18 @@ int main(int argc, char* argv[]) cLog.msg(Log::PRIO_NOTICE) << "anytun started..."; gOpt.parse_post(); // print warnings - // daemonizing has to done before any thread gets started + // daemonizing has to done before any thread gets started service.initPrivs(gOpt.getUsername(), gOpt.getGroupname()); - if(gOpt.getDaemonize()) + if(gOpt.getDaemonize()) { service.daemonize(); + } OptionNetwork net = gOpt.getIfconfigParam(); TunDevice dev(gOpt.getDevName(), gOpt.getDevType(), net.net_addr, net.prefix_length); cLog.msg(Log::PRIO_NOTICE) << "dev opened - name '" << dev.getActualName() << "', node '" << dev.getActualNode() << "'"; cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << dev.getTypeString() << "'"; - SysExec * postup_script = NULL; + SysExec* postup_script = NULL; if(gOpt.getPostUpScript() != "") { cLog.msg(Log::PRIO_NOTICE) << "executing post-up script '" << gOpt.getPostUpScript() << "'"; StringVector args = boost::assign::list_of(dev.getActualName())(dev.getActualNode()); @@ -405,8 +401,7 @@ int main(int argc, char* argv[]) if(gOpt.getChrootDir() != "") { try { service.chroot(gOpt.getChrootDir()); - } - catch(const std::runtime_error& e) { + } catch(const std::runtime_error& e) { cLog.msg(Log::PRIO_WARNING) << "ignoring chroot error: " << e.what(); } } @@ -416,68 +411,70 @@ int main(int argc, char* argv[]) gSignalController.init(service); gResolver.init(); boost::thread(boost::bind(&TunDevice::waitUntilReady,&dev)); - if (postup_script) + if(postup_script) { boost::thread(boost::bind(&SysExec::waitAndDestroy,postup_script)); + } + + initCrypto(); - initCrypto(); - PacketSource* src = new UDPPacketSource(gOpt.getLocalAddr(), gOpt.getLocalPort()); - if(gOpt.getRemoteAddr() != "") + if(gOpt.getRemoteAddr() != "") { gResolver.resolveUdp(gOpt.getRemoteAddr(), gOpt.getRemotePort(), boost::bind(createConnectionResolver, _1, gOpt.getSeqWindowSize(), gOpt.getMux()), boost::bind(createConnectionError, _1), gOpt.getResolvAddrType()); + } HostList connect_to = gOpt.getRemoteSyncHosts(); #ifndef NO_ROUTING NetworkList routes = gOpt.getRoutes(); - NetworkList::const_iterator rit; - for(rit = routes.begin(); rit != routes.end(); ++rit) { - NetworkAddress addr( rit->net_addr ); - NetworkPrefix prefix( addr, static_cast(rit->prefix_length)); - gRoutingTable.addRoute( prefix, gOpt.getMux() ); - } - if (connect_to.begin() == connect_to.end() || gOpt.getDevType()!="tun") { - cLog.msg(Log::PRIO_NOTICE) << "No sync/control host defined or not a tun device. Disabling multi connection support (routing)"; - disableRouting=true; - } + NetworkList::const_iterator rit; + for(rit = routes.begin(); rit != routes.end(); ++rit) { + NetworkAddress addr(rit->net_addr); + NetworkPrefix prefix(addr, static_cast(rit->prefix_length)); + gRoutingTable.addRoute(prefix, gOpt.getMux()); + } + if(connect_to.begin() == connect_to.end() || gOpt.getDevType()!="tun") { + cLog.msg(Log::PRIO_NOTICE) << "No sync/control host defined or not a tun device. Disabling multi connection support (routing)"; + disableRouting=true; + } #endif #ifndef ANYTUN_NOSYNC boost::thread* syncListenerThread = NULL; - if(gOpt.getLocalSyncPort() != "") + if(gOpt.getLocalSyncPort() != "") { syncListenerThread = new boost::thread(boost::bind(syncListener)); - + } + boost::thread_group connectThreads; - for(HostList::const_iterator it = connect_to.begin() ;it != connect_to.end(); ++it) + for(HostList::const_iterator it = connect_to.begin() ; it != connect_to.end(); ++it) { connectThreads.create_thread(boost::bind(syncConnector, *it)); + } #endif // wait for packet source to finish in a seperate thread in order // to be still able to process signals while waiting boost::thread(boost::bind(startSendRecvThreads, &dev, src)); - int ret = gSignalController.run(); + int ret = gSignalController.run(); -// TODO: stop all threads and cleanup -// -// if(src) -// delete src; -// if(connTo) -// delete connTo; - return ret; - } - catch(std::runtime_error& e) - { + // TODO: stop all threads and cleanup + // + // if(src) + // delete src; + // if(connTo) + // delete connTo; + return ret; + } catch(std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "uncaught runtime error, exiting: " << e.what(); - if(!service.isDaemonized()) + if(!service.isDaemonized()) { std::cout << "uncaught runtime error, exiting: " << e.what() << std::endl; - } - catch(std::exception& e) - { + } + } catch(std::exception& e) { cLog.msg(Log::PRIO_ERROR) << "uncaught exception, exiting: " << e.what(); - if(!service.isDaemonized()) + if(!service.isDaemonized()) { std::cout << "uncaught exception, exiting: " << e.what() << std::endl; + } } return -1; } - - + + diff --git a/src/anytunError.cpp b/src/anytunError.cpp index 60bf8eb..20595b3 100644 --- a/src/anytunError.cpp +++ b/src/anytunError.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/anytunError.h b/src/anytunError.h index d500545..616450c 100644 --- a/src/anytunError.h +++ b/src/anytunError.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -61,7 +61,7 @@ public: }; std::ostream& operator<<(std::ostream& stream, AnytunErrno const& value); -class ErrorStringBuilder +class ErrorStringBuilder { public: ErrorStringBuilder(ErrorStringBuilder const& src) { stream << src.stream.str(); }; diff --git a/src/authAlgo.cpp b/src/authAlgo.cpp index f9228c6..8317e9e 100644 --- a/src/authAlgo.cpp +++ b/src/authAlgo.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -59,7 +59,7 @@ Sha1AuthAlgo::Sha1AuthAlgo(kd_dir_t d) : AuthAlgo(d), key_(DIGEST_LENGTH) if(err) { cLog.msg(Log::PRIO_ERROR) << "Sha1AuthAlgo::Sha1AuthAlgo: Failed to open message digest algo"; return; - } + } #else HMAC_CTX_init(&ctx_); HMAC_Init_ex(&ctx_, NULL, 0, EVP_sha1(), NULL); @@ -69,49 +69,53 @@ Sha1AuthAlgo::Sha1AuthAlgo(kd_dir_t d) : AuthAlgo(d), key_(DIGEST_LENGTH) Sha1AuthAlgo::~Sha1AuthAlgo() { #ifndef USE_SSL_CRYPTO - if(handle_) + if(handle_) { gcry_md_close(handle_); + } #else HMAC_CTX_cleanup(&ctx_); -#endif +#endif } void Sha1AuthAlgo::generate(KeyDerivation& kd, EncryptedPacket& packet) { #ifndef USE_SSL_CRYPTO - if(!handle_) + if(!handle_) { return; + } #endif packet.addAuthTag(); - if(!packet.getAuthTagLength()) + if(!packet.getAuthTagLength()) { return; - + } + kd.generate(dir_, LABEL_AUTH, packet.getSeqNr(), key_); #ifndef USE_SSL_CRYPTO gcry_error_t err = gcry_md_setkey(handle_, key_.getBuf(), key_.getLength()); if(err) { cLog.msg(Log::PRIO_ERROR) << "Sha1AuthAlgo::setKey: Failed to set hmac key: " << AnytunGpgError(err); return; - } + } gcry_md_reset(handle_); gcry_md_write(handle_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); gcry_md_final(handle_); - u_int8_t* hmac = gcry_md_read(handle_, 0); + uint8_t* hmac = gcry_md_read(handle_, 0); #else HMAC_Init_ex(&ctx_, key_.getBuf(), key_.getLength(), EVP_sha1(), NULL); - u_int8_t hmac[DIGEST_LENGTH]; + uint8_t hmac[DIGEST_LENGTH]; HMAC_Update(&ctx_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); HMAC_Final(&ctx_, hmac, NULL); #endif - u_int8_t* tag = packet.getAuthTag(); - u_int32_t length = (packet.getAuthTagLength() < DIGEST_LENGTH) ? packet.getAuthTagLength() : DIGEST_LENGTH; + uint8_t* tag = packet.getAuthTag(); + uint32_t length = (packet.getAuthTagLength() < DIGEST_LENGTH) ? packet.getAuthTagLength() : DIGEST_LENGTH; - if(length > DIGEST_LENGTH) + if(length > DIGEST_LENGTH) { std::memset(tag, 0, packet.getAuthTagLength()); + } std::memcpy(&tag[packet.getAuthTagLength() - length], &hmac[DIGEST_LENGTH - length], length); } @@ -119,13 +123,15 @@ void Sha1AuthAlgo::generate(KeyDerivation& kd, EncryptedPacket& packet) bool Sha1AuthAlgo::checkTag(KeyDerivation& kd, EncryptedPacket& packet) { #ifndef USE_SSL_CRYPTO - if(!handle_) + if(!handle_) { return false; + } #endif packet.withAuthTag(true); - if(!packet.getAuthTagLength()) + if(!packet.getAuthTagLength()) { return true; + } kd.generate(dir_, LABEL_AUTH, packet.getSeqNr(), key_); #ifndef USE_SSL_CRYPTO @@ -133,36 +139,35 @@ bool Sha1AuthAlgo::checkTag(KeyDerivation& kd, EncryptedPacket& packet) if(err) { cLog.msg(Log::PRIO_ERROR) << "Sha1AuthAlgo::setKey: Failed to set hmac key: " << AnytunGpgError(err); return false; - } - + } + gcry_md_reset(handle_); gcry_md_write(handle_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); gcry_md_final(handle_); - u_int8_t* hmac = gcry_md_read(handle_, 0); + uint8_t* hmac = gcry_md_read(handle_, 0); #else HMAC_Init_ex(&ctx_, key_.getBuf(), key_.getLength(), EVP_sha1(), NULL); - - u_int8_t hmac[DIGEST_LENGTH]; + + uint8_t hmac[DIGEST_LENGTH]; HMAC_Update(&ctx_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); HMAC_Final(&ctx_, hmac, NULL); #endif - u_int8_t* tag = packet.getAuthTag(); - u_int32_t length = (packet.getAuthTagLength() < DIGEST_LENGTH) ? packet.getAuthTagLength() : DIGEST_LENGTH; + uint8_t* tag = packet.getAuthTag(); + uint32_t length = (packet.getAuthTagLength() < DIGEST_LENGTH) ? packet.getAuthTagLength() : DIGEST_LENGTH; if(length > DIGEST_LENGTH) - for(u_int32_t i=0; i < (packet.getAuthTagLength() - DIGEST_LENGTH); ++i) - if(tag[i]) return false; + for(uint32_t i=0; i < (packet.getAuthTagLength() - DIGEST_LENGTH); ++i) + if(tag[i]) { return false; } int ret = std::memcmp(&tag[packet.getAuthTagLength() - length], &hmac[DIGEST_LENGTH - length], length); packet.removeAuthTag(); - - if(ret) - return false; + if(ret) { + return false; + } + return true; - } #endif - diff --git a/src/authAlgo.h b/src/authAlgo.h index 1c7fa1b..663962f 100644 --- a/src/authAlgo.h +++ b/src/authAlgo.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -76,7 +76,7 @@ public: void generate(KeyDerivation& kd, EncryptedPacket& packet); bool checkTag(KeyDerivation& kd, EncryptedPacket& packet); - static const u_int32_t DIGEST_LENGTH = 0; + static const uint32_t DIGEST_LENGTH = 0; }; #ifndef NO_CRYPT @@ -92,7 +92,7 @@ public: void generate(KeyDerivation& kd, EncryptedPacket& packet); bool checkTag(KeyDerivation& kd, EncryptedPacket& packet); - static const u_int32_t DIGEST_LENGTH = 20; + static const uint32_t DIGEST_LENGTH = 20; private: #ifndef USE_SSL_CRYPTO @@ -100,7 +100,7 @@ private: #else HMAC_CTX ctx_; #endif - + Buffer key_; }; #endif diff --git a/src/authAlgoFactory.cpp b/src/authAlgoFactory.cpp index d1b2fc5..0cd22ce 100644 --- a/src/authAlgoFactory.cpp +++ b/src/authAlgoFactory.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -39,25 +39,30 @@ AuthAlgo* AuthAlgoFactory::create(std::string const& type, kd_dir_t dir) { - if(type == "null") + if(type == "null") { return new NullAuthAlgo(); + } #ifndef NO_CRYPT - else if(type == "sha1") + else if(type == "sha1") { return new Sha1AuthAlgo(dir); + } #endif - else + else { throw std::invalid_argument("auth algo not available"); + } } -u_int32_t AuthAlgoFactory::getDigestLength(std::string const& type) +uint32_t AuthAlgoFactory::getDigestLength(std::string const& type) { - if(type == "null") + if(type == "null") { return NullAuthAlgo::DIGEST_LENGTH; + } #ifndef NO_CRYPT - else if(type == "sha1") + else if(type == "sha1") { return Sha1AuthAlgo::DIGEST_LENGTH; + } #endif - else + else { throw std::invalid_argument("auth algo not available"); + } } - diff --git a/src/authAlgoFactory.h b/src/authAlgoFactory.h index db3125b..86a4c38 100644 --- a/src/authAlgoFactory.h +++ b/src/authAlgoFactory.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,7 +42,7 @@ class AuthAlgoFactory { public: static AuthAlgo* create(std::string const& type, kd_dir_t dir); - static u_int32_t getDigestLength(std::string const& type); + static uint32_t getDigestLength(std::string const& type); private: AuthAlgoFactory(); diff --git a/src/bsd/tunDevice.cpp b/src/bsd/tunDevice.cpp index 9cd58df..b4b5e29 100644 --- a/src/bsd/tunDevice.cpp +++ b/src/bsd/tunDevice.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -54,7 +54,7 @@ #define DEVICE_FILE_MAX 255 -TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, u_int16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400),sys_exec_(NULL) +TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400),sys_exec_(NULL) { std::string device_file = "/dev/"; bool dynamic = true; @@ -71,34 +71,36 @@ TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifc else if(conf_.type_ == TYPE_TUN) { device_file.append("tun"); actual_name_ = "tun"; - } - else if(conf_.type_ == TYPE_TAP) { + } else if(conf_.type_ == TYPE_TAP) { device_file.append("tap"); actual_name_ = "tap"; } #endif - else + else { AnytunError::throwErr() << "unable to recognize type of device (tun or tap)"; + } - u_int32_t dev_id=0; + uint32_t dev_id=0; if(dynamic) { for(; dev_id <= DEVICE_FILE_MAX; ++dev_id) { std::ostringstream ds; ds << device_file; ds << dev_id; fd_ = ::open(ds.str().c_str(), O_RDWR); - if(fd_ >= 0) + if(fd_ >= 0) { break; + } } - } - else + } else { fd_ = ::open(device_file.c_str(), O_RDWR); + } if(fd_ < 0) { - if(dynamic) + if(dynamic) { AnytunError::throwErr() << "can't open device file dynamically: no unused node left"; - else + } else { AnytunError::throwErr() << "can't open device file (" << device_file << "): " << AnytunErrno(errno); + } } if(dynamic) { @@ -106,22 +108,24 @@ TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifc s << actual_name_; s << dev_id; actual_name_ = s.str(); - } - else + } else { actual_name_ = dev_name; - + } + actual_node_ = device_file; init_post(); - if(ifcfg_addr != "") + if(ifcfg_addr != "") { do_ifconfig(); + } } TunDevice::~TunDevice() { - if(fd_ > 0) + if(fd_ > 0) { ::close(fd_); + } } #if defined(__GNUC__) && defined(__OpenBSD__) @@ -129,21 +133,23 @@ TunDevice::~TunDevice() void TunDevice::init_post() { with_pi_ = true; - if(conf_.type_ == TYPE_TAP) + if(conf_.type_ == TYPE_TAP) { with_pi_ = false; - - struct tuninfo ti; + } + + struct tuninfo ti; - if (ioctl(fd_, TUNGIFINFO, &ti) < 0) { + if(ioctl(fd_, TUNGIFINFO, &ti) < 0) { ::close(fd_); AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno); } - + ti.flags |= IFF_MULTICAST; - if(conf_.type_ == TYPE_TUN) + if(conf_.type_ == TYPE_TUN) { ti.flags &= ~IFF_POINTOPOINT; - - if (ioctl(fd_, TUNSIFINFO, &ti) < 0) { + } + + if(ioctl(fd_, TUNSIFINFO, &ti) < 0) { ::close(fd_); AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno); } @@ -154,8 +160,9 @@ void TunDevice::init_post() void TunDevice::init_post() { with_pi_ = true; - if(conf_.type_ == TYPE_TAP) + if(conf_.type_ == TYPE_TAP) { with_pi_ = false; + } if(conf_.type_ == TYPE_TUN) { int arg = 0; @@ -192,63 +199,68 @@ void TunDevice::init_post() } #else - #error This Device works just for OpenBSD, FreeBSD or NetBSD +#error This Device works just for OpenBSD, FreeBSD or NetBSD #endif int TunDevice::fix_return(int ret, size_t pi_length) const { - if(ret < 0) + if(ret < 0) { return ret; + } return (static_cast(ret) > pi_length ? (ret - pi_length) : 0); } -int TunDevice::read(u_int8_t* buf, u_int32_t len) +int TunDevice::read(uint8_t* buf, uint32_t len) { - if(fd_ < 0) + if(fd_ < 0) { return -1; - + } + if(with_pi_) { struct iovec iov[2]; - u_int32_t type; - + uint32_t type; + iov[0].iov_base = &type; iov[0].iov_len = sizeof(type); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::readv(fd_, iov, 2), sizeof(type))); - } - else + } else { return(::read(fd_, buf, len)); + } } -int TunDevice::write(u_int8_t* buf, u_int32_t len) +int TunDevice::write(uint8_t* buf, uint32_t len) { - if(fd_ < 0) + if(fd_ < 0) { return -1; - - if(!buf) + } + + if(!buf) { return 0; + } if(with_pi_) { struct iovec iov[2]; - u_int32_t type; - struct ip *hdr = reinterpret_cast(buf); - + uint32_t type; + struct ip* hdr = reinterpret_cast(buf); + type = 0; - if(hdr->ip_v == 4) + if(hdr->ip_v == 4) { type = htonl(AF_INET); - else + } else { type = htonl(AF_INET6); - + } + iov[0].iov_base = &type; iov[0].iov_len = sizeof(type); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::writev(fd_, iov, 2), sizeof(type))); - } - else + } else { return(::write(fd_, buf, len)); + } } void TunDevice::do_ifconfig() @@ -257,17 +269,17 @@ void TunDevice::do_ifconfig() mtu_ss << conf_.mtu_; StringVector args = boost::assign::list_of(actual_name_)(conf_.addr_.toString())("netmask")(conf_.netmask_.toString())("mtu")(mtu_ss.str()); - if(conf_.type_ == TYPE_TUN) + if(conf_.type_ == TYPE_TUN) { args.push_back("up"); - else { + } else { #if defined(__GNUC__) && defined(__OpenBSD__) args.push_back("link0"); #elif defined(__GNUC__) && (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) args.push_back("up"); #elif defined(__GNUC__) && defined(__NetBSD__) - // nothing to be done here + // nothing to be done here #else - #error This Device works just for OpenBSD, FreeBSD or NetBSD +#error This Device works just for OpenBSD, FreeBSD or NetBSD #endif } sys_exec_ = new SysExec("/sbin/ifconfig", args); @@ -275,7 +287,8 @@ void TunDevice::do_ifconfig() void TunDevice::waitUntilReady() { - if(sys_exec_) + if(sys_exec_) { SysExec::waitAndDestroy(sys_exec_); + } } diff --git a/src/buffer.cpp b/src/buffer.cpp index 574c034..320129d 100644 --- a/src/buffer.cpp +++ b/src/buffer.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -41,13 +41,13 @@ #include "buffer.h" Buffer::Buffer(bool allow_realloc) : buf_(0), length_(0), real_length_(0), allow_realloc_(allow_realloc) -{ +{ } -Buffer::Buffer(u_int32_t length, bool allow_realloc) : length_(length), real_length_(length_ + Buffer::OVER_SIZE_), - allow_realloc_(allow_realloc) +Buffer::Buffer(uint32_t length, bool allow_realloc) : length_(length), real_length_(length_ + Buffer::OVER_SIZE_), + allow_realloc_(allow_realloc) { - buf_ = new u_int8_t[real_length_]; + buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; @@ -56,8 +56,8 @@ Buffer::Buffer(u_int32_t length, bool allow_realloc) : length_(length), real_len std::memset(buf_, 0, real_length_); } -Buffer::Buffer(u_int8_t* data, u_int32_t length, bool allow_realloc) : length_(length), real_length_(length + Buffer::OVER_SIZE_), - allow_realloc_(allow_realloc) +Buffer::Buffer(uint8_t* data, uint32_t length, bool allow_realloc) : length_(length), real_length_(length + Buffer::OVER_SIZE_), + allow_realloc_(allow_realloc) { if(!data) { length_ = 0; @@ -65,7 +65,7 @@ Buffer::Buffer(u_int8_t* data, u_int32_t length, bool allow_realloc) : length_(l return; } - buf_ = new u_int8_t[real_length_]; + buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; @@ -74,35 +74,35 @@ Buffer::Buffer(u_int8_t* data, u_int32_t length, bool allow_realloc) : length_(l std::memcpy(buf_, data, length_); } -Buffer::Buffer(std::string hex_data, bool allow_realloc) : length_(static_cast(hex_data.size())/2), - real_length_(length_ + Buffer::OVER_SIZE_), - allow_realloc_(allow_realloc) +Buffer::Buffer(std::string hex_data, bool allow_realloc) : length_(static_cast(hex_data.size())/2), + real_length_(length_ + Buffer::OVER_SIZE_), + allow_realloc_(allow_realloc) { - buf_ = new u_int8_t[real_length_]; + buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; throw std::bad_alloc(); } - - for(u_int32_t i=0; i> std::hex >> tmp)) tmp = 0; - buf_[i] = static_cast(tmp); + if(!(ss >> std::hex >> tmp)) { tmp = 0; } + buf_[i] = static_cast(tmp); } } Buffer::~Buffer() { - if(buf_) + if(buf_) { delete[] buf_; + } } -Buffer::Buffer(const Buffer &src) : length_(src.length_), real_length_(src.real_length_), allow_realloc_(src.allow_realloc_) +Buffer::Buffer(const Buffer& src) : length_(src.length_), real_length_(src.real_length_), allow_realloc_(src.allow_realloc_) { - buf_ = new u_int8_t[real_length_]; + buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; @@ -111,16 +111,17 @@ Buffer::Buffer(const Buffer &src) : length_(src.length_), real_length_(src.real_ std::memcpy(buf_, src.buf_, length_); } -void Buffer::operator=(const Buffer &src) +void Buffer::operator=(const Buffer& src) { - if(buf_) + if(buf_) { delete[] buf_; - + } + length_ = src.length_; - real_length_ = src.real_length_; + real_length_ = src.real_length_; allow_realloc_ = src.allow_realloc_; - - buf_ = new u_int8_t[real_length_]; + + buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; @@ -129,96 +130,104 @@ void Buffer::operator=(const Buffer &src) std::memcpy(buf_, src.buf_, length_); } -bool Buffer::operator==(const Buffer &cmp) const +bool Buffer::operator==(const Buffer& cmp) const { - if(length_ != cmp.length_) + if(length_ != cmp.length_) { return false; + } - if(!std::memcmp(buf_, cmp.buf_, length_)) + if(!std::memcmp(buf_, cmp.buf_, length_)) { return true; + } return false; } -Buffer Buffer::operator^(const Buffer &xor_by) const +Buffer Buffer::operator^(const Buffer& xor_by) const { - u_int32_t res_length = (xor_by.length_ > length_) ? xor_by.length_ : length_; - u_int32_t min_length = (xor_by.length_ < length_) ? xor_by.length_ : length_; + uint32_t res_length = (xor_by.length_ > length_) ? xor_by.length_ : length_; + uint32_t min_length = (xor_by.length_ < length_) ? xor_by.length_ : length_; Buffer res(res_length); - for( u_int32_t index = 0; index < min_length; index++ ) + for(uint32_t index = 0; index < min_length; index++) { res[index] = buf_[index] ^ xor_by[index]; - + } + return res; } -u_int32_t Buffer::getLength() const +uint32_t Buffer::getLength() const { return length_; } -void Buffer::setLength(u_int32_t new_length) +void Buffer::setLength(uint32_t new_length) { - if(new_length == length_) + if(new_length == length_) { return; + } - if(new_length > real_length_) - { - if(!allow_realloc_) + if(new_length > real_length_) { + if(!allow_realloc_) { throw std::out_of_range("buffer::setLength() - reallocation not allowed for this Buffer"); + } - u_int8_t* old_buf = buf_; - u_int32_t old_length = length_; + uint8_t* old_buf = buf_; + uint32_t old_length = length_; length_ = new_length; real_length_ = length_ + Buffer::OVER_SIZE_; - - buf_ = new u_int8_t[real_length_]; + + buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; - if(old_buf) + if(old_buf) { delete[] old_buf; - + } + throw std::bad_alloc(); } std::memcpy(buf_, old_buf, old_length); - if(old_buf) + if(old_buf) { delete[] old_buf; + } old_buf = &buf_[old_length]; std::memset(old_buf, 0, real_length_ - old_length); - } - else + } else { length_ = new_length; + } reinit(); -} +} -u_int8_t* Buffer::getBuf() +uint8_t* Buffer::getBuf() { return buf_; } -u_int8_t& Buffer::operator[](u_int32_t index) +uint8_t& Buffer::operator[](uint32_t index) { - if(index >= length_) + if(index >= length_) { throw std::out_of_range("buffer::operator[]"); + } return buf_[index]; } -u_int8_t Buffer::operator[](u_int32_t index) const +uint8_t Buffer::operator[](uint32_t index) const { - if(index >= length_) + if(index >= length_) { throw std::out_of_range("buffer::operator[] const"); + } return buf_[index]; } -Buffer::operator u_int8_t*() +Buffer::operator uint8_t*() { return buf_; } @@ -227,15 +236,15 @@ std::string Buffer::getHexDump() const { std::stringstream ss; ss << "Length=" << length_ << std::endl << std::hex << std::uppercase; - for( u_int32_t index = 0; index < length_; index++ ) - { - ss << std::setw(2) << std::setfill('0') << u_int32_t(buf_[index]) << " "; + for(uint32_t index = 0; index < length_; index++) { + ss << std::setw(2) << std::setfill('0') << uint32_t(buf_[index]) << " "; if(!((index+1) % 16)) { ss << std::endl; continue; } - if(!((index+1) % 8)) + if(!((index+1) % 8)) { ss << " "; + } } return ss.str(); } @@ -244,9 +253,8 @@ std::string Buffer::getHexDumpOneLine() const { std::stringstream ss; ss << length_ << " Bytes,'" << std::hex << std::uppercase; - for( u_int32_t index = 0; index < length_; index++ ) - { - ss << std::setw(2) << std::setfill('0') << u_int32_t(buf_[index]); + for(uint32_t index = 0; index < length_; index++) { + ss << std::setw(2) << std::setfill('0') << uint32_t(buf_[index]); } ss << "'"; return ss.str(); diff --git a/src/buffer.h b/src/buffer.h index bbece3d..12e771f 100644 --- a/src/buffer.h +++ b/src/buffer.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,36 +43,36 @@ class Buffer { public: Buffer(bool allow_realloc = true); - Buffer(u_int32_t length, bool allow_realloc = true); - Buffer(u_int8_t* data, u_int32_t length, bool allow_realloc = true); + Buffer(uint32_t length, bool allow_realloc = true); + Buffer(uint8_t* data, uint32_t length, bool allow_realloc = true); Buffer(std::string hex_data, bool allow_realloc = true); virtual ~Buffer(); - Buffer(const Buffer &src); - void operator=(const Buffer &src); - bool operator==(const Buffer &cmp) const; - Buffer operator^(const Buffer &xor_by) const; + Buffer(const Buffer& src); + void operator=(const Buffer& src); + bool operator==(const Buffer& cmp) const; + Buffer operator^(const Buffer& xor_by) const; - u_int32_t getLength() const; - virtual void setLength(u_int32_t new_length); - u_int8_t* getBuf(); - u_int8_t& operator[](u_int32_t index); - u_int8_t operator[](u_int32_t index) const; + uint32_t getLength() const; + virtual void setLength(uint32_t new_length); + uint8_t* getBuf(); + uint8_t& operator[](uint32_t index); + uint8_t operator[](uint32_t index) const; std::string getHexDump() const; std::string getHexDumpOneLine() const; bool isReallocAllowed() const; - operator u_int8_t*(); + operator uint8_t*(); protected: virtual void reinit() {}; - u_int8_t *buf_; - u_int32_t length_; - u_int32_t real_length_; + uint8_t* buf_; + uint32_t length_; + uint32_t real_length_; bool allow_realloc_; - static const u_int32_t OVER_SIZE_ = 100; + static const uint32_t OVER_SIZE_ = 100; }; #endif diff --git a/src/cipher.cpp b/src/cipher.cpp index 5613739..a10e6c4 100644 --- a/src/cipher.cpp +++ b/src/cipher.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,58 +42,64 @@ #include "log.h" #include "anytunError.h" -void Cipher::encrypt(KeyDerivation& kd, PlainPacket & in, EncryptedPacket & out, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) +void Cipher::encrypt(KeyDerivation& kd, PlainPacket& in, EncryptedPacket& out, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { - u_int32_t len = cipher(kd, in, in.getLength(), out.getPayload(), out.getPayloadLength(), seq_nr, sender_id, mux); - out.setSenderId(sender_id); - out.setSeqNr(seq_nr); + uint32_t len = cipher(kd, in, in.getLength(), out.getPayload(), out.getPayloadLength(), seq_nr, sender_id, mux); + out.setSenderId(sender_id); + out.setSeqNr(seq_nr); out.setMux(mux); - out.setPayloadLength(len); + out.setPayloadLength(len); } -void Cipher::decrypt(KeyDerivation& kd, EncryptedPacket & in, PlainPacket & out) +void Cipher::decrypt(KeyDerivation& kd, EncryptedPacket& in, PlainPacket& out) { - u_int32_t len = decipher(kd, in.getPayload() , in.getPayloadLength(), out, out.getLength(), in.getSeqNr(), in.getSenderId(), in.getMux()); - out.setLength(len); + uint32_t len = decipher(kd, in.getPayload() , in.getPayloadLength(), out, out.getLength(), in.getSeqNr(), in.getSenderId(), in.getMux()); + out.setLength(len); } //******* NullCipher ******* -u_int32_t NullCipher::cipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) +uint32_t NullCipher::cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { - std::memcpy(out, in, (ilen < olen) ? ilen : olen); + std::memcpy(out, in, (ilen < olen) ? ilen : olen); return (ilen < olen) ? ilen : olen; } -u_int32_t NullCipher::decipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) +uint32_t NullCipher::decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { - std::memcpy(out, in, (ilen < olen) ? ilen : olen); + std::memcpy(out, in, (ilen < olen) ? ilen : olen); return (ilen < olen) ? ilen : olen; } #ifndef NO_CRYPT -//****** AesIcmCipher ****** +//****** AesIcmCipher ****** -AesIcmCipher::AesIcmCipher(kd_dir_t d) : Cipher(d), key_(u_int32_t(DEFAULT_KEY_LENGTH/8)), salt_(u_int32_t(SALT_LENGTH)) +AesIcmCipher::AesIcmCipher(kd_dir_t d) : Cipher(d), key_(uint32_t(DEFAULT_KEY_LENGTH/8)), salt_(uint32_t(SALT_LENGTH)) { init(); } -AesIcmCipher::AesIcmCipher(kd_dir_t d, u_int16_t key_length) : Cipher(d), key_(u_int32_t(key_length/8)), salt_(u_int32_t(SALT_LENGTH)) +AesIcmCipher::AesIcmCipher(kd_dir_t d, uint16_t key_length) : Cipher(d), key_(uint32_t(key_length/8)), salt_(uint32_t(SALT_LENGTH)) { init(key_length); } -void AesIcmCipher::init(u_int16_t key_length) +void AesIcmCipher::init(uint16_t key_length) { #ifndef USE_SSL_CRYPTO handle_ = NULL; int algo; switch(key_length) { - case 128: algo = GCRY_CIPHER_AES128; break; - case 192: algo = GCRY_CIPHER_AES192; break; - case 256: algo = GCRY_CIPHER_AES256; break; + case 128: + algo = GCRY_CIPHER_AES128; + break; + case 192: + algo = GCRY_CIPHER_AES192; + break; + case 256: + algo = GCRY_CIPHER_AES256; + break; default: { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher::AesIcmCipher: cipher key length of " << key_length << " Bits is not supported"; return; @@ -101,9 +107,9 @@ void AesIcmCipher::init(u_int16_t key_length) } gcry_error_t err = gcry_cipher_open(&handle_, algo, GCRY_CIPHER_MODE_CTR, 0); - if( err ) { + if(err) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher::AesIcmCipher: Failed to open cipher" << AnytunGpgError(err); - } + } #endif } @@ -111,18 +117,19 @@ void AesIcmCipher::init(u_int16_t key_length) AesIcmCipher::~AesIcmCipher() { #ifndef USE_SSL_CRYPTO - if(handle_) + if(handle_) { gcry_cipher_close(handle_); + } #endif } -u_int32_t AesIcmCipher::cipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) +uint32_t AesIcmCipher::cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { calc(kd, in, ilen, out, olen, seq_nr, sender_id, mux); return (ilen < olen) ? ilen : olen; } -u_int32_t AesIcmCipher::decipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) +uint32_t AesIcmCipher::decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { calc(kd, in, ilen, out, olen, seq_nr, sender_id, mux); return (ilen < olen) ? ilen : olen; @@ -141,11 +148,12 @@ void AesIcmCipher::calcCtr(KeyDerivation& kd, seq_nr_t seq_nr, sender_id_t sende return; } -void AesIcmCipher::calc(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) +void AesIcmCipher::calc(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { #ifndef USE_SSL_CRYPTO - if(!handle_) + if(!handle_) { return; + } #endif kd.generate(dir_, LABEL_ENC, seq_nr, key_); @@ -164,7 +172,7 @@ void AesIcmCipher::calc(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_ #endif calcCtr(kd, seq_nr, sender_id, mux); - + #ifndef USE_SSL_CRYPTO err = gcry_cipher_setctr(handle_, ctr_.buf_, CTR_LENGTH); if(err) { diff --git a/src/cipher.h b/src/cipher.h index 92c4ef2..97d941c 100644 --- a/src/cipher.h +++ b/src/cipher.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -53,12 +53,12 @@ public: Cipher(kd_dir_t d) : dir_(d) {}; virtual ~Cipher() {}; - void encrypt(KeyDerivation& kd, PlainPacket & in, EncryptedPacket & out, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); - void decrypt(KeyDerivation& kd, EncryptedPacket & in, PlainPacket & out); - + void encrypt(KeyDerivation& kd, PlainPacket& in, EncryptedPacket& out, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); + void decrypt(KeyDerivation& kd, EncryptedPacket& in, PlainPacket& out); + protected: - virtual u_int32_t cipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) = 0; - virtual u_int32_t decipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) = 0; + virtual uint32_t cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) = 0; + virtual uint32_t decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) = 0; kd_dir_t dir_; }; @@ -68,8 +68,8 @@ protected: class NullCipher : public Cipher { protected: - u_int32_t cipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); - u_int32_t decipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); + uint32_t cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); + uint32_t decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); }; #ifndef NO_CRYPT @@ -79,52 +79,52 @@ class AesIcmCipher : public Cipher { public: AesIcmCipher(kd_dir_t d); - AesIcmCipher(kd_dir_t d, u_int16_t key_length); + AesIcmCipher(kd_dir_t d, uint16_t key_length); ~AesIcmCipher(); - - static const u_int16_t DEFAULT_KEY_LENGTH = 128; - static const u_int16_t CTR_LENGTH = 16; - static const u_int16_t SALT_LENGTH = 14; + + static const uint16_t DEFAULT_KEY_LENGTH = 128; + static const uint16_t CTR_LENGTH = 16; + static const uint16_t SALT_LENGTH = 14; protected: - u_int32_t cipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); - u_int32_t decipher(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); + uint32_t cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); + uint32_t decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); private: - void init(u_int16_t key_length = DEFAULT_KEY_LENGTH); + void init(uint16_t key_length = DEFAULT_KEY_LENGTH); void calcCtr(KeyDerivation& kd, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); - void calc(KeyDerivation& kd, u_int8_t* in, u_int32_t ilen, u_int8_t* out, u_int32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); + void calc(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux); #ifndef USE_SSL_CRYPTO gcry_cipher_hd_t handle_; #else AES_KEY aes_key_; - u_int8_t ecount_buf_[AES_BLOCK_SIZE]; + uint8_t ecount_buf_[AES_BLOCK_SIZE]; #endif Buffer key_; Buffer salt_; #ifdef _MSC_VER - #pragma pack(push, 1) +#pragma pack(push, 1) #endif union ATTR_PACKED cipher_aesctr_ctr_union { - u_int8_t buf_[CTR_LENGTH]; + uint8_t buf_[CTR_LENGTH]; struct ATTR_PACKED { - u_int8_t buf_[SALT_LENGTH]; - u_int16_t zero_; + uint8_t buf_[SALT_LENGTH]; + uint16_t zero_; } salt_; - struct ATTR_PACKED { - u_int8_t fill_[SALT_LENGTH - sizeof(mux_t) - sizeof(sender_id_t) - 2*sizeof(u_int8_t) - sizeof(seq_nr_t)]; + struct ATTR_PACKED { + uint8_t fill_[SALT_LENGTH - sizeof(mux_t) - sizeof(sender_id_t) - 2*sizeof(uint8_t) - sizeof(seq_nr_t)]; mux_t mux_; sender_id_t sender_id_; - u_int8_t empty_[2]; + uint8_t empty_[2]; seq_nr_t seq_nr_; - u_int16_t zero_; + uint16_t zero_; } params_; } ctr_; #ifdef _MSC_VER - #pragma pack(pop) +#pragma pack(pop) #endif }; #endif diff --git a/src/cipherFactory.cpp b/src/cipherFactory.cpp index 96879b7..836a517 100644 --- a/src/cipherFactory.cpp +++ b/src/cipherFactory.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -39,19 +39,22 @@ Cipher* CipherFactory::create(std::string const& type, kd_dir_t dir) { - if(type == "null") + if(type == "null") { return new NullCipher(); + } #ifndef NO_CRYPT - else if(type == "aes-ctr") + else if(type == "aes-ctr") { return new AesIcmCipher(dir); - else if(type == "aes-ctr-128") + } else if(type == "aes-ctr-128") { return new AesIcmCipher(dir, 128); - else if(type == "aes-ctr-192") + } else if(type == "aes-ctr-192") { return new AesIcmCipher(dir, 192); - else if(type == "aes-ctr-256") + } else if(type == "aes-ctr-256") { return new AesIcmCipher(dir, 256); + } #endif - else + else { throw std::invalid_argument("cipher not available"); + } } diff --git a/src/cipherFactory.h b/src/cipherFactory.h index 96a8d33..e268c7c 100644 --- a/src/cipherFactory.h +++ b/src/cipherFactory.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/configure b/src/configure index bcadb99..76b1017 100755 --- a/src/configure +++ b/src/configure @@ -12,7 +12,7 @@ # tunneling and relaying of packets of any protocol. # # -# Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, +# Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, # Christian Pointner # # This file is part of Anytun. @@ -36,7 +36,7 @@ TARGET=`uname -s` EBUILD_COMPAT=0 CXXFLAGS='-g -Wall -O2 -DLOG_SYSLOG -DLOG_FILE -DLOG_STDOUT' -LDFLAGS='-g -Wall -O2 -lboost_thread -lboost_serialization -lboost_system -lboost_date_time' +LDFLAGS='-g -Wall -O2 -lboost_thread -lboost_serialization -lboost_system -lboost_date_time -lpthread' CRYPTO_LIB='gcrypt' PASSPHRASE=1 @@ -105,7 +105,7 @@ do ;; --no-crypto) CRYPTO_LIB='none' - ;; + ;; --enable-passphrase) PASSPHRASE=1 ;; @@ -142,10 +142,11 @@ fi rm -f include.mk -case $TARGET in +rm -f version.h +case $TARGET in Linux) rm -f tunDevice.cpp - ln -sf linux/tunDevice.cpp + ln -sf linux/tunDevice.cpp rm -f signalHandler.hpp ln -sf posix/signalHandler.hpp rm -f sysExec.hpp @@ -157,7 +158,7 @@ case $TARGET in ;; OpenBSD|FreeBSD|NetBSD|GNU/kFreeBSD) rm -f tunDevice.cpp - ln -sf bsd/tunDevice.cpp + ln -sf bsd/tunDevice.cpp rm -f signalHandler.hpp ln -sf posix/signalHandler.hpp rm -f sysExec.hpp @@ -187,7 +188,6 @@ case $CRYPTO_LIB in ;; none) CXXFLAGS=$CXXFLAGS' -DNO_CRYPT' - echo "NO_CRYPT_OBJ = 1" >> include.mk echo "disabling crypto" ;; esac @@ -222,15 +222,15 @@ if [ -z "$EXAMPLESDIR" ]; then EXAMPLESDIR=$PREFIX/share/examples fi -cat >> include.mk < include.mk <> include.mk +fi + if [ $INSTALLMANPAGE -eq 1 ]; then echo "MANDIR := $MANDIR" >> include.mk echo "installing manpage" @@ -257,7 +261,7 @@ fi VERSION=`cat ../version` if which svn >/dev/null; then - SVN_REV=`svn info | grep "^Revision: " | awk '{print($2)}'` + SVN_REV=`svn info 2> /dev/null | grep "^Revision: " | awk '{print($2)}'` if [ -n "$SVN_REV" ]; then VERSION="$VERSION (svn$SVN_REV)" fi @@ -265,8 +269,8 @@ fi HOSTNAME=`hostname` DATE=`date +"%d.%m.%Y %H:%M:%S %Z"` -cat >> version.h < version.h < * * This file is part of Anytun. @@ -47,8 +47,9 @@ ConnectionList& ConnectionList::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new ConnectionList(); + } return *inst; } @@ -59,22 +60,21 @@ ConnectionList::ConnectionList() ConnectionList::~ConnectionList() { -// TODO: comment this in as soon as threads @ main get cleaned up properly -// Lock lock(mutex_); -// ConnectionMap::iterator it; -// for(it = connections_.begin(); it != connections_.end(); ++it) { -// delete &it->second.kd_; -// delete &it->second.seq_window_; -// } -} - -void ConnectionList::addConnection(ConnectionParam &conn, u_int16_t mux ) + // TODO: comment this in as soon as threads @ main get cleaned up properly + // Lock lock(mutex_); + // ConnectionMap::iterator it; + // for(it = connections_.begin(); it != connections_.end(); ++it) { + // delete &it->second.kd_; + // delete &it->second.seq_window_; + // } +} + +void ConnectionList::addConnection(ConnectionParam& conn, uint16_t mux) { Lock lock(mutex_); std::pair ret = connections_.insert(ConnectionMap::value_type(mux, conn)); - if(!ret.second) - { + if(!ret.second) { connections_.erase(ret.first); connections_.insert(ConnectionMap::value_type(mux, conn)); } @@ -82,8 +82,8 @@ void ConnectionList::addConnection(ConnectionParam &conn, u_int16_t mux ) const ConnectionMap::iterator ConnectionList::getEnd() { - Lock lock(mutex_); - return connections_.end(); + Lock lock(mutex_); + return connections_.end(); } ConnectionMap::iterator ConnectionList::getBeginUnlocked() @@ -103,50 +103,51 @@ ConnectionMap::iterator ConnectionList::getEndUnlocked() return connections_.end(); } -const ConnectionMap::iterator ConnectionList::getConnection(u_int16_t mux) +const ConnectionMap::iterator ConnectionList::getConnection(uint16_t mux) { - Lock lock(mutex_); - ConnectionMap::iterator it = connections_.find(mux); - return it; + Lock lock(mutex_); + ConnectionMap::iterator it = connections_.find(mux); + return it; } -ConnectionParam & ConnectionList::getOrNewConnectionUnlocked(u_int16_t mux) +ConnectionParam& ConnectionList::getOrNewConnectionUnlocked(uint16_t mux) { - ConnectionMap::iterator it = connections_.find(mux); - if(it!=connections_.end()) - return it->second; + ConnectionMap::iterator it = connections_.find(mux); + if(it!=connections_.end()) { + return it->second; + } - u_int8_t key[] = { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' + uint8_t key[] = { + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' }; - - u_int8_t salt[] = { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n' + + uint8_t salt[] = { + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n' }; - SeqWindow * seq= new SeqWindow(0); + SeqWindow* seq= new SeqWindow(0); seq_nr_t seq_nr_=0; - KeyDerivation * kd = KeyDerivationFactory::create(gOpt.getKdPrf()); + KeyDerivation* kd = KeyDerivationFactory::create(gOpt.getKdPrf()); kd->init(Buffer(key, sizeof(key)), Buffer(salt, sizeof(salt))); - ConnectionParam conn ((*kd), (*seq), seq_nr_, PacketSourceEndpoint()); - connections_.insert(ConnectionMap::value_type(mux, conn)); - it = connections_.find(mux); - return it->second; + ConnectionParam conn((*kd), (*seq), seq_nr_, PacketSourceEndpoint()); + connections_.insert(ConnectionMap::value_type(mux, conn)); + it = connections_.find(mux); + return it->second; } void ConnectionList::clear() { Lock lock(mutex_); - connections_.clear(); + connections_.clear(); } bool ConnectionList::empty() { Lock lock(mutex_); - return connections_.empty(); + return connections_.empty(); } Mutex& ConnectionList::getMutex() diff --git a/src/connectionList.h b/src/connectionList.h index 29eb94f..750a142 100644 --- a/src/connectionList.h +++ b/src/connectionList.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,37 +40,40 @@ #include "datatypes.h" #include "connectionParam.h" #include "networkAddress.h" -typedef std::map ConnectionMap; +typedef std::map ConnectionMap; class ConnectionList { public: - ConnectionList(); - ~ConnectionList(); - static ConnectionList& instance(); - void addConnection(ConnectionParam &conn, u_int16_t mux); - const ConnectionMap::iterator getConnection(u_int16_t mux); - const ConnectionMap::iterator getEnd(); - ConnectionMap::iterator getEndUnlocked(); - ConnectionMap::iterator getBeginUnlocked(); - const ConnectionMap::iterator getBegin(); - ConnectionParam & getOrNewConnectionUnlocked(u_int16_t mux); - bool empty(); - void clear(); + ConnectionList(); + ~ConnectionList(); + static ConnectionList& instance(); + void addConnection(ConnectionParam& conn, uint16_t mux); + const ConnectionMap::iterator getConnection(uint16_t mux); + const ConnectionMap::iterator getEnd(); + ConnectionMap::iterator getEndUnlocked(); + ConnectionMap::iterator getBeginUnlocked(); + const ConnectionMap::iterator getBegin(); + ConnectionParam& getOrNewConnectionUnlocked(uint16_t mux); + bool empty(); + void clear(); Mutex& getMutex(); private: static Mutex instMutex; - static ConnectionList* inst; - class instanceCleaner { - public: ~instanceCleaner() { - if(ConnectionList::inst != 0) - delete ConnectionList::inst; - } + static ConnectionList* inst; + class instanceCleaner + { + public: + ~instanceCleaner() { + if(ConnectionList::inst != 0) { + delete ConnectionList::inst; + } + } }; - ConnectionList(const ConnectionList &s); - void operator=(const ConnectionList &s); - ConnectionMap connections_; + ConnectionList(const ConnectionList& s); + void operator=(const ConnectionList& s); + ConnectionMap connections_; Mutex mutex_; }; diff --git a/src/connectionParam.cpp b/src/connectionParam.cpp index fc1e33a..05b02ca 100644 --- a/src/connectionParam.cpp +++ b/src/connectionParam.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -36,6 +36,6 @@ ConnectionParam::ConnectionParam(KeyDerivation& kd, SeqWindow& seq_window,seq_nr { } -ConnectionParam::ConnectionParam(const ConnectionParam & src) : kd_(src.kd_),seq_window_(src.seq_window_),seq_nr_(src.seq_nr_),remote_end_(src.remote_end_),mutex_() +ConnectionParam::ConnectionParam(const ConnectionParam& src) : kd_(src.kd_),seq_window_(src.seq_window_),seq_nr_(src.seq_nr_),remote_end_(src.remote_end_),mutex_() { } diff --git a/src/connectionParam.h b/src/connectionParam.h index ed24531..563391c 100644 --- a/src/connectionParam.h +++ b/src/connectionParam.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -44,36 +44,36 @@ class ConnectionParam { public: - ConnectionParam(const ConnectionParam & src); - ConnectionParam( KeyDerivation& kd, SeqWindow& seq_window, seq_nr_t seq_nr_, PacketSourceEndpoint remote_end); + ConnectionParam(const ConnectionParam& src); + ConnectionParam(KeyDerivation& kd, SeqWindow& seq_window, seq_nr_t seq_nr_, PacketSourceEndpoint remote_end); KeyDerivation& kd_; SeqWindow& seq_window_; - seq_nr_t seq_nr_; - PacketSourceEndpoint remote_end_; + seq_nr_t seq_nr_; + PacketSourceEndpoint remote_end_; private: //TODO: check if this is ok - Mutex mutex_; + Mutex mutex_; friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - Lock lock(mutex_); - std::string remote_host(remote_end_.address().to_string()); - u_int16_t remote_port = remote_end_.port(); - ar & kd_; - ar & seq_window_; - ar & seq_nr_; - ar & remote_host; - ar & remote_port; - PacketSourceEndpoint emptyEndpoint; - UDPPacketSource::proto::endpoint endpoint(boost::asio::ip::address::from_string(remote_host), remote_port); - //This is a workarround, against race condition in sync process - //TODO: find a better solution - if (endpoint != emptyEndpoint && remote_host != "::" && remote_host != "[::]" && remote_host != "0.0.0.0") - remote_end_ = endpoint; - } + void serialize(Archive& ar, const unsigned int version) { + Lock lock(mutex_); + std::string remote_host(remote_end_.address().to_string()); + uint16_t remote_port = remote_end_.port(); + ar& kd_; + ar& seq_window_; + ar& seq_nr_; + ar& remote_host; + ar& remote_port; + PacketSourceEndpoint emptyEndpoint; + UDPPacketSource::proto::endpoint endpoint(boost::asio::ip::address::from_string(remote_host), remote_port); + //This is a workarround, against race condition in sync process + //TODO: find a better solution + if(endpoint != emptyEndpoint && remote_host != "::" && remote_host != "[::]" && remote_host != "0.0.0.0") { + remote_end_ = endpoint; + } + } }; #endif diff --git a/src/cryptinit.hpp b/src/cryptinit.hpp index f8ac938..64c57b4 100644 --- a/src/cryptinit.hpp +++ b/src/cryptinit.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -38,62 +38,64 @@ #include // boost thread callbacks for libgcrypt -static int boost_mutex_init(void **priv) +static int boost_mutex_init(void** priv) { - boost::mutex *lock = new boost::mutex(); - if (!lock) + boost::mutex* lock = new boost::mutex(); + if(!lock) { return ENOMEM; + } *priv = lock; return 0; } -static int boost_mutex_destroy(void **lock) +static int boost_mutex_destroy(void** lock) { delete reinterpret_cast(*lock); return 0; } -static int boost_mutex_lock(void **lock) +static int boost_mutex_lock(void** lock) { reinterpret_cast(*lock)->lock(); return 0; } -static int boost_mutex_unlock(void **lock) +static int boost_mutex_unlock(void** lock) { reinterpret_cast(*lock)->unlock(); return 0; } -static struct gcry_thread_cbs gcry_threads_boost = -{ GCRY_THREAD_OPTION_USER, NULL, +static struct gcry_thread_cbs gcry_threads_boost = { + GCRY_THREAD_OPTION_USER, NULL, boost_mutex_init, boost_mutex_destroy, - boost_mutex_lock, boost_mutex_unlock }; + boost_mutex_lock, boost_mutex_unlock +}; #define MIN_GCRYPT_VERSION "1.2.0" bool initLibGCrypt() { - // make libgcrypt thread safe + // make libgcrypt thread safe // this must be called before any other libgcrypt call - gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_boost ); + gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_boost); // this must be called right after the GCRYCTL_SET_THREAD_CBS command // no other function must be called till now - if( !gcry_check_version( MIN_GCRYPT_VERSION ) ) { + if(!gcry_check_version(MIN_GCRYPT_VERSION)) { std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl; return false; } - gcry_error_t err = gcry_control (GCRYCTL_DISABLE_SECMEM, 0); - if( err ) { + gcry_error_t err = gcry_control(GCRYCTL_DISABLE_SECMEM, 0); + if(err) { std::cout << "initLibGCrypt: Failed to disable secure memory: " << AnytunGpgError(err) << std::endl; return false; } // Tell Libgcrypt that initialization has completed. err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED); - if( err ) { + if(err) { std::cout << "initLibGCrypt: Failed to finish initialization: " << AnytunGpgError(err) << std::endl; return false; } diff --git a/src/datatypes.h b/src/datatypes.h index ba34614..cc13fb1 100644 --- a/src/datatypes.h +++ b/src/datatypes.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -36,23 +36,24 @@ #include #include -typedef boost::uint8_t u_int8_t; -typedef boost::uint16_t u_int16_t; -typedef boost::uint32_t u_int32_t; -typedef boost::uint64_t u_int64_t; -typedef boost::int8_t int8_t; -typedef boost::int16_t int16_t; -typedef boost::int32_t int32_t; -typedef boost::int64_t int64_t; +// should not be necessary on GCC, #ifdef + #include should do the job; still required on MS VC++9, though. +using boost::int8_t; +using boost::uint8_t; +using boost::int16_t; +using boost::uint16_t; +using boost::int32_t; +using boost::uint32_t; +using boost::int64_t; +using boost::uint64_t; -typedef u_int32_t window_size_t; +typedef uint32_t window_size_t; -typedef u_int32_t seq_nr_t; +typedef uint32_t seq_nr_t; #define SEQ_NR_MAX 0xFFFFFFFF -typedef u_int16_t sender_id_t; -typedef u_int16_t payload_type_t; -typedef u_int16_t mux_t; -typedef u_int32_t satp_prf_label_t; +typedef uint16_t sender_id_t; +typedef uint16_t payload_type_t; +typedef uint16_t mux_t; +typedef uint32_t satp_prf_label_t; typedef enum { ANY, IPV4_ONLY, IPV6_ONLY } ResolvAddrType; @@ -63,7 +64,7 @@ typedef int system_error_t; #include #define ATTR_PACKED typedef DWORD system_error_t; -#endif +#endif #define MAX_PACKET_LENGTH 1600 diff --git a/src/deviceConfig.hpp b/src/deviceConfig.hpp index 6353cd1..ede6f34 100644 --- a/src/deviceConfig.hpp +++ b/src/deviceConfig.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -41,44 +41,48 @@ class TunDevice; enum device_type_t { TYPE_UNDEF, TYPE_TUN, TYPE_TAP }; -class DeviceConfig +class DeviceConfig { public: - DeviceConfig(std::string dev_name ,std::string dev_type, std::string ifcfg_addr, u_int16_t ifcfg_prefix, u_int16_t mtu) - { + DeviceConfig(std::string dev_name ,std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix, uint16_t mtu) { mtu_ = mtu; type_ = TYPE_UNDEF; #ifndef _MSC_VER if(dev_type != "") { - if(!dev_type.compare(0,3,"tun")) + if(!dev_type.compare(0,3,"tun")) { type_ = TYPE_TUN; - else if (!dev_type.compare(0,3,"tap")) + } else if(!dev_type.compare(0,3,"tap")) { type_ = TYPE_TAP; - } - else if(dev_name != "") { - if(!dev_name.compare(0,3,"tun")) + } + } else if(dev_name != "") { + if(!dev_name.compare(0,3,"tun")) { type_ = TYPE_TUN; - else if(!dev_name.compare(0,3,"tap")) + } else if(!dev_name.compare(0,3,"tap")) { type_ = TYPE_TAP; + } } #else - if(dev_type == "") + if(dev_type == "") { AnytunError::throwErr() << "Device type must be specified on Windows"; - - if(dev_type == "tun") + } + + if(dev_type == "tun") { type_ = TYPE_TUN; - else if(dev_type == "tap") + } else if(dev_type == "tap") { type_ = TYPE_TAP; + } - if(type_ == TYPE_TUN && ifcfg_addr == "") + if(type_ == TYPE_TUN && ifcfg_addr == "") { AnytunError::throwErr() << "Device type tun requires ifconfig parameter (--ifconfig)"; + } #endif - if(ifcfg_addr != "") + if(ifcfg_addr != "") { addr_.setNetworkAddress(ipv4, ifcfg_addr.c_str()); + } prefix_ = ifcfg_prefix; - u_int32_t mask = 0; - for(u_int16_t i = 0; i < prefix_; ++i) { + uint32_t mask = 0; + for(uint16_t i = 0; i < prefix_; ++i) { mask = mask >> 1; mask |= 0x80000000L; } @@ -89,8 +93,8 @@ private: device_type_t type_; NetworkAddress addr_; NetworkAddress netmask_; - u_int16_t prefix_; - u_int16_t mtu_; + uint16_t prefix_; + uint16_t mtu_; friend class TunDevice; }; diff --git a/src/encryptedPacket.cpp b/src/encryptedPacket.cpp index 46235c5..466378a 100644 --- a/src/encryptedPacket.cpp +++ b/src/encryptedPacket.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,184 +40,199 @@ #include "log.h" #include "anytunError.h" -EncryptedPacket::EncryptedPacket(u_int32_t payload_length, u_int32_t auth_tag_length, bool allow_realloc) +EncryptedPacket::EncryptedPacket(uint32_t payload_length, uint32_t auth_tag_length, bool allow_realloc) : Buffer(payload_length + sizeof(struct HeaderStruct), allow_realloc), auth_tag_length_(auth_tag_length) { header_ = reinterpret_cast(buf_); payload_ = buf_ + sizeof(struct HeaderStruct); auth_tag_ = NULL; - if(header_) - { + if(header_) { header_->seq_nr = 0; header_->sender_id = 0; header_->mux = 0; } } -u_int32_t EncryptedPacket::getHeaderLength() +uint32_t EncryptedPacket::getHeaderLength() { return sizeof(struct HeaderStruct); } seq_nr_t EncryptedPacket::getSeqNr() const { - if(header_) + if(header_) { return SEQ_NR_T_NTOH(header_->seq_nr); - + } + return 0; } sender_id_t EncryptedPacket::getSenderId() const { - if(header_) + if(header_) { return SENDER_ID_T_NTOH(header_->sender_id); + } return 0; } mux_t EncryptedPacket::getMux() const { - if(header_) + if(header_) { return MUX_T_NTOH(header_->mux); + } return 0; } void EncryptedPacket::setSeqNr(seq_nr_t seq_nr) { - if(header_) + if(header_) { header_->seq_nr = SEQ_NR_T_HTON(seq_nr); + } } void EncryptedPacket::setSenderId(sender_id_t sender_id) { - if(header_) + if(header_) { header_->sender_id = SENDER_ID_T_HTON(sender_id); + } } void EncryptedPacket::setMux(mux_t mux) { - if(header_) + if(header_) { header_->mux = MUX_T_HTON(mux); + } } void EncryptedPacket::setHeader(seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { - if(!header_) + if(!header_) { return; + } header_->seq_nr = SEQ_NR_T_HTON(seq_nr); header_->sender_id = SENDER_ID_T_HTON(sender_id); header_->mux = MUX_T_HTON(mux); } -u_int32_t EncryptedPacket::getPayloadLength() const +uint32_t EncryptedPacket::getPayloadLength() const { - if(!payload_) + if(!payload_) { return 0; + } - if(!auth_tag_) + if(!auth_tag_) { return (length_ > sizeof(struct HeaderStruct)) ? (length_ - sizeof(struct HeaderStruct)) : 0; - + } + return (length_ > (sizeof(struct HeaderStruct) + auth_tag_length_)) ? (length_ - sizeof(struct HeaderStruct) - auth_tag_length_) : 0; } -void EncryptedPacket::setPayloadLength(u_int32_t payload_length) +void EncryptedPacket::setPayloadLength(uint32_t payload_length) { Buffer::setLength(payload_length + sizeof(struct HeaderStruct)); - // depending on allow_realloc buf_ may point to another address - // therefore in this case reinit() gets called by Buffer::setLength() + // depending on allow_realloc buf_ may point to another address + // therefore in this case reinit() gets called by Buffer::setLength() } void EncryptedPacket::reinit() { header_ = reinterpret_cast(buf_); payload_ = buf_ + sizeof(struct HeaderStruct); - - if(length_ <= (sizeof(struct HeaderStruct))) + + if(length_ <= (sizeof(struct HeaderStruct))) { payload_ = NULL; - + } + if(length_ < (sizeof(struct HeaderStruct))) { header_ = NULL; - AnytunError::throwErr() << "encrypted packet can't be initialized, buffer is too small"; - } - - if(auth_tag_) - { + AnytunError::throwErr() << "encrypted packet can't be initialized, buffer is too small"; + } + + if(auth_tag_) { if(length_ < (sizeof(struct HeaderStruct) + auth_tag_length_)) { auth_tag_ = NULL; - AnytunError::throwErr() << "auth-tag can't be enabled, buffer is too small"; + AnytunError::throwErr() << "auth-tag can't be enabled, buffer is too small"; } auth_tag_ = buf_ + length_ - auth_tag_length_; - } + } } -u_int8_t* EncryptedPacket::getPayload() +uint8_t* EncryptedPacket::getPayload() { return payload_; } -u_int8_t* EncryptedPacket::getAuthenticatedPortion() +uint8_t* EncryptedPacket::getAuthenticatedPortion() { return buf_; } -u_int32_t EncryptedPacket::getAuthenticatedPortionLength() +uint32_t EncryptedPacket::getAuthenticatedPortionLength() { - if(!buf_) + if(!buf_) { return 0; + } - if(!auth_tag_) + if(!auth_tag_) { return length_; - + } + return (length_ > auth_tag_length_) ? (length_ - auth_tag_length_) : 0; } void EncryptedPacket::withAuthTag(bool b) { - if((b && auth_tag_) || (!b && !auth_tag_)) + if((b && auth_tag_) || (!b && !auth_tag_)) { return; - - if(b) - { - if(length_ < (sizeof(struct HeaderStruct) + auth_tag_length_)) + } + + if(b) { + if(length_ < (sizeof(struct HeaderStruct) + auth_tag_length_)) { AnytunError::throwErr() << "auth-tag can't be enabled, buffer is too small"; - + } + auth_tag_ = buf_ + length_ - auth_tag_length_; - } - else + } else { auth_tag_ = NULL; + } } void EncryptedPacket::addAuthTag() { - if(auth_tag_) + if(auth_tag_) { return; + } auth_tag_ = buf_; // will be set to the correct value @ reinit setLength(length_ + auth_tag_length_); - if(auth_tag_ == buf_) // reinit was not called by setLength + if(auth_tag_ == buf_) { // reinit was not called by setLength reinit(); + } } void EncryptedPacket::removeAuthTag() { - if(!auth_tag_) + if(!auth_tag_) { return; + } auth_tag_ = NULL; setLength(length_ - auth_tag_length_); } -u_int8_t* EncryptedPacket::getAuthTag() +uint8_t* EncryptedPacket::getAuthTag() { return auth_tag_; } -u_int32_t EncryptedPacket::getAuthTagLength() +uint32_t EncryptedPacket::getAuthTagLength() { - if(auth_tag_) + if(auth_tag_) { return auth_tag_length_; + } return 0; } diff --git a/src/encryptedPacket.h b/src/encryptedPacket.h index bd321b3..221c534 100644 --- a/src/encryptedPacket.h +++ b/src/encryptedPacket.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,10 +43,10 @@ public: /** * Packet constructor - * @param the length of the payload + * @param the length of the payload * @param allow reallocation of buffer */ - EncryptedPacket(u_int32_t payload_length, u_int32_t auth_tag_length, bool allow_realloc = false); + EncryptedPacket(uint32_t payload_length, uint32_t auth_tag_length, bool allow_realloc = false); /** * Packet destructor @@ -57,7 +57,7 @@ public: * Get the length of the header * @return the length of the header */ - static u_int32_t getHeaderLength(); + static uint32_t getHeaderLength(); /** * Get the sequence number @@ -107,53 +107,52 @@ public: * Get the length of the payload * @return the length of the payload */ - u_int32_t getPayloadLength() const; + uint32_t getPayloadLength() const; /** * Set the length of the payload * @param length length of the payload */ - void setPayloadLength(u_int32_t payload_length); + void setPayloadLength(uint32_t payload_length); /** * Get the the payload * @return the Pointer to the payload */ - u_int8_t* getPayload(); + uint8_t* getPayload(); - u_int8_t* getAuthenticatedPortion(); - u_int32_t getAuthenticatedPortionLength(); + uint8_t* getAuthenticatedPortion(); + uint32_t getAuthenticatedPortionLength(); void withAuthTag(bool b); void addAuthTag(); void removeAuthTag(); - u_int8_t* getAuthTag(); - u_int32_t getAuthTagLength(); - + uint8_t* getAuthTag(); + uint32_t getAuthTagLength(); + private: EncryptedPacket(); - EncryptedPacket(const EncryptedPacket &src); + EncryptedPacket(const EncryptedPacket& src); void reinit(); #ifdef _MSC_VER - #pragma pack(push, 1) -#endif - struct ATTR_PACKED HeaderStruct - { +#pragma pack(push, 1) +#endif + struct ATTR_PACKED HeaderStruct { seq_nr_t seq_nr; sender_id_t sender_id; mux_t mux; }; #ifdef _MSC_VER - #pragma pack(pop) +#pragma pack(pop) #endif struct HeaderStruct* header_; - u_int8_t * payload_; - u_int8_t * auth_tag_; - u_int32_t auth_tag_length_; + uint8_t* payload_; + uint8_t* auth_tag_; + uint32_t auth_tag_length_; }; #endif diff --git a/src/endian.h b/src/endian.h index 75646e7..498db4d 100644 --- a/src/endian.h +++ b/src/endian.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/keyDerivation.cpp b/src/keyDerivation.cpp index 25b7cf0..17d2a7c 100644 --- a/src/keyDerivation.cpp +++ b/src/keyDerivation.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -61,7 +61,7 @@ void KeyDerivation::setRole(const role_t role) #ifndef NO_CRYPT #ifndef NO_PASSPHRASE -void KeyDerivation::calcMasterKey(std::string passphrase, u_int16_t length) +void KeyDerivation::calcMasterKey(std::string passphrase, uint16_t length) { cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: calculating master key from passphrase"; if(!length) { @@ -79,10 +79,10 @@ void KeyDerivation::calcMasterKey(std::string passphrase, u_int16_t length) } #ifndef USE_SSL_CRYPTO - Buffer digest(static_cast(gcry_md_get_algo_dlen(GCRY_MD_SHA256))); + Buffer digest(static_cast(gcry_md_get_algo_dlen(GCRY_MD_SHA256))); gcry_md_hash_buffer(GCRY_MD_SHA256, digest.getBuf(), passphrase.c_str(), passphrase.length()); #else - Buffer digest(u_int32_t(SHA256_DIGEST_LENGTH)); + Buffer digest(uint32_t(SHA256_DIGEST_LENGTH)); SHA256(reinterpret_cast(passphrase.c_str()), passphrase.length(), digest.getBuf()); #endif master_key_.setLength(length); @@ -90,7 +90,7 @@ void KeyDerivation::calcMasterKey(std::string passphrase, u_int16_t length) std::memcpy(master_key_.getBuf(), &digest.getBuf()[digest.getLength() - master_key_.getLength()], master_key_.getLength()); } -void KeyDerivation::calcMasterSalt(std::string passphrase, u_int16_t length) +void KeyDerivation::calcMasterSalt(std::string passphrase, uint16_t length) { cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: calculating master salt from passphrase"; if(!length) { @@ -108,10 +108,10 @@ void KeyDerivation::calcMasterSalt(std::string passphrase, u_int16_t length) } #ifndef USE_SSL_CRYPTO - Buffer digest(static_cast(gcry_md_get_algo_dlen(GCRY_MD_SHA1))); + Buffer digest(static_cast(gcry_md_get_algo_dlen(GCRY_MD_SHA1))); gcry_md_hash_buffer(GCRY_MD_SHA1, digest.getBuf(), passphrase.c_str(), passphrase.length()); #else - Buffer digest(u_int32_t(SHA_DIGEST_LENGTH)); + Buffer digest(uint32_t(SHA_DIGEST_LENGTH)); SHA1(reinterpret_cast(passphrase.c_str()), passphrase.length(), digest.getBuf()); #endif master_salt_.setLength(length); @@ -126,34 +126,31 @@ satp_prf_label_t KeyDerivation::convertLabel(kd_dir_t dir, satp_prf_label_t labe switch(label) { case LABEL_ENC: { if(dir == KD_OUTBOUND) { - if(role_ == ROLE_LEFT) return LABEL_LEFT_ENC; - if(role_ == ROLE_RIGHT) return LABEL_RIGHT_ENC; - } - else { - if(role_ == ROLE_LEFT) return LABEL_RIGHT_ENC; - if(role_ == ROLE_RIGHT) return LABEL_LEFT_ENC; + if(role_ == ROLE_LEFT) { return LABEL_LEFT_ENC; } + if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_ENC; } + } else { + if(role_ == ROLE_LEFT) { return LABEL_RIGHT_ENC; } + if(role_ == ROLE_RIGHT) { return LABEL_LEFT_ENC; } } break; } case LABEL_SALT: { if(dir == KD_OUTBOUND) { - if(role_ == ROLE_LEFT) return LABEL_LEFT_SALT; - if(role_ == ROLE_RIGHT) return LABEL_RIGHT_SALT; - } - else { - if(role_ == ROLE_LEFT) return LABEL_RIGHT_SALT; - if(role_ == ROLE_RIGHT) return LABEL_LEFT_SALT; + if(role_ == ROLE_LEFT) { return LABEL_LEFT_SALT; } + if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_SALT; } + } else { + if(role_ == ROLE_LEFT) { return LABEL_RIGHT_SALT; } + if(role_ == ROLE_RIGHT) { return LABEL_LEFT_SALT; } } break; } case LABEL_AUTH: { if(dir == KD_OUTBOUND) { - if(role_ == ROLE_LEFT) return LABEL_LEFT_AUTH; - if(role_ == ROLE_RIGHT) return LABEL_RIGHT_AUTH; - } - else { - if(role_ == ROLE_LEFT) return LABEL_RIGHT_AUTH; - if(role_ == ROLE_RIGHT) return LABEL_LEFT_AUTH; + if(role_ == ROLE_LEFT) { return LABEL_LEFT_AUTH; } + if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_AUTH; } + } else { + if(role_ == ROLE_LEFT) { return LABEL_RIGHT_AUTH; } + if(role_ == ROLE_RIGHT) { return LABEL_LEFT_AUTH; } } break; } @@ -173,19 +170,21 @@ bool NullKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t #ifndef NO_CRYPT //****** AesIcmKeyDerivation ****** -AesIcmKeyDerivation::AesIcmKeyDerivation() : KeyDerivation(DEFAULT_KEY_LENGTH) +AesIcmKeyDerivation::AesIcmKeyDerivation() : KeyDerivation(DEFAULT_KEY_LENGTH) { #ifndef USE_SSL_CRYPTO - for(int i=0; i<2; i++) + for(int i=0; i<2; i++) { handle_[i] = NULL; + } #endif } -AesIcmKeyDerivation::AesIcmKeyDerivation(u_int16_t key_length) : KeyDerivation(key_length) +AesIcmKeyDerivation::AesIcmKeyDerivation(uint16_t key_length) : KeyDerivation(key_length) { #ifndef USE_SSL_CRYPTO - for(int i=0; i<2; i++) + for(int i=0; i<2; i++) { handle_[i] = NULL; + } #endif } @@ -194,8 +193,9 @@ AesIcmKeyDerivation::~AesIcmKeyDerivation() WritersLock lock(mutex_); #ifndef USE_SSL_CRYPTO for(int i=0; i<2; i++) - if(handle_[i]) + if(handle_[i]) { gcry_cipher_close(handle_[i]); + } #endif } @@ -205,15 +205,17 @@ void AesIcmKeyDerivation::init(Buffer key, Buffer salt, std::string passphrase) is_initialized_ = false; #ifndef NO_PASSPHRASE - if(passphrase != "" && !key.getLength()) + if(passphrase != "" && !key.getLength()) { calcMasterKey(passphrase, key_length_/8); - else + } else { master_key_ = SyncBuffer(key); - - if(passphrase != "" && !salt.getLength()) + } + + if(passphrase != "" && !salt.getLength()) { calcMasterSalt(passphrase, SALT_LENGTH); - else + } else { master_salt_ = SyncBuffer(salt); + } #else master_key_ = SyncBuffer(key); master_salt_ = SyncBuffer(salt); @@ -237,9 +239,15 @@ void AesIcmKeyDerivation::updateMasterKey() #ifndef USE_SSL_CRYPTO int algo; switch(key_length_) { - case 128: algo = GCRY_CIPHER_AES128; break; - case 192: algo = GCRY_CIPHER_AES192; break; - case 256: algo = GCRY_CIPHER_AES256; break; + case 128: + algo = GCRY_CIPHER_AES128; + break; + case 192: + algo = GCRY_CIPHER_AES192; + break; + case 256: + algo = GCRY_CIPHER_AES256; + break; default: { cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: cipher key length of " << key_length_ << " Bits is not supported"; return; @@ -247,15 +255,16 @@ void AesIcmKeyDerivation::updateMasterKey() } for(int i=0; i<2; i++) { - if(handle_[i]) + if(handle_[i]) { gcry_cipher_close(handle_[i]); - + } + gcry_error_t err = gcry_cipher_open(&handle_[i], algo, GCRY_CIPHER_MODE_CTR, 0); if(err) { cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to open cipher: " << AnytunGpgError(err); return; - } - + } + err = gcry_cipher_setkey(handle_[i], master_key_.getBuf(), master_key_.getLength()); if(err) { cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to set cipher key: " << AnytunGpgError(err); @@ -274,7 +283,7 @@ void AesIcmKeyDerivation::updateMasterKey() is_initialized_ = true; } -std::string AesIcmKeyDerivation::printType() +std::string AesIcmKeyDerivation::printType() { ReadersLock lock(mutex_); @@ -297,17 +306,18 @@ bool AesIcmKeyDerivation::calcCtr(kd_dir_t dir, satp_prf_label_t label, seq_nr_t return true; } -bool AesIcmKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key) +bool AesIcmKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key) { ReadersLock lock(mutex_); - if(!is_initialized_) + if(!is_initialized_) { return false; + } if(!calcCtr(dir, label, seq_nr)) { return false; } - + #ifndef USE_SSL_CRYPTO gcry_error_t err = gcry_cipher_reset(handle_[dir]); if(err) { @@ -335,7 +345,7 @@ bool AesIcmKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_ std::memset(key.getBuf(), 0, key.getLength()); AES_ctr128_encrypt(key.getBuf(), key.getBuf(), key.getLength(), &aes_key_[dir], ctr_[dir].buf_, ecount_buf_[dir], &num); #endif - + return true; } #endif diff --git a/src/keyDerivation.h b/src/keyDerivation.h index eea4266..f34499c 100644 --- a/src/keyDerivation.h +++ b/src/keyDerivation.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -67,7 +67,7 @@ class KeyDerivation { public: KeyDerivation() : is_initialized_(false), role_(ROLE_LEFT), key_length_(0), master_salt_(0), master_key_(0) {}; - KeyDerivation(u_int16_t key_length) : is_initialized_(false), role_(ROLE_LEFT), key_length_(key_length), master_salt_(0), master_key_(0) {}; + KeyDerivation(uint16_t key_length) : is_initialized_(false), role_(ROLE_LEFT), key_length_(key_length), master_salt_(0), master_key_(0) {}; virtual ~KeyDerivation() {}; void setRole(const role_t role); @@ -77,39 +77,38 @@ public: virtual std::string printType() { return "GenericKeyDerivation"; }; - satp_prf_label_t convertLabel(kd_dir_t dir, satp_prf_label_t label); + satp_prf_label_t convertLabel(kd_dir_t dir, satp_prf_label_t label); protected: virtual void updateMasterKey() = 0; - + #ifndef NO_PASSPHRASE - void calcMasterKey(std::string passphrase, u_int16_t length); - void calcMasterSalt(std::string passphrase, u_int16_t length); + void calcMasterKey(std::string passphrase, uint16_t length); + void calcMasterSalt(std::string passphrase, uint16_t length); #endif - KeyDerivation(const KeyDerivation & src); - friend class boost::serialization::access; - template - void serialize(Archive & ar, const unsigned int version) - { - WritersLock lock(mutex_); - ar & role_; - ar & key_length_; - ar & master_salt_; - ar & master_key_; + KeyDerivation(const KeyDerivation& src); + friend class boost::serialization::access; + template + void serialize(Archive& ar, const unsigned int version) { + WritersLock lock(mutex_); + ar& role_; + ar& key_length_; + ar& master_salt_; + ar& master_key_; updateMasterKey(); - } + } bool is_initialized_; role_t role_; - u_int16_t key_length_; + uint16_t key_length_; SyncBuffer master_salt_; SyncBuffer master_key_; SharedMutex mutex_; }; -#if BOOST_VERSION <= 103500 +#if BOOST_VERSION <= 103500 BOOST_IS_ABSTRACT(KeyDerivation); #else BOOST_SERIALIZATION_ASSUME_ABSTRACT(KeyDerivation); @@ -131,12 +130,11 @@ public: private: void updateMasterKey() {}; - friend class boost::serialization::access; - template - void serialize(Archive & ar, const unsigned int version) - { - ar & boost::serialization::base_object(*this); - } + friend class boost::serialization::access; + template + void serialize(Archive& ar, const unsigned int version) { + ar& boost::serialization::base_object(*this); + } }; @@ -147,13 +145,13 @@ class AesIcmKeyDerivation : public KeyDerivation { public: AesIcmKeyDerivation(); - AesIcmKeyDerivation(u_int16_t key_length); + AesIcmKeyDerivation(uint16_t key_length); ~AesIcmKeyDerivation(); - static const u_int16_t DEFAULT_KEY_LENGTH = 128; - static const u_int16_t CTR_LENGTH = 16; - static const u_int16_t SALT_LENGTH = 14; - + static const uint16_t DEFAULT_KEY_LENGTH = 128; + static const uint16_t CTR_LENGTH = 16; + static const uint16_t SALT_LENGTH = 14; + void init(Buffer key, Buffer salt, std::string passphrase = ""); bool generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key); @@ -164,38 +162,37 @@ private: bool calcCtr(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr); - friend class boost::serialization::access; - template - void serialize(Archive & ar, const unsigned int version) - { - ar & boost::serialization::base_object(*this); - } + friend class boost::serialization::access; + template + void serialize(Archive& ar, const unsigned int version) { + ar& boost::serialization::base_object(*this); + } #ifndef USE_SSL_CRYPTO gcry_cipher_hd_t handle_[2]; #else AES_KEY aes_key_[2]; - u_int8_t ecount_buf_[2][AES_BLOCK_SIZE]; + uint8_t ecount_buf_[2][AES_BLOCK_SIZE]; #endif #ifdef _MSC_VER - #pragma pack(push, 1) -#endif +#pragma pack(push, 1) +#endif union ATTR_PACKED key_derivation_aesctr_ctr_union { - u_int8_t buf_[CTR_LENGTH]; + uint8_t buf_[CTR_LENGTH]; struct ATTR_PACKED { - u_int8_t buf_[SALT_LENGTH]; - u_int16_t zero_; + uint8_t buf_[SALT_LENGTH]; + uint16_t zero_; } salt_; struct ATTR_PACKED { - u_int8_t fill_[SALT_LENGTH - sizeof(satp_prf_label_t) - sizeof(seq_nr_t)]; + uint8_t fill_[SALT_LENGTH - sizeof(satp_prf_label_t) - sizeof(seq_nr_t)]; satp_prf_label_t label_; seq_nr_t seq_; - u_int16_t zero_; + uint16_t zero_; } params_; } ctr_[2]; -#ifdef _MSC_VER - #pragma pack(pop) +#ifdef _MSC_VER +#pragma pack(pop) #endif }; diff --git a/src/keyDerivationFactory.cpp b/src/keyDerivationFactory.cpp index d325c35..a4cbf1c 100644 --- a/src/keyDerivationFactory.cpp +++ b/src/keyDerivationFactory.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -39,19 +39,22 @@ KeyDerivation* KeyDerivationFactory::create(std::string const& type) { - if(type == "null") + if(type == "null") { return new NullKeyDerivation(); + } #ifndef NO_CRYPT - else if(type == "aes-ctr") + else if(type == "aes-ctr") { return new AesIcmKeyDerivation(); - else if(type == "aes-ctr-128") + } else if(type == "aes-ctr-128") { return new AesIcmKeyDerivation(128); - else if(type == "aes-ctr-192") + } else if(type == "aes-ctr-192") { return new AesIcmKeyDerivation(192); - else if(type == "aes-ctr-256") + } else if(type == "aes-ctr-256") { return new AesIcmKeyDerivation(256); + } #endif - else + else { throw std::invalid_argument("key derivation prf not available"); + } } diff --git a/src/keyDerivationFactory.h b/src/keyDerivationFactory.h index caafe7e..fc11a4d 100644 --- a/src/keyDerivationFactory.h +++ b/src/keyDerivationFactory.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/linux/tunDevice.cpp b/src/linux/tunDevice.cpp index ee6ac0e..94c2e27 100644 --- a/src/linux/tunDevice.cpp +++ b/src/linux/tunDevice.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -50,110 +50,116 @@ #include "anytunError.h" #include "sysExec.h" -TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, u_int16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400), sys_exec_(NULL) +TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400), sys_exec_(NULL) { - struct ifreq ifr; - memset(&ifr, 0, sizeof(ifr)); + struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); if(conf_.type_ == TYPE_TUN) { ifr.ifr_flags = IFF_TUN; with_pi_ = true; - } - else if(conf_.type_ == TYPE_TAP) { + } else if(conf_.type_ == TYPE_TAP) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; with_pi_ = false; - } - else + } else { AnytunError::throwErr() << "unable to recognize type of device (tun or tap)"; + } - if(dev_name != "") - strncpy(ifr.ifr_name, dev_name.c_str(), IFNAMSIZ); + if(dev_name != "") { + strncpy(ifr.ifr_name, dev_name.c_str(), IFNAMSIZ); + } - fd_ = ::open(DEFAULT_DEVICE, O_RDWR); - if(fd_ < 0) + fd_ = ::open(DEFAULT_DEVICE, O_RDWR); + if(fd_ < 0) { AnytunError::throwErr() << "can't open device file (" << DEFAULT_DEVICE << "): " << AnytunErrno(errno); + } - if(!ioctl(fd_, TUNSETIFF, &ifr)) { - actual_name_ = ifr.ifr_name; - } else if(!ioctl(fd_, (('T' << 8) | 202), &ifr)) { - actual_name_ = ifr.ifr_name; - } else { + if(!ioctl(fd_, TUNSETIFF, &ifr)) { + actual_name_ = ifr.ifr_name; + } else if(!ioctl(fd_, (('T' << 8) | 202), &ifr)) { + actual_name_ = ifr.ifr_name; + } else { ::close(fd_); AnytunError::throwErr() << "tun/tap device ioctl failed: " << AnytunErrno(errno); } actual_node_ = DEFAULT_DEVICE; - if(ifcfg_addr != "") + if(ifcfg_addr != "") { do_ifconfig(); + } } TunDevice::~TunDevice() { - if(fd_ > 0) + if(fd_ > 0) { ::close(fd_); + } } int TunDevice::fix_return(int ret, size_t pi_length) const { - if(ret < 0) + if(ret < 0) { return ret; + } return (static_cast(ret) > pi_length ? (ret - pi_length) : 0); } -int TunDevice::read(u_int8_t* buf, u_int32_t len) +int TunDevice::read(uint8_t* buf, uint32_t len) { - if(fd_ < 0) + if(fd_ < 0) { return -1; + } - if(with_pi_) - { + if(with_pi_) { struct iovec iov[2]; struct tun_pi tpi; - + iov[0].iov_base = &tpi; iov[0].iov_len = sizeof(tpi); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::readv(fd_, iov, 2), sizeof(tpi))); - } - else + } else { return(::read(fd_, buf, len)); + } } -int TunDevice::write(u_int8_t* buf, u_int32_t len) +int TunDevice::write(uint8_t* buf, uint32_t len) { - if(fd_ < 0) + if(fd_ < 0) { return -1; + } - if(!buf) + if(!buf) { return 0; + } - if(with_pi_) - { + if(with_pi_) { struct iovec iov[2]; struct tun_pi tpi; - struct iphdr *hdr = reinterpret_cast(buf); - + struct iphdr* hdr = reinterpret_cast(buf); + tpi.flags = 0; - if(hdr->version == 4) + if(hdr->version == 4) { tpi.proto = htons(ETH_P_IP); - else + } else { tpi.proto = htons(ETH_P_IPV6); - + } + iov[0].iov_base = &tpi; iov[0].iov_len = sizeof(tpi); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::writev(fd_, iov, 2), sizeof(tpi))); - } - else + } else { return(::write(fd_, buf, len)); + } } void TunDevice::init_post() { -// nothing to be done here + // nothing to be done here } void TunDevice::do_ifconfig() @@ -166,6 +172,7 @@ void TunDevice::do_ifconfig() void TunDevice::waitUntilReady() { - if(sys_exec_) + if(sys_exec_) { SysExec::waitAndDestroy(sys_exec_); + } } diff --git a/src/log.cpp b/src/log.cpp index d1049b2..9924d7f 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,17 +40,17 @@ Log* Log::inst = NULL; Mutex Log::instMutex; Log& cLog = Log::instance(); -LogStringBuilder::LogStringBuilder(LogStringBuilder const& src) : log(src.log), prio(src.prio) +LogStringBuilder::LogStringBuilder(LogStringBuilder const& src) : log(src.log), prio(src.prio) { stream << src.stream.str(); } -LogStringBuilder::LogStringBuilder(Log& l, int p) : log(l), prio(p) +LogStringBuilder::LogStringBuilder(Log& l, int p) : log(l), prio(p) { - // do something on the start of the line. + // do something on the start of the line. } -LogStringBuilder::~LogStringBuilder() +LogStringBuilder::~LogStringBuilder() { log.log(stream.str(), prio); } @@ -59,9 +59,10 @@ Log& Log::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new Log(); - + } + return *inst; } @@ -70,8 +71,9 @@ void Log::addTarget(std::string conf) Lock lock(mutex); LogTarget* target = targets.add(conf); target->open(); - if(target->getMaxPrio() > 0) + if(target->getMaxPrio() > 0) { target->enable(); + } } void Log::addTarget(LogTargetList::target_type_t type, int prio, std::string conf) @@ -79,8 +81,9 @@ void Log::addTarget(LogTargetList::target_type_t type, int prio, std::string con Lock lock(mutex); LogTarget* target = targets.add(type, prio, conf); target->open(); - if(target->getMaxPrio() > 0) + if(target->getMaxPrio() > 0) { target->enable(); + } } void Log::log(std::string msg, int prio) @@ -92,11 +95,17 @@ void Log::log(std::string msg, int prio) std::string Log::prioToString(int prio) { switch(prio) { - case PRIO_ERROR: return "ERROR"; - case PRIO_WARNING: return "WARNING"; - case PRIO_NOTICE: return "NOTICE"; - case PRIO_INFO: return "INFO"; - case PRIO_DEBUG: return "DEBUG"; - default: return "UNKNOWN"; + case PRIO_ERROR: + return "ERROR"; + case PRIO_WARNING: + return "WARNING"; + case PRIO_NOTICE: + return "NOTICE"; + case PRIO_INFO: + return "INFO"; + case PRIO_DEBUG: + return "DEBUG"; + default: + return "UNKNOWN"; } } diff --git a/src/log.h b/src/log.h index 8ff24e3..12c723d 100644 --- a/src/log.h +++ b/src/log.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -41,7 +41,7 @@ class Log; -class LogStringBuilder +class LogStringBuilder { public: LogStringBuilder(LogStringBuilder const& src); @@ -77,15 +77,18 @@ public: private: Log() {}; ~Log() {}; - Log(const Log &l); - void operator=(const Log &l); + Log(const Log& l); + void operator=(const Log& l); static Log* inst; static Mutex instMutex; - class instanceCleaner { - public: ~instanceCleaner() { - if(Log::inst != 0) + class instanceCleaner + { + public: + ~instanceCleaner() { + if(Log::inst != 0) { delete Log::inst; + } } }; friend class instanceCleaner; diff --git a/src/logTargets.cpp b/src/logTargets.cpp index 5b19954..487ee8b 100644 --- a/src/logTargets.cpp +++ b/src/logTargets.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -62,23 +62,29 @@ LogTargetList::~LogTargetList() LogTargetList::target_type_t LogTargetList::targetTypeFromString(std::string type) { - if(type == "syslog") return TARGET_SYSLOG; - if(type == "file") return TARGET_FILE; - if(type == "stdout") return TARGET_STDOUT; - if(type == "stderr") return TARGET_STDERR; - if(type == "eventlog") return TARGET_WINEVENTLOG; + if(type == "syslog") { return TARGET_SYSLOG; } + if(type == "file") { return TARGET_FILE; } + if(type == "stdout") { return TARGET_STDOUT; } + if(type == "stderr") { return TARGET_STDERR; } + if(type == "eventlog") { return TARGET_WINEVENTLOG; } return TARGET_UNKNOWN; } std::string LogTargetList::targetTypeToString(target_type_t type) { switch(type) { - case TARGET_SYSLOG: return "syslog"; - case TARGET_FILE: return "file"; - case TARGET_STDOUT: return "stdout"; - case TARGET_STDERR: return "stderr"; - case TARGET_WINEVENTLOG: return "eventlog"; - default: return "unknown"; + case TARGET_SYSLOG: + return "syslog"; + case TARGET_FILE: + return "file"; + case TARGET_STDOUT: + return "stdout"; + case TARGET_STDERR: + return "stderr"; + case TARGET_WINEVENTLOG: + return "eventlog"; + default: + return "unknown"; } } @@ -87,23 +93,26 @@ LogTarget* LogTargetList::add(std::string conf) std::stringstream s(conf); std::string type; getline(s, type, ':'); - if(!s.good()) + if(!s.good()) { throw syntax_error(conf, 0); + } int prio = Log::PRIO_NOTICE; s >> prio; - if(s.fail()) + if(s.fail()) { throw syntax_error(conf, conf.find_first_of(':')+1); + } char buff[100]; if(s.good()) { s.get(buff[0]); - if(buff[0] != ',') + if(buff[0] != ',') { throw syntax_error(conf, (s.tellg() > 0) ? static_cast(s.tellg()) - 1 : 0); + } s.get(buff, 100); - } - else + } else { buff[0] = 0; + } return add(targetTypeFromString(type), prio, buff); } @@ -112,50 +121,55 @@ LogTarget* LogTargetList::add(target_type_t type, int prio, std::string conf) { switch(type) { case TARGET_SYSLOG: { - #ifdef LOG_SYSLOG - if(!LogTargetSyslog::duplicateAllowed() && targets.count(TARGET_SYSLOG)) +#ifdef LOG_SYSLOG + if(!LogTargetSyslog::duplicateAllowed() && targets.count(TARGET_SYSLOG)) { AnytunError::throwErr() << targetTypeToString(TARGET_SYSLOG) << " logtarget is supported only once"; + } return targets.insert(TargetsMap::value_type(TARGET_SYSLOG, new LogTargetSyslog(prio, conf)))->second; - #else +#else AnytunError::throwErr() << targetTypeToString(TARGET_SYSLOG) << " logtarget is not supported"; - #endif +#endif } case TARGET_FILE: { - #ifdef LOG_FILE - if(!LogTargetFile::duplicateAllowed() && targets.count(TARGET_FILE)) +#ifdef LOG_FILE + if(!LogTargetFile::duplicateAllowed() && targets.count(TARGET_FILE)) { AnytunError::throwErr() << targetTypeToString(TARGET_FILE) << " logtarget is supported only once"; + } return targets.insert(TargetsMap::value_type(TARGET_FILE, new LogTargetFile(prio, conf)))->second; - #else +#else AnytunError::throwErr() << targetTypeToString(TARGET_FILE) << " logtarget is not supported"; - #endif +#endif } - case TARGET_STDOUT: + case TARGET_STDOUT: case TARGET_STDERR: { - #ifdef LOG_STDOUT - if(!LogTargetStdout::duplicateAllowed() && targets.count(type)) +#ifdef LOG_STDOUT + if(!LogTargetStdout::duplicateAllowed() && targets.count(type)) { AnytunError::throwErr() << targetTypeToString(type) << " logtarget is supported only once"; - - if(type == TARGET_STDERR) + } + + if(type == TARGET_STDERR) { return targets.insert(TargetsMap::value_type(type, new LogTargetStdout(prio, std::cerr)))->second; - else + } else { return targets.insert(TargetsMap::value_type(type, new LogTargetStdout(prio, std::cout)))->second; - #else + } +#else AnytunError::throwErr() << targetTypeToString(type) + " logtarget is not supported"; - #endif +#endif } case TARGET_WINEVENTLOG: { - #ifdef LOG_WINEVENTLOG - if(!LogTargetWinEventlog::duplicateAllowed() && targets.count(TARGET_WINEVENTLOG)) +#ifdef LOG_WINEVENTLOG + if(!LogTargetWinEventlog::duplicateAllowed() && targets.count(TARGET_WINEVENTLOG)) { AnytunError::throwErr() << targetTypeToString(TARGET_WINEVENTLOG) << " logtarget is supported only once"; + } return targets.insert(TargetsMap::value_type(TARGET_WINEVENTLOG, new LogTargetWinEventlog(prio, conf)))->second; - #else +#else AnytunError::throwErr() << targetTypeToString(TARGET_WINEVENTLOG) << " logtarget is not supported"; - #endif +#endif } - default: + default: AnytunError::throwErr() << "unknown log target"; } return NULL; @@ -164,17 +178,19 @@ LogTarget* LogTargetList::add(target_type_t type, int prio, std::string conf) void LogTargetList::clear() { TargetsMap::iterator it; - for(it = targets.begin(); it != targets.end(); ++it) + for(it = targets.begin(); it != targets.end(); ++it) { delete it->second; + } targets.clear(); } - + void LogTargetList::log(std::string msg, int prio) { TargetsMap::const_iterator it; for(it = targets.begin(); it != targets.end(); ++it) { - if(it->second->isEnabled() && it->second->getMaxPrio() >= prio) + if(it->second->isEnabled() && it->second->getMaxPrio() >= prio) { it->second->log(msg, prio); + } } } @@ -182,26 +198,26 @@ void LogTargetList::log(std::string msg, int prio) #ifdef LOG_SYSLOG int LogTargetSyslog::facilityFromString(std::string fac) { - if(fac == "user") return FAC_USER; - if(fac == "mail") return FAC_MAIL; - if(fac == "daemon") return FAC_DAEMON; - if(fac == "auth") return FAC_AUTH; - if(fac == "syslog") return FAC_SYSLOG; - if(fac == "lpr") return FAC_LPR; - if(fac == "news") return FAC_NEWS; - if(fac == "uucp") return FAC_UUCP; - if(fac == "cron") return FAC_CRON; - if(fac == "authpriv") return FAC_AUTHPRIV; - if(fac == "ftp") return FAC_FTP; - if(fac == "local0") return FAC_LOCAL0; - if(fac == "local1") return FAC_LOCAL1; - if(fac == "local2") return FAC_LOCAL2; - if(fac == "local3") return FAC_LOCAL3; - if(fac == "local4") return FAC_LOCAL4; - if(fac == "local5") return FAC_LOCAL5; - if(fac == "local6") return FAC_LOCAL6; - if(fac == "local7") return FAC_LOCAL7; - + if(fac == "user") { return FAC_USER; } + if(fac == "mail") { return FAC_MAIL; } + if(fac == "daemon") { return FAC_DAEMON; } + if(fac == "auth") { return FAC_AUTH; } + if(fac == "syslog") { return FAC_SYSLOG; } + if(fac == "lpr") { return FAC_LPR; } + if(fac == "news") { return FAC_NEWS; } + if(fac == "uucp") { return FAC_UUCP; } + if(fac == "cron") { return FAC_CRON; } + if(fac == "authpriv") { return FAC_AUTHPRIV; } + if(fac == "ftp") { return FAC_FTP; } + if(fac == "local0") { return FAC_LOCAL0; } + if(fac == "local1") { return FAC_LOCAL1; } + if(fac == "local2") { return FAC_LOCAL2; } + if(fac == "local3") { return FAC_LOCAL3; } + if(fac == "local4") { return FAC_LOCAL4; } + if(fac == "local5") { return FAC_LOCAL5; } + if(fac == "local6") { return FAC_LOCAL6; } + if(fac == "local7") { return FAC_LOCAL7; } + AnytunError::throwErr() << "unknown syslog facility"; return 0; } @@ -209,26 +225,46 @@ int LogTargetSyslog::facilityFromString(std::string fac) std::string LogTargetSyslog::facilityToString(int fac) { switch(fac) { - case FAC_USER: return "user"; - case FAC_MAIL: return "mail"; - case FAC_DAEMON: return "daemon"; - case FAC_AUTH: return "auth"; - case FAC_SYSLOG: return "syslog"; - case FAC_LPR: return "lpr"; - case FAC_NEWS: return "news"; - case FAC_UUCP: return "uucp"; - case FAC_CRON: return "cron"; - case FAC_AUTHPRIV: return "authpriv"; - case FAC_FTP: return "ftp"; - case FAC_LOCAL0: return "local0"; - case FAC_LOCAL1: return "local1"; - case FAC_LOCAL2: return "local2"; - case FAC_LOCAL3: return "local3"; - case FAC_LOCAL4: return "local4"; - case FAC_LOCAL5: return "local5"; - case FAC_LOCAL6: return "local6"; - case FAC_LOCAL7: return "local7"; - default: AnytunError::throwErr() << "unknown syslog facility"; + case FAC_USER: + return "user"; + case FAC_MAIL: + return "mail"; + case FAC_DAEMON: + return "daemon"; + case FAC_AUTH: + return "auth"; + case FAC_SYSLOG: + return "syslog"; + case FAC_LPR: + return "lpr"; + case FAC_NEWS: + return "news"; + case FAC_UUCP: + return "uucp"; + case FAC_CRON: + return "cron"; + case FAC_AUTHPRIV: + return "authpriv"; + case FAC_FTP: + return "ftp"; + case FAC_LOCAL0: + return "local0"; + case FAC_LOCAL1: + return "local1"; + case FAC_LOCAL2: + return "local2"; + case FAC_LOCAL3: + return "local3"; + case FAC_LOCAL4: + return "local4"; + case FAC_LOCAL5: + return "local5"; + case FAC_LOCAL6: + return "local6"; + case FAC_LOCAL7: + return "local7"; + default: + AnytunError::throwErr() << "unknown syslog facility"; } return ""; } @@ -244,16 +280,18 @@ LogTargetSyslog::LogTargetSyslog(int prio, std::string conf) : LogTarget(prio) } std::string fac; getline(s, fac, ','); - if(s.fail()) + if(s.fail()) { return; + } facility = LogTargetSyslog::facilityFromString(fac); } LogTargetSyslog::~LogTargetSyslog() { - if(opened) + if(opened) { close(); + } } void LogTargetSyslog::open() @@ -270,17 +308,19 @@ void LogTargetSyslog::close() void LogTargetSyslog::log(std::string msg, int prio) { - if(!opened) + if(!opened) { return; + } - syslog((prio + 2) | facility, "%s", msg.c_str()); + syslog((prio + 2) | facility, "%s", msg.c_str()); } LogTargetSyslog& LogTargetSyslog::setLogName(std::string l) { logname = l; - if(opened) + if(opened) { close(); + } open(); return *this; } @@ -288,8 +328,9 @@ LogTargetSyslog& LogTargetSyslog::setLogName(std::string l) LogTargetSyslog& LogTargetSyslog::setFacility(int f) { facility = f; - if(opened) + if(opened) { close(); + } open(); return *this; } @@ -301,14 +342,16 @@ LogTargetFile::LogTargetFile(int prio, std::string conf) : LogTarget(prio) { std::stringstream s(conf); getline(s, logfilename, ','); - if(s.fail()) + if(s.fail()) { logfilename = "anytun.log"; + } } LogTargetFile::~LogTargetFile() { - if(opened) + if(opened) { close(); + } } void LogTargetFile::open() @@ -319,15 +362,17 @@ void LogTargetFile::open() void LogTargetFile::close() { - if(logfile.is_open()) + if(logfile.is_open()) { logfile.close(); + } opened = false; } void LogTargetFile::log(std::string msg, int prio) { - if(!opened) + if(!opened) { return; + } std::string timestamp = boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()); logfile << timestamp << " " << Log::prioToString(prio) << ": " << msg << std::endl; @@ -336,8 +381,9 @@ void LogTargetFile::log(std::string msg, int prio) LogTargetFile& LogTargetFile::setLogFilename(std::string l) { logfilename = l; - if(opened) + if(opened) { close(); + } open(); return *this; } @@ -351,8 +397,9 @@ LogTargetStdout::LogTargetStdout(int prio, std::ostream& s) : LogTarget(prio), s LogTargetStdout::~LogTargetStdout() { - if(opened) + if(opened) { close(); + } } void LogTargetStdout::open() @@ -367,8 +414,9 @@ void LogTargetStdout::close() void LogTargetStdout::log(std::string msg, int prio) { - if(!opened) + if(!opened) { return; + } std::string timestamp = boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()); stream << timestamp << " " << Log::prioToString(prio) << ": " << msg << std::endl; @@ -381,48 +429,55 @@ LogTargetWinEventlog::LogTargetWinEventlog(int prio, std::string conf) : LogTarg { std::stringstream s(conf); getline(s, logname, ','); - if(s.fail()) + if(s.fail()) { logname = "anytun"; + } } LogTargetWinEventlog::~LogTargetWinEventlog() { - if(opened) + if(opened) { close(); + } } void LogTargetWinEventlog::open() { h_event_source = RegisterEventSourceA(NULL, logname.c_str()); - if(h_event_source) + if(h_event_source) { opened = true; + } } void LogTargetWinEventlog::close() { - if(h_event_source) + if(h_event_source) { DeregisterEventSource(h_event_source); + } opened = false; } void LogTargetWinEventlog::log(std::string msg, int prio) { - if(!opened) + if(!opened) { return; + } - LPCTSTR lpszStrings[1]; + LPCTSTR lpszStrings[1]; CHAR buffer[STERROR_TEXT_MAX]; StringCchPrintfA(buffer, STERROR_TEXT_MAX, "%s", msg.c_str()); lpszStrings[0] = buffer; - if(h_event_source) + if(h_event_source) { ReportEventA(h_event_source, prioToEventLogType(prio), 0, prio, NULL, 1, 0, lpszStrings, NULL); + } } LogTargetWinEventlog& LogTargetWinEventlog::setLogName(std::string l) { logname = l; - if(opened) + if(opened) { close(); + } open(); return *this; } @@ -430,12 +485,18 @@ LogTargetWinEventlog& LogTargetWinEventlog::setLogName(std::string l) WORD LogTargetWinEventlog::prioToEventLogType(int prio) { switch(prio) { - case Log::PRIO_ERROR: return EVENTLOG_ERROR_TYPE; - case Log::PRIO_WARNING: return EVENTLOG_WARNING_TYPE; - case Log::PRIO_NOTICE: return EVENTLOG_INFORMATION_TYPE; - case Log::PRIO_INFO: return EVENTLOG_SUCCESS; - case Log::PRIO_DEBUG: return EVENTLOG_INFORMATION_TYPE; - default: return EVENTLOG_ERROR_TYPE; + case Log::PRIO_ERROR: + return EVENTLOG_ERROR_TYPE; + case Log::PRIO_WARNING: + return EVENTLOG_WARNING_TYPE; + case Log::PRIO_NOTICE: + return EVENTLOG_INFORMATION_TYPE; + case Log::PRIO_INFO: + return EVENTLOG_SUCCESS; + case Log::PRIO_DEBUG: + return EVENTLOG_INFORMATION_TYPE; + default: + return EVENTLOG_ERROR_TYPE; } } #endif diff --git a/src/logTargets.h b/src/logTargets.h index 63156c1..a42d2c6 100644 --- a/src/logTargets.h +++ b/src/logTargets.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -64,7 +64,7 @@ public: int getMaxPrio() { return max_prio; }; void setMaxPrio(int p) { max_prio = p; }; - virtual void log(std::string msg, int prio) = 0; + virtual void log(std::string msg, int prio) = 0; protected: bool opened; @@ -72,11 +72,12 @@ protected: int max_prio; }; -class LogTargetList +class LogTargetList { public: - typedef enum { TARGET_UNKNOWN, TARGET_SYSLOG, TARGET_FILE, - TARGET_STDOUT, TARGET_STDERR, TARGET_WINEVENTLOG } target_type_t; + typedef enum { TARGET_UNKNOWN, TARGET_SYSLOG, TARGET_FILE, + TARGET_STDOUT, TARGET_STDERR, TARGET_WINEVENTLOG + } target_type_t; static target_type_t targetTypeFromString(std::string type); static std::string targetTypeToString(target_type_t type); @@ -85,7 +86,7 @@ public: LogTarget* add(std::string conf); LogTarget* add(target_type_t type, int prio, std::string conf); void clear(); - + void log(std::string msg, int prio); private: @@ -126,14 +127,14 @@ public: void open(); void close(); - void log(std::string msg, int prio); + void log(std::string msg, int prio); static bool duplicateAllowed() { return false; }; - LogTargetSyslog& setLogName(std::string l); + LogTargetSyslog& setLogName(std::string l); std::string getLogName() const { return logname; } LogTargetSyslog& setFacility(int f); int getFacility() const { return facility; } - + private: std::string logname; int facility; @@ -149,12 +150,12 @@ public: void open(); void close(); - void log(std::string msg, int prio); + void log(std::string msg, int prio); static bool duplicateAllowed() { return true; }; - LogTargetFile& setLogFilename(std::string l); + LogTargetFile& setLogFilename(std::string l); std::string getLogFilename() const { return logfilename; } - + private: std::string logfilename; std::ofstream logfile; @@ -170,7 +171,7 @@ public: void open(); void close(); - void log(std::string msg, int prio); + void log(std::string msg, int prio); static bool duplicateAllowed() { return false; }; private: @@ -189,10 +190,10 @@ public: void open(); void close(); - void log(std::string msg, int prio); + void log(std::string msg, int prio); static bool duplicateAllowed() { return false; }; - LogTargetWinEventlog& setLogName(std::string l); + LogTargetWinEventlog& setLogName(std::string l); std::string getLogName() const { return logname; }; private: diff --git a/src/networkAddress.cpp b/src/networkAddress.cpp index 7701159..d489342 100644 --- a/src/networkAddress.cpp +++ b/src/networkAddress.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -39,42 +39,41 @@ NetworkAddress::NetworkAddress():ipv4_address_(),ipv6_address_() { - network_address_type_=ipv4; + network_address_type_=ipv4; } -NetworkAddress::NetworkAddress(const NetworkAddress & ref) : mutex_(),ipv4_address_(ref.ipv4_address_),ipv6_address_(ref.ipv6_address_),ethernet_address_(ref.ethernet_address_),network_address_type_(ref.network_address_type_) +NetworkAddress::NetworkAddress(const NetworkAddress& ref) : mutex_(),ipv4_address_(ref.ipv4_address_),ipv6_address_(ref.ipv6_address_),ethernet_address_(ref.ethernet_address_),network_address_type_(ref.network_address_type_) { } -NetworkAddress::NetworkAddress(const std::string & address) +NetworkAddress::NetworkAddress(const std::string& address) { - boost::asio::ip::address addr = boost::asio::ip::address::from_string(address); - if (addr.is_v4()) - { - network_address_type_=ipv4; - ipv4_address_ = addr.to_v4(); - } else { - network_address_type_=ipv6; - ipv6_address_ = addr.to_v6(); - } + boost::asio::ip::address addr = boost::asio::ip::address::from_string(address); + if(addr.is_v4()) { + network_address_type_=ipv4; + ipv4_address_ = addr.to_v4(); + } else { + network_address_type_=ipv6; + ipv6_address_ = addr.to_v6(); + } } NetworkAddress::NetworkAddress(boost::asio::ip::address_v6 ipv6_address) { - network_address_type_=ipv6; - ipv6_address_ = ipv6_address; + network_address_type_=ipv6; + ipv6_address_ = ipv6_address; } NetworkAddress::NetworkAddress(boost::asio::ip::address_v4 ipv4_address) { - network_address_type_=ipv4; - ipv4_address_ = ipv4_address; + network_address_type_=ipv4; + ipv4_address_ = ipv4_address; } -NetworkAddress::NetworkAddress(u_int64_t ethernet_address) +NetworkAddress::NetworkAddress(uint64_t ethernet_address) { - network_address_type_=ethernet; - ethernet_address_=ethernet_address; + network_address_type_=ethernet; + ethernet_address_=ethernet_address; } @@ -82,123 +81,122 @@ NetworkAddress::~NetworkAddress() { } -NetworkAddress::NetworkAddress(const network_address_type_t type, const std::string & address ) +NetworkAddress::NetworkAddress(const network_address_type_t type, const std::string& address) { - setNetworkAddress( type, address); + setNetworkAddress(type, address); } -void NetworkAddress::setNetworkAddress(const network_address_type_t type, const std::string & address ) +void NetworkAddress::setNetworkAddress(const network_address_type_t type, const std::string& address) { - if (type==ipv4) - { - ipv4_address_=boost::asio::ip::address_v4::from_string(address); - } else if (type==ipv6) { - ipv6_address_=boost::asio::ip::address_v6::from_string(address); - } else if (type==ethernet) { - //TODO - } else { - //TODO - } - network_address_type_ = type; + if(type==ipv4) { + ipv4_address_=boost::asio::ip::address_v4::from_string(address); + } else if(type==ipv6) { + ipv6_address_=boost::asio::ip::address_v6::from_string(address); + } else if(type==ethernet) { + //TODO + } else { + //TODO + } + network_address_type_ = type; } void NetworkAddress::setNetworkAddress(boost::asio::ip::address_v4 addr) { - network_address_type_=ipv4; - ipv4_address_ = addr; + network_address_type_=ipv4; + ipv4_address_ = addr; } void NetworkAddress::setNetworkAddress(boost::asio::ip::address_v6 addr) { - network_address_type_=ipv6; - ipv6_address_ = addr; + network_address_type_=ipv6; + ipv6_address_ = addr; } -void NetworkAddress::setNetworkAddress(u_int64_t addr) +void NetworkAddress::setNetworkAddress(uint64_t addr) { - network_address_type_=ethernet; - ethernet_address_=addr; + network_address_type_=ethernet; + ethernet_address_=addr; } network_address_type_t NetworkAddress::getNetworkAddressType() const { - return network_address_type_; + return network_address_type_; } const boost::asio::ip::address_v4& NetworkAddress::getNetworkAddressV4() const { - if(network_address_type_ != ipv4) + if(network_address_type_ != ipv4) { AnytunError::throwErr() << "wrong address type"; - + } + return ipv4_address_; } const boost::asio::ip::address_v6& NetworkAddress::getNetworkAddressV6() const { - if(network_address_type_ != ipv6) + if(network_address_type_ != ipv6) { AnytunError::throwErr() << "wrong address type"; - + } + return ipv6_address_; } -const u_int64_t NetworkAddress::getNetworkAdrressEther() const +const uint64_t NetworkAddress::getNetworkAdrressEther() const { - if(network_address_type_ != ethernet) + if(network_address_type_ != ethernet) { AnytunError::throwErr() << "wrong address type"; - + } + return ethernet_address_; } std::string NetworkAddress::toString() const { - if (network_address_type_==ipv4){ - return ipv4_address_.to_string(); - } - else if (network_address_type_==ipv6) { - return ipv6_address_.to_string(); - } - else if (network_address_type_==ethernet) { - // TODO - } + if(network_address_type_==ipv4) { + return ipv4_address_.to_string(); + } else if(network_address_type_==ipv6) { + return ipv6_address_.to_string(); + } else if(network_address_type_==ethernet) { + // TODO + } return std::string(""); } ipv4_bytes_type NetworkAddress::to_bytes_v4() const { - return ipv4_address_.to_bytes(); + return ipv4_address_.to_bytes(); } ipv6_bytes_type NetworkAddress::to_bytes_v6() const { - return ipv6_address_.to_bytes(); + return ipv6_address_.to_bytes(); } ethernet_bytes_type NetworkAddress::to_bytes_ethernet() const { - boost::array result; - u_int64_t ether=ethernet_address_; - for (int i = 0; i < 6; i++) - { - result[i] = (unsigned char) (ether && 0xff); - ether >>= 8; - } - return result; -} - -bool NetworkAddress::operator<(const NetworkAddress &right) const -{ - if (network_address_type_!=right.network_address_type_) - AnytunError::throwErr() << "NetworkAddress::operator<() address types don't match"; - if (network_address_type_==ipv4) - { - return (ipv4_address_ < right.ipv4_address_); - } else if (network_address_type_==ipv6) { - return (ipv6_address_ < right.ipv6_address_); - } else if (network_address_type_==ethernet) { - return (ethernet_address_ < right.ethernet_address_); - } else { - //TODO - } - return false; + boost::array result; + uint64_t ether=ethernet_address_; + for(int i = 0; i < 6; i++) { + result[i] = (unsigned char)(ether && 0xff); + ether >>= 8; + } + return result; +} + +bool NetworkAddress::operator<(const NetworkAddress& right) const +{ + if(network_address_type_!=right.network_address_type_) { + AnytunError::throwErr() << "NetworkAddress::operator<() address types don't match"; + } + if(network_address_type_==ipv4) { + return (ipv4_address_ < right.ipv4_address_); + } else if(network_address_type_==ipv6) { + return (ipv6_address_ < right.ipv6_address_); + } else if(network_address_type_==ethernet) { + return (ethernet_address_ < right.ethernet_address_); + } else { + //TODO + } + return false; } diff --git a/src/networkAddress.h b/src/networkAddress.h index dc4c7ac..1d4c602 100644 --- a/src/networkAddress.h +++ b/src/networkAddress.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -48,65 +48,62 @@ typedef boost::array ethernet_bytes_type; typedef boost::asio::ip::address_v4::bytes_type ipv4_bytes_type; typedef boost::asio::ip::address_v6::bytes_type ipv6_bytes_type; -enum network_address_type_t -{ - ipv4=0, - ipv6=1, - ethernet=2 +enum network_address_type_t { + ipv4=0, + ipv6=1, + ethernet=2 }; class NetworkAddress { public: - NetworkAddress(); - NetworkAddress(const NetworkAddress &); - NetworkAddress(const std::string &); - NetworkAddress(boost::asio::ip::address_v6); - NetworkAddress(boost::asio::ip::address_v4); - NetworkAddress(u_int64_t); - NetworkAddress(const network_address_type_t type, const std::string & address ); - ~NetworkAddress(); - void setNetworkAddress(const network_address_type_t type, const std::string & address ); - void setNetworkAddress(boost::asio::ip::address_v4); - void setNetworkAddress(boost::asio::ip::address_v6); - void setNetworkAddress(u_int64_t); - network_address_type_t getNetworkAddressType() const; + NetworkAddress(); + NetworkAddress(const NetworkAddress&); + NetworkAddress(const std::string&); + NetworkAddress(boost::asio::ip::address_v6); + NetworkAddress(boost::asio::ip::address_v4); + NetworkAddress(uint64_t); + NetworkAddress(const network_address_type_t type, const std::string& address); + ~NetworkAddress(); + void setNetworkAddress(const network_address_type_t type, const std::string& address); + void setNetworkAddress(boost::asio::ip::address_v4); + void setNetworkAddress(boost::asio::ip::address_v6); + void setNetworkAddress(uint64_t); + network_address_type_t getNetworkAddressType() const; std::string toString() const; - bool operator<(const NetworkAddress &s) const; - ipv4_bytes_type to_bytes_v4() const; - ipv6_bytes_type to_bytes_v6() const; - ethernet_bytes_type to_bytes_ethernet() const; + bool operator<(const NetworkAddress& s) const; + ipv4_bytes_type to_bytes_v4() const; + ipv6_bytes_type to_bytes_v6() const; + ethernet_bytes_type to_bytes_ethernet() const; const boost::asio::ip::address_v4& getNetworkAddressV4() const; const boost::asio::ip::address_v6& getNetworkAddressV6() const; - const u_int64_t getNetworkAdrressEther() const; + const uint64_t getNetworkAdrressEther() const; protected: Mutex mutex_; - boost::asio::ip::address_v4 ipv4_address_; - boost::asio::ip::address_v6 ipv6_address_; - u_int64_t ethernet_address_; - network_address_type_t network_address_type_; + boost::asio::ip::address_v4 ipv4_address_; + boost::asio::ip::address_v6 ipv6_address_; + uint64_t ethernet_address_; + network_address_type_t network_address_type_; private: - NetworkAddress operator=(const NetworkAddress &s); + NetworkAddress operator=(const NetworkAddress& s); friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - ar & network_address_type_; - if (network_address_type_==ipv4) - { - std::string ip(ipv4_address_.to_string()); - ar & ip; - ipv4_address_=boost::asio::ip::address_v4::from_string(ip); - } - if (network_address_type_==ipv6) - { - std::string ip(ipv6_address_.to_string()); - ar & ip; - ipv6_address_=boost::asio::ip::address_v6::from_string(ip); - } - if (network_address_type_==ethernet) - ar & ethernet_address_; - } + void serialize(Archive& ar, const unsigned int version) { + ar& network_address_type_; + if(network_address_type_==ipv4) { + std::string ip(ipv4_address_.to_string()); + ar& ip; + ipv4_address_=boost::asio::ip::address_v4::from_string(ip); + } + if(network_address_type_==ipv6) { + std::string ip(ipv6_address_.to_string()); + ar& ip; + ipv6_address_=boost::asio::ip::address_v6::from_string(ip); + } + if(network_address_type_==ethernet) { + ar& ethernet_address_; + } + } }; // for(int i=0;i<4;i++) diff --git a/src/networkPrefix.cpp b/src/networkPrefix.cpp index 31287b9..85b687d 100644 --- a/src/networkPrefix.cpp +++ b/src/networkPrefix.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,31 +40,33 @@ NetworkPrefix::NetworkPrefix(): NetworkAddress(),length_(0) { } -NetworkPrefix::NetworkPrefix(const NetworkAddress & src,u_int8_t length): NetworkAddress(src),length_(length) +NetworkPrefix::NetworkPrefix(const NetworkAddress& src,uint8_t length): NetworkAddress(src),length_(length) { } -NetworkPrefix::NetworkPrefix(const NetworkPrefix & src): NetworkAddress(src),length_(src.length_) +NetworkPrefix::NetworkPrefix(const NetworkPrefix& src): NetworkAddress(src),length_(src.length_) { } -void NetworkPrefix::setNetworkPrefixLength(u_int8_t length ) +void NetworkPrefix::setNetworkPrefixLength(uint8_t length) { - length_ = length; + length_ = length; } -u_int8_t NetworkPrefix::getNetworkPrefixLength() const +uint8_t NetworkPrefix::getNetworkPrefixLength() const { - return length_; + return length_; } -bool NetworkPrefix::operator<(const NetworkPrefix &right) const +bool NetworkPrefix::operator<(const NetworkPrefix& right) const { - if (network_address_type_!=right.network_address_type_) - return false; - if (right.length_!=length_) - return (length_(*this)(right); + if(network_address_type_!=right.network_address_type_) { + return false; + } + if(right.length_!=length_) { + return (length_(*this)(right); } diff --git a/src/networkPrefix.h b/src/networkPrefix.h index 1c023ed..2c328a7 100644 --- a/src/networkPrefix.h +++ b/src/networkPrefix.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,23 +43,22 @@ class NetworkPrefix : public NetworkAddress { public: - NetworkPrefix(); - NetworkPrefix(const NetworkAddress &, u_int8_t length); - NetworkPrefix(const NetworkPrefix &); - void setNetworkPrefixLength(u_int8_t length ); - u_int8_t getNetworkPrefixLength() const; - bool operator<(const NetworkPrefix &s) const; + NetworkPrefix(); + NetworkPrefix(const NetworkAddress&, uint8_t length); + NetworkPrefix(const NetworkPrefix&); + void setNetworkPrefixLength(uint8_t length); + uint8_t getNetworkPrefixLength() const; + bool operator<(const NetworkPrefix& s) const; private: - operator NetworkAddress(); - void operator=(const NetworkPrefix &s); - u_int8_t length_; + operator NetworkAddress(); + void operator=(const NetworkPrefix& s); + uint8_t length_; friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - ar & length_; - ar & boost::serialization::base_object(*this); + void serialize(Archive& ar, const unsigned int version) { + ar& length_; + ar& boost::serialization::base_object(*this); }; }; diff --git a/src/nullDaemon.cpp b/src/nullDaemon.cpp index 5c1235c..8adcb50 100644 --- a/src/nullDaemon.cpp +++ b/src/nullDaemon.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -34,22 +34,22 @@ void DaemonService::initPrivs(std::string const& username, std::string const& groupname) { -// nothing here + // nothing here } void DaemonService::dropPrivs() { -// nothing here + // nothing here } void DaemonService::chroot(std::string const& chrootdir) { -// nothing here + // nothing here } void DaemonService::daemonize() { -// nothing here + // nothing here } bool DaemonService::isDaemonized() diff --git a/src/nullDaemon.h b/src/nullDaemon.h index 379b300..7f5ec5a 100644 --- a/src/nullDaemon.h +++ b/src/nullDaemon.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/options.cpp b/src/options.cpp index 5d70751..9682873 100644 --- a/src/options.cpp +++ b/src/options.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -48,7 +48,7 @@ std::ostream& operator<<(std::ostream& stream, syntax_error const& error) stream << "syntax error: " << error.what() << std::endl; if(error.pos >= 0) { stream << " "; - for(int32_t i = 0; i < error.pos; ++i) stream << " "; + for(int32_t i = 0; i < error.pos; ++i) { stream << " "; } return stream << "^"; } return stream; @@ -57,10 +57,16 @@ std::ostream& operator<<(std::ostream& stream, syntax_error const& error) std::ostream& operator<<(std::ostream& stream, role_t const& role) { switch(role) { - case ROLE_LEFT: stream << "left"; break; - case ROLE_RIGHT: stream << "right"; break; - default: stream << "unknown"; break; - } + case ROLE_LEFT: + stream << "left"; + break; + case ROLE_RIGHT: + stream << "right"; + break; + default: + stream << "unknown"; + break; + } return stream; } @@ -69,30 +75,32 @@ void OptionHost::init(std::string addrPort) std::string origAddrPort(addrPort); size_t pos = addrPort.find_first_of("["); - if(pos != std::string::npos && pos != 0) - throw syntax_error(origAddrPort, pos); // an [ was found but not at the beginning; + if(pos != std::string::npos && pos != 0) { + throw syntax_error(origAddrPort, pos); // an [ was found but not at the beginning; + } bool hasPort = false; if(pos != std::string::npos) { addrPort.erase(pos, 1); pos = addrPort.find_first_of("]"); - if(pos == std::string::npos) - throw syntax_error(origAddrPort, origAddrPort.length()); //no trailing ] although an leading [ was found + if(pos == std::string::npos) { + throw syntax_error(origAddrPort, origAddrPort.length()); //no trailing ] although an leading [ was found + } if(pos < addrPort.length()-2) { - if(addrPort[pos+1] != ':') - throw syntax_error(origAddrPort, pos+2); // wrong port delimieter + if(addrPort[pos+1] != ':') { + throw syntax_error(origAddrPort, pos+2); // wrong port delimieter + } addrPort[pos+1] = '/'; hasPort = true; + } else if(pos != addrPort.length()-1) { + throw syntax_error(origAddrPort, pos+2); // too few characters left } - else if(pos != addrPort.length()-1) - throw syntax_error(origAddrPort, pos+2); // too few characters left addrPort.erase(pos, 1); - } - else { + } else { pos = addrPort.find_first_of(":"); if(pos != std::string::npos && pos == addrPort.find_last_of(":")) { // an ':' has been found and it is the only one -> assuming port present @@ -105,12 +113,12 @@ void OptionHost::init(std::string addrPort) std::stringstream tmp_stream(addrPort); getline(tmp_stream, addr, '/'); - if(!tmp_stream.good()) + if(!tmp_stream.good()) { throw syntax_error(origAddrPort, addr.length()); + } tmp_stream >> port; - } - else { + } else { addr = addrPort; port = "2323"; // default sync port } @@ -124,12 +132,13 @@ std::istream& operator>>(std::istream& stream, OptionHost& host) return stream; } -void OptionNetwork::init(std::string network) +void OptionNetwork::init(std::string network) { std::stringstream tmp_stream(network); getline(tmp_stream, net_addr, '/'); - if(!tmp_stream.good()) + if(!tmp_stream.good()) { throw syntax_error(network, net_addr.length()); + } tmp_stream >> prefix_length; } @@ -149,13 +158,14 @@ Options& Options::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new Options(); - + } + return *inst; } -Options::Options() : key_(u_int32_t(0)), salt_(u_int32_t(0)) +Options::Options() : key_(uint32_t(0)), salt_(uint32_t(0)) { #if defined(ANYCTR_OPTIONS) progname_ = "anytun-controld"; @@ -255,7 +265,7 @@ Options::~Options() if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ - u_int32_t pos = str.length() + 1; \ + uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ std::stringstream tmp; \ @@ -274,11 +284,11 @@ Options::~Options() if(argc < 2) \ throw syntax_error(str.append(" ").append(argv[i+1]), str.length()); \ if(argv[i+1][0] == '-') { \ - u_int32_t pos = str.length() + 1; \ + uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ if(argv[i+2][0] == '-') { \ - u_int32_t pos = str.length() + 1 + strlen(argv[i+1]) + 1; \ + uint32_t pos = str.length() + 1 + strlen(argv[i+1]) + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]).append(" ").append(argv[i+2]), pos); \ } \ std::stringstream tmp; \ @@ -296,7 +306,7 @@ Options::~Options() if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ - u_int32_t pos = str.length() + 1; \ + uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ std::stringstream tmp(argv[i+1]); \ @@ -317,7 +327,7 @@ Options::~Options() if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ - u_int32_t pos = str.length() + 1; \ + uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ VALUE = Buffer(std::string(argv[i+1])); \ @@ -334,7 +344,7 @@ Options::~Options() if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ - u_int32_t pos = str.length() + 1; \ + uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ VALUE = argv[i+1]; \ @@ -351,7 +361,7 @@ Options::~Options() if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ - u_int32_t pos = str.length() + 1; \ + uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ LIST.push_back(argv[i+1]); \ @@ -368,29 +378,27 @@ bool Options::parse(int argc, char* argv[]) argc--; bool ipv4_only = false, ipv6_only = false; std::string role = ""; - for(int i=1; argc > 0; ++i) - { + for(int i=1; argc > 0; ++i) { std::string str(argv[i]); argc--; if(str == "-h" || str == "--help") { printUsage(); return false; - } - else if(str == "-v" || str == "--version") { + } else if(str == "-v" || str == "--version") { printVersion(); return false; } #if defined(ANYTUN_OPTIONS) || defined(ANYCTR_OPTIONS) - #ifndef _MSC_VER +#ifndef _MSC_VER PARSE_INVERSE_BOOL_PARAM("-D","--nodaemonize", daemonize_, NOTHING) PARSE_SCALAR_PARAM("-u","--username", username_, NOTHING) PARSE_SCALAR_PARAM("-g","--groupname", groupname_, NOTHING) PARSE_SCALAR_PARAM("-C","--chroot", chroot_dir_, NOTHING) PARSE_SCALAR_PARAM("-P","--write-pid", pid_file_, NOTHING) - #endif +#endif #endif @@ -433,70 +441,75 @@ bool Options::parse(int argc, char* argv[]) #endif #if defined(ANYTUN_OPTIONS) || defined(ANYCONF_OPTIONS) - #ifndef NO_ROUTING +#ifndef NO_ROUTING PARSE_CSLIST_PARAM("-R","--route", routes_, OptionNetwork, connection_opts = true) - #endif +#endif PARSE_SCALAR_PARAM("-m","--mux", mux_, connection_opts = true) PARSE_SCALAR_PARAM("-w","--window-size", seq_window_size_, connection_opts = true) - #ifndef NO_CRYPT +#ifndef NO_CRYPT PARSE_SCALAR_PARAM("-k","--kd-prf", kd_prf_, connection_opts = true) PARSE_SCALAR_PARAM("-e","--role", role, connection_opts = true) - #ifndef NO_PASSPHRASE +#ifndef NO_PASSPHRASE PARSE_PHRASE_PARAM_SEC("-E","--passphrase", passphrase_, connection_opts = true) - #endif +#endif PARSE_HEXSTRING_PARAM_SEC("-K","--key", key_, connection_opts = true) PARSE_HEXSTRING_PARAM_SEC("-A","--salt", salt_, connection_opts = true) - #endif +#endif #endif #if defined(ANYTUN_OPTIONS) - #ifndef NO_CRYPT +#ifndef NO_CRYPT PARSE_SCALAR_PARAM("-c","--cipher", cipher_, NOTHING) PARSE_SCALAR_PARAM("-a","--auth-algo", auth_algo_, NOTHING) PARSE_SCALAR_PARAM("-b","--auth-tag-length", auth_tag_length_, NOTHING) - #endif +#endif #endif - else + else { throw syntax_error(str, 0); + } } - if(ipv4_only && ipv6_only) + if(ipv4_only && ipv6_only) { throw syntax_error("-4 and -6 are mutual exclusive", -1); - if(ipv4_only) + } + if(ipv4_only) { resolv_addr_type_ = IPV4_ONLY; - if(ipv6_only) + } + if(ipv6_only) { resolv_addr_type_ = IPV6_ONLY; + } if(role != "") { - if(role == "alice" || role == "server" || role == "left") + if(role == "alice" || role == "server" || role == "left") { role_ = ROLE_LEFT; - else if(role == "bob" || role == "client" || role == "right") + } else if(role == "bob" || role == "client" || role == "right") { role_ = ROLE_RIGHT; - else - throw syntax_error("unknown role name: " + role, -1); + } else { + throw syntax_error("unknown role name: " + role, -1); + } } if(debug_) { log_targets_.push_back("stdout:5"); - daemonize_ = false; + daemonize_ = false; } if(log_targets_.empty()) { #ifndef _MSC_VER - #if !defined(ANYCONF_OPTIONS) +#if !defined(ANYCONF_OPTIONS) log_targets_.push_back(std::string("syslog:3,").append(progname_).append(",daemon")); - #else +#else log_targets_.push_back("stderr:2"); - #endif +#endif #else - #ifdef WIN_SERVICE +#ifdef WIN_SERVICE log_targets_.push_back(std::string("eventlog:3,").append(progname_)); - #else +#else log_targets_.push_back("stdout:3"); - #endif +#endif #endif } @@ -506,24 +519,28 @@ bool Options::parse(int argc, char* argv[]) void Options::parse_post() { #if defined(ANYTUN_OPTIONS) - if(cluster_opts && connection_opts) + if(cluster_opts && connection_opts) { cLog.msg(Log::PRIO_WARNING) << "you have provided options for cluster support as well as connection oriented options, we strongly recommend to use anytun-config and anytun-controld when building a cluster"; + } - if(cipher_ == "null" && auth_algo_ == "null") + if(cipher_ == "null" && auth_algo_ == "null") { kd_prf_ = "null"; - if((cipher_ != "null" || auth_algo_ != "null") && kd_prf_ == "null") + } + if((cipher_ != "null" || auth_algo_ != "null") && kd_prf_ == "null") { cLog.msg(Log::PRIO_WARNING) << "using NULL key derivation with encryption and or authentication enabled!"; + } - u_int32_t tag_len_max = AuthAlgoFactory::getDigestLength(auth_algo_); - if(!tag_len_max) auth_tag_length_ = 0; + uint32_t tag_len_max = AuthAlgoFactory::getDigestLength(auth_algo_); + if(!tag_len_max) { auth_tag_length_ = 0; } else if(tag_len_max < auth_tag_length_) { cLog.msg(Log::PRIO_WARNING) << auth_algo_ << " auth algo can't generate tags of length " << auth_tag_length_ << ", using maximum tag length(" << tag_len_max << ")"; auth_tag_length_ = tag_len_max; } #endif - if(dev_name_ == "" && dev_type_ == "") + if(dev_name_ == "" && dev_type_ == "") { dev_type_ = "tun"; + } } void Options::printVersion() @@ -556,13 +573,13 @@ void Options::printUsage() #if defined(ANYTUN_OPTIONS) || defined(ANYCTR_OPTIONS) - #ifndef _MSC_VER +#ifndef _MSC_VER std::cout << " [-D|--nodaemonize] don't run in background" << std::endl; std::cout << " [-u|--username] change to this user" << std::endl; std::cout << " [-g|--groupname] change to this group" << std::endl; std::cout << " [-C|--chroot] chroot to this directory" << std::endl; std::cout << " [-P|--write-pid] write pid to this file" << std::endl; - #endif +#endif #endif @@ -610,31 +627,31 @@ void Options::printUsage() #endif #if defined(ANYTUN_OPTIONS) || defined(ANYCONF_OPTIONS) - #ifndef NO_ROUTING +#ifndef NO_ROUTING std::cout << " [-R|--route] / add a route to connection, can be invoked several times" << std::endl; - #endif +#endif std::cout << " [-m|--mux] the multiplex id to use" << std::endl; std::cout << " [-w|--window-size] seqence number window size" << std::endl; - #ifndef NO_CRYPT +#ifndef NO_CRYPT std::cout << " [-k|--kd-prf] key derivation pseudo random function" << std::endl; std::cout << " [-e|--role] left (alice) or right (bob)" << std::endl; - #ifndef NO_PASSPHRASE +#ifndef NO_PASSPHRASE std::cout << " [-E|--passphrase] a passprhase to generate master key and salt from" << std::endl; - #endif +#endif std::cout << " [-K|--key] master key to use for encryption" << std::endl; std::cout << " [-A|--salt] master salt to use for encryption" << std::endl; - #endif +#endif #endif #if defined(ANYTUN_OPTIONS) - #ifndef NO_CRYPT +#ifndef NO_CRYPT std::cout << " [-c|--cipher] payload encryption algorithm" << std::endl; std::cout << " [-a|--auth-algo] message authentication algorithm" << std::endl; std::cout << " [-b|--auth-tag-length] length of the auth tag" << std::endl; - #endif +#endif #endif } @@ -653,8 +670,9 @@ void Options::printOptions() std::cout << std::endl; std::cout << "log_targets:"; StringList::const_iterator lit = log_targets_.begin(); - for(; lit != log_targets_.end(); ++lit) + for(; lit != log_targets_.end(); ++lit) { std::cout << " '" << *lit << "',"; + } std::cout << std::endl; std::cout << "debug = " << debug_ << std::endl; std::cout << std::endl; @@ -664,10 +682,18 @@ void Options::printOptions() std::cout << std::endl; std::cout << "resolv_addr_type = "; switch(resolv_addr_type_) { - case ANY: std::cout << "any" << std::endl; break; - case IPV4_ONLY: std::cout << "ipv4-only" << std::endl; break; - case IPV6_ONLY: std::cout << "ipv6-only" << std::endl; break; - default: std::cout << "?" << std::endl; break; + case ANY: + std::cout << "any" << std::endl; + break; + case IPV4_ONLY: + std::cout << "ipv4-only" << std::endl; + break; + case IPV6_ONLY: + std::cout << "ipv6-only" << std::endl; + break; + default: + std::cout << "?" << std::endl; + break; } std::cout << std::endl; std::cout << "local.addr = '" << local_.addr << "'" << std::endl; @@ -678,8 +704,9 @@ void Options::printOptions() std::cout << "local_sync.port = '" << local_sync_.port << "'" << std::endl; std::cout << "remote_sync_hosts:" << std::endl; HostList::const_iterator hit = remote_sync_hosts_.begin(); - for(; hit != remote_sync_hosts_.end(); ++hit) + for(; hit != remote_sync_hosts_.end(); ++hit) { std::cout << " '" << hit->addr << "','" << hit->port << "'" << std::endl; + } std::cout << std::endl; std::cout << "dev_name = '" << dev_name_ << "'" << std::endl; std::cout << "dev_type = '" << dev_type_ << "'" << std::endl; @@ -687,8 +714,9 @@ void Options::printOptions() std::cout << "post_up_script = '" << post_up_script_ << "'" << std::endl; std::cout << "routes:" << std::endl; NetworkList::const_iterator rit; - for(rit = routes_.begin(); rit != routes_.end(); ++rit) + for(rit = routes_.begin(); rit != routes_.end(); ++rit) { std::cout << " " << rit->net_addr << "/" << rit->prefix_length << std::endl; + } std::cout << std::endl; std::cout << "sender_id = '" << sender_id_ << "'" << std::endl; std::cout << "mux_id = " << mux_ << std::endl; @@ -700,9 +728,15 @@ void Options::printOptions() std::cout << "kd_prf = '" << kd_prf_ << "'" << std::endl; std::cout << "role = "; switch(role_) { - case ROLE_LEFT: std::cout << "left" << std::endl; break; - case ROLE_RIGHT: std::cout << "right" << std::endl; break; - default: std::cout << "??" << std::endl; break; + case ROLE_LEFT: + std::cout << "left" << std::endl; + break; + case ROLE_RIGHT: + std::cout << "right" << std::endl; + break; + default: + std::cout << "??" << std::endl; + break; } std::cout << "passphrase = '" << passphrase_ << "'" << std::endl; std::cout << "key = " << key_.getHexDumpOneLine() << std::endl; @@ -839,7 +873,7 @@ Options& Options::setBindToAddr(std::string b) std::string Options::getBindToPort() { ReadersLock lock(mutex); - return bind_to_.port; + return bind_to_.port; } Options& Options::setBindToPort(std::string b) @@ -1076,13 +1110,13 @@ Options& Options::setAuthAlgo(std::string a) return *this; } -u_int32_t Options::getAuthTagLength() +uint32_t Options::getAuthTagLength() { ReadersLock lock(mutex); return auth_tag_length_; } -Options& Options::setAuthTagLength(u_int32_t a) +Options& Options::setAuthTagLength(uint32_t a) { WritersLock lock(mutex); auth_tag_length_ = a; diff --git a/src/options.h b/src/options.h index 7a58c58..70458d5 100644 --- a/src/options.h +++ b/src/options.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -56,7 +56,7 @@ public: void init(std::string addrPort); std::string addr; - std::string port; + std::string port; }; typedef std::list HostList; std::istream& operator>>(std::istream& stream, OptionHost& host); @@ -66,12 +66,12 @@ class OptionNetwork public: OptionNetwork() : net_addr(""), prefix_length(0) {}; OptionNetwork(std::string network) { init(network); }; - OptionNetwork(std::string n, u_int16_t p) : net_addr(n), prefix_length(p) {}; + OptionNetwork(std::string n, uint16_t p) : net_addr(n), prefix_length(p) {}; void init(std::string network); std::string net_addr; - u_int16_t prefix_length; + uint16_t prefix_length; }; typedef std::list NetworkList; std::istream& operator>>(std::istream& stream, OptionNetwork& network); @@ -131,7 +131,7 @@ public: Options& setLocalSyncAddr(std::string l); std::string getLocalSyncPort(); Options& setLocalSyncPort(std::string l); - HostList getRemoteSyncHosts(); + HostList getRemoteSyncHosts(); std::string getDevName(); Options& setDevName(std::string d); @@ -154,8 +154,8 @@ public: Options& setCipher(std::string c); std::string getAuthAlgo(); Options& setAuthAlgo(std::string a); - u_int32_t getAuthTagLength(); - Options& setAuthTagLength(u_int32_t a); + uint32_t getAuthTagLength(); + Options& setAuthTagLength(uint32_t a); std::string getKdPrf(); Options& setKdPrf(std::string k); role_t getRole(); @@ -171,15 +171,18 @@ public: private: Options(); ~Options(); - Options(const Options &l); - void operator=(const Options &l); + Options(const Options& l); + void operator=(const Options& l); static Options* inst; static ::Mutex instMutex; - class instanceCleaner { - public: ~instanceCleaner() { - if(Options::inst != 0) + class instanceCleaner + { + public: + ~instanceCleaner() { + if(Options::inst != 0) { delete Options::inst; + } } }; friend class instanceCleaner; @@ -208,7 +211,7 @@ private: OptionHost remote_; OptionHost local_sync_; - HostList remote_sync_hosts_; + HostList remote_sync_hosts_; std::string dev_name_; std::string dev_type_; @@ -222,7 +225,7 @@ private: std::string cipher_; std::string auth_algo_; - u_int32_t auth_tag_length_; + uint32_t auth_tag_length_; std::string kd_prf_; role_t role_; std::string passphrase_; diff --git a/src/packetSource.cpp b/src/packetSource.cpp index a5443ad..bd3590d 100644 --- a/src/packetSource.cpp +++ b/src/packetSource.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -55,11 +55,11 @@ UDPPacketSource::UDPPacketSource(std::string localaddr, std::string port) UDPPacketSource::~UDPPacketSource() { std::list::iterator it = sockets_.begin(); - for(;it != sockets_.end(); ++it) { -/// this might be a needed by the receiver thread, TODO cleanup -// delete[](it->buf_); -// delete(it->sem_); -// delete(it->sock_); + for(; it != sockets_.end(); ++it) { + /// this might be a needed by the receiver thread, TODO cleanup + // delete[](it->buf_); + // delete(it->sem_); + // delete(it->sock_); } } @@ -74,13 +74,15 @@ void UDPPacketSource::onResolve(PacketSourceResolverIt& it) sock.len_ = 0; sock.sem_ = NULL; sock.sock_ = new proto::socket(io_service_); - if(!sock.sock_) + if(!sock.sock_) { AnytunError::throwErr() << "memory error"; + } sock.sock_->open(e.protocol()); #ifndef _MSC_VER - if(e.protocol() == proto::v6()) + if(e.protocol() == proto::v6()) { sock.sock_->set_option(boost::asio::ip::v6_only(true)); + } #endif sock.sock_->bind(e); sockets_.push_back(sock); @@ -88,15 +90,16 @@ void UDPPacketSource::onResolve(PacketSourceResolverIt& it) it++; } - // prepare multi-socket recv + // prepare multi-socket recv if(sockets_.size() > 1) { std::list::iterator it = sockets_.begin(); - for(;it != sockets_.end(); ++it) { + for(; it != sockets_.end(); ++it) { it->len_ = MAX_PACKET_LENGTH; - it->buf_ = new u_int8_t[it->len_]; - if(!it->buf_) + it->buf_ = new uint8_t[it->len_]; + if(!it->buf_) { AnytunError::throwErr() << "memory error"; - + } + it->sem_ = new Semaphore(); if(!it->sem_) { delete[](it->buf_); @@ -125,7 +128,7 @@ void UDPPacketSource::recv_thread(std::list::iterator it) result.it_ = it; for(;;) { it->sem_->down(); - result.len_ = static_cast(it->sock_->receive_from(boost::asio::buffer(it->buf_, it->len_), result.remote_)); + result.len_ = static_cast(it->sock_->receive_from(boost::asio::buffer(it->buf_, it->len_), result.remote_)); { Lock lock(thread_result_mutex_); thread_result_queue_.push(result); @@ -134,10 +137,11 @@ void UDPPacketSource::recv_thread(std::list::iterator it) } } -u_int32_t UDPPacketSource::recv(u_int8_t* buf, u_int32_t len, PacketSourceEndpoint& remote) +uint32_t UDPPacketSource::recv(uint8_t* buf, uint32_t len, PacketSourceEndpoint& remote) { - if(sockets_.size() == 1) - return static_cast(sockets_.front().sock_->receive_from(boost::asio::buffer(buf, len), remote)); + if(sockets_.size() == 1) { + return static_cast(sockets_.front().sock_->receive_from(boost::asio::buffer(buf, len), remote)); + } thread_result_sem_.down(); ThreadResult result; @@ -154,10 +158,10 @@ u_int32_t UDPPacketSource::recv(u_int8_t* buf, u_int32_t len, PacketSourceEndpoi return len; } -void UDPPacketSource::send(u_int8_t* buf, u_int32_t len, PacketSourceEndpoint remote) +void UDPPacketSource::send(uint8_t* buf, uint32_t len, PacketSourceEndpoint remote) { std::list::iterator it = sockets_.begin(); - for(;it != sockets_.end(); ++it) { + for(; it != sockets_.end(); ++it) { if(it->sock_->local_endpoint().protocol() == remote.protocol()) { it->sock_->send_to(boost::asio::buffer(buf, len), remote); return; diff --git a/src/packetSource.h b/src/packetSource.h index d5ee736..bd75be2 100644 --- a/src/packetSource.h +++ b/src/packetSource.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -50,8 +50,8 @@ class PacketSource public: virtual ~PacketSource() {} - virtual u_int32_t recv(u_int8_t* buf, u_int32_t len, PacketSourceEndpoint& remote) = 0; - virtual void send(u_int8_t* buf, u_int32_t len, PacketSourceEndpoint remote) = 0; + virtual uint32_t recv(uint8_t* buf, uint32_t len, PacketSourceEndpoint& remote) = 0; + virtual void send(uint8_t* buf, uint32_t len, PacketSourceEndpoint remote) = 0; void waitUntilReady(); @@ -60,25 +60,25 @@ protected: }; class UDPPacketSource : public PacketSource -{ +{ public: typedef boost::asio::ip::udp proto; UDPPacketSource(std::string localaddr, std::string port); ~UDPPacketSource(); - u_int32_t recv(u_int8_t* buf, u_int32_t len, PacketSourceEndpoint& remote); - void send(u_int8_t* buf, u_int32_t len, PacketSourceEndpoint remote); + uint32_t recv(uint8_t* buf, uint32_t len, PacketSourceEndpoint& remote); + void send(uint8_t* buf, uint32_t len, PacketSourceEndpoint remote); void onResolve(PacketSourceResolverIt& it); void onError(const std::runtime_error& e); private: boost::asio::io_service io_service_; - + typedef struct { - u_int8_t* buf_; - u_int32_t len_; + uint8_t* buf_; + uint32_t len_; proto::socket* sock_; Semaphore* sem_; } SocketsElement; @@ -86,7 +86,7 @@ private: void recv_thread(std::list::iterator it); typedef struct { - u_int32_t len_; + uint32_t len_; PacketSourceEndpoint remote_; std::list::iterator it_; } ThreadResult; diff --git a/src/plainPacket.cpp b/src/plainPacket.cpp index 79a72de..ad37263 100644 --- a/src/plainPacket.cpp +++ b/src/plainPacket.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -37,62 +37,66 @@ #include "plainPacket.h" #include "anytunError.h" -PlainPacket::PlainPacket(u_int32_t payload_length, bool allow_realloc) : Buffer(payload_length + sizeof(payload_type_t), allow_realloc) +PlainPacket::PlainPacket(uint32_t payload_length, bool allow_realloc) : Buffer(payload_length + sizeof(payload_type_t), allow_realloc) { payload_type_ = reinterpret_cast(buf_); payload_ = buf_ + sizeof(payload_type_t); *payload_type_ = 0; } -u_int32_t PlainPacket::getHeaderLength() +uint32_t PlainPacket::getHeaderLength() { return sizeof(payload_type_t); } payload_type_t PlainPacket::getPayloadType() const { - if(payload_type_) + if(payload_type_) { return PAYLOAD_TYPE_T_NTOH(*payload_type_); + } return 0; } void PlainPacket::setPayloadType(payload_type_t payload_type) { - if(!payload_type_) + if(!payload_type_) { return; - + } + if(payload_type == PAYLOAD_TYPE_TUN) { if(!payload_) { *payload_type_ = PAYLOAD_TYPE_T_HTON(PAYLOAD_TYPE_TUN); return; } - char * ip_version_ptr = reinterpret_cast(payload_); - char ip_version = ip_version_ptr[0]; - ip_version >>=4; - if(ip_version == 4) + char* ip_version_ptr = reinterpret_cast(payload_); + char ip_version = ip_version_ptr[0]; + ip_version >>=4; + if(ip_version == 4) { *payload_type_ = PAYLOAD_TYPE_T_HTON(PAYLOAD_TYPE_TUN4); - else if(ip_version == 6) + } else if(ip_version == 6) { *payload_type_ = PAYLOAD_TYPE_T_HTON(PAYLOAD_TYPE_TUN6); - } - else + } + } else { *payload_type_ = PAYLOAD_TYPE_T_HTON(payload_type); + } } -u_int32_t PlainPacket::getPayloadLength() const +uint32_t PlainPacket::getPayloadLength() const { - if(!payload_) + if(!payload_) { return 0; + } return (length_ > sizeof(payload_type_t)) ? (length_ - sizeof(payload_type_t)) : 0; } - -void PlainPacket::setPayloadLength(u_int32_t payload_length) + +void PlainPacket::setPayloadLength(uint32_t payload_length) { Buffer::setLength(payload_length + sizeof(payload_type_t)); - // depending on allow_realloc buf_ may point to another address - // therefore in this case reinit() gets called by Buffer::setLength() + // depending on allow_realloc buf_ may point to another address + // therefore in this case reinit() gets called by Buffer::setLength() } void PlainPacket::reinit() @@ -100,17 +104,18 @@ void PlainPacket::reinit() payload_type_ = reinterpret_cast(buf_); payload_ = buf_ + sizeof(payload_type_t); - if(length_ <= (sizeof(payload_type_t))) + if(length_ <= (sizeof(payload_type_t))) { payload_ = NULL; + } if(length_ < (sizeof(payload_type_t))) { payload_type_ = NULL; - AnytunError::throwErr() << "plain packet can't be initialized, buffer is too small"; + AnytunError::throwErr() << "plain packet can't be initialized, buffer is too small"; } } -u_int8_t* PlainPacket::getPayload() +uint8_t* PlainPacket::getPayload() { return payload_; } @@ -147,35 +152,35 @@ NetworkAddress PlainPacket::getSrcAddr() const NetworkAddress PlainPacket::getDstAddr() const { - if(!payload_type_ || !payload_) - return NetworkAddress(); - - payload_type_t type = PAYLOAD_TYPE_T_NTOH(*payload_type_); - - if(type == PAYLOAD_TYPE_TAP) // Ehternet - { - // TODO - return NetworkAddress(); - } - else if(type == PAYLOAD_TYPE_TUN4) // IPv4 - { - if(length_ < (sizeof(payload_type_t)+5*4)) - return NetworkAddress(); - char * hdr = reinterpret_cast(payload_); - boost::asio::ip::address_v4::bytes_type ip_octets; - for (int i=0; i<4;i++) - ip_octets[i]=hdr[4*4+i]; - return NetworkAddress(boost::asio::ip::address_v4(ip_octets)); - } - else if(type == PAYLOAD_TYPE_TUN6) // IPv6 - { - if(length_ < (sizeof(payload_type_t)+2*16+2*4)) - return NetworkAddress(); - char * hdr = reinterpret_cast(payload_); - boost::asio::ip::address_v6::bytes_type ip_octets; - for (int i=0; i<16;i++) - ip_octets[i]=hdr[2*4+16+i]; - return NetworkAddress(boost::asio::ip::address_v6(ip_octets)); - } - return NetworkAddress(); + if(!payload_type_ || !payload_) { + return NetworkAddress(); + } + + payload_type_t type = PAYLOAD_TYPE_T_NTOH(*payload_type_); + + if(type == PAYLOAD_TYPE_TAP) { // Ehternet + // TODO + return NetworkAddress(); + } else if(type == PAYLOAD_TYPE_TUN4) { // IPv4 + if(length_ < (sizeof(payload_type_t)+5*4)) { + return NetworkAddress(); + } + char* hdr = reinterpret_cast(payload_); + boost::asio::ip::address_v4::bytes_type ip_octets; + for(int i=0; i<4; i++) { + ip_octets[i]=hdr[4*4+i]; + } + return NetworkAddress(boost::asio::ip::address_v4(ip_octets)); + } else if(type == PAYLOAD_TYPE_TUN6) { // IPv6 + if(length_ < (sizeof(payload_type_t)+2*16+2*4)) { + return NetworkAddress(); + } + char* hdr = reinterpret_cast(payload_); + boost::asio::ip::address_v6::bytes_type ip_octets; + for(int i=0; i<16; i++) { + ip_octets[i]=hdr[2*4+16+i]; + } + return NetworkAddress(boost::asio::ip::address_v6(ip_octets)); + } + return NetworkAddress(); } diff --git a/src/plainPacket.h b/src/plainPacket.h index 8cf0368..6a1396f 100644 --- a/src/plainPacket.h +++ b/src/plainPacket.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -47,17 +47,17 @@ class Cipher; #define PAYLOAD_TYPE_TAP 0x6558 #define PAYLOAD_TYPE_TUN 0x0000 #define PAYLOAD_TYPE_TUN4 0x0800 -#define PAYLOAD_TYPE_TUN6 0x86DD +#define PAYLOAD_TYPE_TUN6 0x86DD class PlainPacket : public Buffer { public: /** * Packet constructor - * @param the length of the payload + * @param the length of the payload * @param allow reallocation of buffer */ - PlainPacket(u_int32_t payload_length, bool allow_realloc = false); + PlainPacket(uint32_t payload_length, bool allow_realloc = false); /** * Packet destructor @@ -68,11 +68,11 @@ public: * Get the length of the header * @return the length of the header */ - static u_int32_t getHeaderLength(); + static uint32_t getHeaderLength(); /** * Get the payload type - * @return the id of the payload type + * @return the id of the payload type */ payload_type_t getPayloadType() const; @@ -86,31 +86,31 @@ public: * Get the length of the payload * @return the length of the payload */ - u_int32_t getPayloadLength() const; + uint32_t getPayloadLength() const; /** * Set the length of the payload * @param length length of the payload */ - void setPayloadLength(u_int32_t payload_length); + void setPayloadLength(uint32_t payload_length); /** * Get the the payload * @return the Pointer to the payload */ - u_int8_t* getPayload(); + uint8_t* getPayload(); -// NetworkAddress getSrcAddr() const; + // NetworkAddress getSrcAddr() const; NetworkAddress getDstAddr() const; private: PlainPacket(); - PlainPacket(const PlainPacket &src); + PlainPacket(const PlainPacket& src); void reinit(); payload_type_t* payload_type_; - u_int8_t* payload_; + uint8_t* payload_; }; #endif diff --git a/src/posix/posixDaemon.cpp b/src/posix/posixDaemon.cpp index e4a4148..96cad00 100644 --- a/src/posix/posixDaemon.cpp +++ b/src/posix/posixDaemon.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -49,112 +49,131 @@ DaemonService::DaemonService() : pw_(NULL), gr_(NULL), daemonized_(false) void DaemonService::initPrivs(std::string const& username, std::string const& groupname) { - if(username == "") + if(username == "") { return; - + } + pw_ = getpwnam(username.c_str()); - if(!pw_) + if(!pw_) { AnytunError::throwErr() << "unknown user " << username; - - if(groupname != "") + } + + if(groupname != "") { gr_ = getgrnam(groupname.c_str()); - else + } else { gr_ = getgrgid(pw_->pw_gid); - - if(!gr_) + } + + if(!gr_) { AnytunError::throwErr() << "unknown group " << groupname; + } } void DaemonService::dropPrivs() { - if(!pw_ || !gr_) + if(!pw_ || !gr_) { return; - - if(setgid(gr_->gr_gid)) + } + + if(setgid(gr_->gr_gid)) { AnytunError::throwErr() << "setgid('" << gr_->gr_name << "') failed: " << AnytunErrno(errno); - + } + gid_t gr_list[1]; gr_list[0] = gr_->gr_gid; - if(setgroups (1, gr_list)) + if(setgroups(1, gr_list)) { AnytunError::throwErr() << "setgroups(['" << gr_->gr_name << "']) failed: " << AnytunErrno(errno); - - if(setuid(pw_->pw_uid)) + } + + if(setuid(pw_->pw_uid)) { AnytunError::throwErr() << "setuid('" << pw_->pw_name << "') failed: " << AnytunErrno(errno); - + } + cLog.msg(Log::PRIO_NOTICE) << "dropped privileges to " << pw_->pw_name << ":" << gr_->gr_name; } void DaemonService::chroot(std::string const& chrootdir) { - if (getuid() != 0) + if(getuid() != 0) { AnytunError::throwErr() << "this program has to be run as root in order to run in a chroot"; + } - if(::chroot(chrootdir.c_str())) + if(::chroot(chrootdir.c_str())) { AnytunError::throwErr() << "can't chroot to " << chrootdir; + } cLog.msg(Log::PRIO_NOTICE) << "we are in chroot jail (" << chrootdir << ") now" << std::endl; - if(chdir("/")) + if(chdir("/")) { AnytunError::throwErr() << "can't change to /"; + } } /// TODO: this outstandignly ugly please and i really can't stress the please fix it asap!!!!!!! -std::ofstream pidFile; // FIXXXME no global variable +std::ofstream pidFile; // FIXXXME no global variable void DaemonService::daemonize() { -// std::ofstream pidFile; + // std::ofstream pidFile; if(gOpt.getPidFile() != "") { pidFile.open(gOpt.getPidFile().c_str()); - if(!pidFile.is_open()) + if(!pidFile.is_open()) { AnytunError::throwErr() << "can't open pid file (" << gOpt.getPidFile() << "): " << AnytunErrno(errno); + } } pid_t pid; pid = fork(); - if(pid < 0) + if(pid < 0) { AnytunError::throwErr() << "daemonizing failed at fork(): " << AnytunErrno(errno) << ", exitting"; + } - if(pid) exit(0); + if(pid) { exit(0); } umask(0); - if(setsid() < 0) + if(setsid() < 0) { AnytunError::throwErr() << "daemonizing failed at setsid(): " << AnytunErrno(errno) << ", exitting"; + } pid = fork(); - if(pid < 0) + if(pid < 0) { AnytunError::throwErr() << "daemonizing failed at fork(): " << AnytunErrno(errno) << ", exitting"; + } - if(pid) exit(0); + if(pid) { exit(0); } - if ((chdir("/")) < 0) + if((chdir("/")) < 0) { AnytunError::throwErr() << "daemonizing failed at chdir(): " << AnytunErrno(errno) << ", exitting"; + } -// std::cout << "running in background now..." << std::endl; + // std::cout << "running in background now..." << std::endl; int fd; -// for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors - for (fd=0;fd<=2;fd++) // close all file descriptors + // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors + for(fd=0; fd<=2; fd++) { // close all file descriptors close(fd); + } fd = open("/dev/null",O_RDWR); // stdin - if(fd == -1) + if(fd == -1) { cLog.msg(Log::PRIO_WARNING) << "can't open /dev/null as stdin"; - else { - if(dup(fd) == -1) // stdout + } else { + if(dup(fd) == -1) { // stdout cLog.msg(Log::PRIO_WARNING) << "can't open /dev/null as stdout"; - if(dup(fd) == -1) // stderr + } + if(dup(fd) == -1) { // stderr cLog.msg(Log::PRIO_WARNING) << "can't open /dev/null as stderr"; + } } - -// FIXXXXME: write this pid to file (currently pid from posix/signhandler.hpp:77 is used) -// -// if(pidFile.is_open()) { -// pid_t pid = getpid(); -// pidFile << pid; -// pidFile.close(); -// } + + // FIXXXXME: write this pid to file (currently pid from posix/signhandler.hpp:77 is used) + // + // if(pidFile.is_open()) { + // pid_t pid = getpid(); + // pidFile << pid; + // pidFile.close(); + // } daemonized_ = true; } diff --git a/src/posix/posixDaemon.h b/src/posix/posixDaemon.h index e6d56d5..e3ac3e3 100644 --- a/src/posix/posixDaemon.h +++ b/src/posix/posixDaemon.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/posix/signalHandler.hpp b/src/posix/signalHandler.hpp index 3851c78..11d0c2f 100644 --- a/src/posix/signalHandler.hpp +++ b/src/posix/signalHandler.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -51,7 +51,7 @@ int SigQuitHandler(int /*sig*/, const std::string& /*msg*/) int SigHupHandler(int /*sig*/, const std::string& /*msg*/) { - cLog.msg(Log::PRIO_NOTICE) << "SIG-Hup caught"; + cLog.msg(Log::PRIO_NOTICE) << "SIG-Hup caught"; return 0; } @@ -98,10 +98,10 @@ void handleSignal() timeout.tv_sec = 1; timeout.tv_nsec = 0; sigNum = sigtimedwait(&signal_set, NULL, &timeout); - if (sigNum == -1) { - if (errno != EINTR && errno != EAGAIN) { - cLog.msg(Log::PRIO_ERROR) << "sigwait failed with error: \"" << AnytunErrno(errno) << "\" SignalHandling will be disabled"; - break; + if(sigNum == -1) { + if(errno != EINTR && errno != EAGAIN) { + cLog.msg(Log::PRIO_ERROR) << "sigwait failed with error: \"" << AnytunErrno(errno) << "\" SignalHandling will be disabled"; + break; } } else { gSignalController.inject(sigNum); @@ -112,7 +112,7 @@ void handleSignal() void registerSignalHandler(SignalController& ctrl, DaemonService& /*service*/) { sigset_t signal_set; - + sigemptyset(&signal_set); sigaddset(&signal_set, SIGINT); sigaddset(&signal_set, SIGQUIT); @@ -120,13 +120,13 @@ void registerSignalHandler(SignalController& ctrl, DaemonService& /*service*/) sigaddset(&signal_set, SIGTERM); sigaddset(&signal_set, SIGUSR1); sigaddset(&signal_set, SIGUSR2); - + #if defined(BOOST_HAS_PTHREADS) pthread_sigmask(SIG_BLOCK, &signal_set, NULL); #else #error The signalhandler works only with pthreads #endif - + boost::thread(boost::bind(handleSignal)); ctrl.handler[SIGINT] = boost::bind(SigIntHandler, _1, _2); diff --git a/src/posix/sysExec.hpp b/src/posix/sysExec.hpp index 18fde97..7e8f37e 100644 --- a/src/posix/sysExec.hpp +++ b/src/posix/sysExec.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,8 +45,9 @@ SysExec::~SysExec() { - if(!closed_) + if(!closed_) { close(pipefd_); + } } @@ -55,15 +56,17 @@ char** dupSysStringArray(T const& array) { char** new_array; new_array = static_cast(malloc((array.size() + 1)*sizeof(char*))); - if(!new_array) + if(!new_array) { return NULL; + } unsigned int i = 0; for(typename T::const_iterator it = array.begin(); it != array.end(); ++it) { new_array[i] = strdup(it->c_str()); if(!new_array) { - while(i--) + while(i--) { free(new_array[i]); + } free(new_array); return NULL; } @@ -75,11 +78,13 @@ char** dupSysStringArray(T const& array) void freeSysStringArray(char** array) { - if(!array) + if(!array) { return; + } - for(int i=0; array[i] ; ++i) + for(int i=0; array[i] ; ++i) { free(array[i]); + } free(array); } @@ -106,35 +111,38 @@ void SysExec::doExec(StringVector args, StringList env) } // child code, exec the script int fd; - for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors - if(fd != pipefd[1]) close(fd); - + for(fd=getdtablesize(); fd>=0; --fd) // close all file descriptors + if(fd != pipefd[1]) { close(fd); } + fd = open("/dev/null",O_RDWR); // stdin - if(fd == -1) + if(fd == -1) { cLog.msg(Log::PRIO_WARNING) << "can't open stdin"; - else { - if(dup(fd) == -1) // stdout + } else { + if(dup(fd) == -1) { // stdout cLog.msg(Log::PRIO_WARNING) << "can't open stdout"; - if(dup(fd) == -1) // stderr + } + if(dup(fd) == -1) { // stderr cLog.msg(Log::PRIO_WARNING) << "can't open stderr"; + } } - + args.insert(args.begin(), script_); char** argv = dupSysStringArray(args); char** evp = dupSysStringArray(env); - + execve(script_.c_str(), argv, evp); - // if execve returns, an error occurred, but logging doesn't work - // because we closed all file descriptors, so just write errno to - // pipe and call exit - + // if execve returns, an error occurred, but logging doesn't work + // because we closed all file descriptors, so just write errno to + // pipe and call exit + freeSysStringArray(argv); freeSysStringArray(evp); int err = errno; int ret = write(pipefd[1], (void*)(&err), sizeof(err)); - if(ret != sizeof(errno)) + if(ret != sizeof(errno)) { exit(-2); + } exit(-1); } @@ -166,18 +174,20 @@ int SysExec::waitForScript() void SysExec::waitAndDestroy(SysExec*& s) { - if(!s) + if(!s) { return; + } s->waitForScript(); - if(WIFEXITED(s->return_code_)) - cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << WEXITSTATUS(s->return_code_); - else if(WIFSIGNALED(s->return_code_)) + if(WIFEXITED(s->return_code_)) { + cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << WEXITSTATUS(s->return_code_); + } else if(WIFSIGNALED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' terminated after signal " << WTERMSIG(s->return_code_); - else if(WIFSTOPPED(s->return_code_)) + } else if(WIFSTOPPED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' stopped after signal " << WSTOPSIG(s->return_code_); - else if(WIFCONTINUED(s->return_code_)) + } else if(WIFCONTINUED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' continued after SIGCONT"; + } delete(s); s = NULL; diff --git a/src/resolver.cpp b/src/resolver.cpp index 55371d0..6a17cde 100644 --- a/src/resolver.cpp +++ b/src/resolver.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -40,20 +40,20 @@ using ::boost::asio::ip::udp; using ::boost::asio::ip::tcp; template -void waitAndEnqueue(u_int32_t s, const std::string& addr, const std::string& port, boost::function)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r) +void waitAndEnqueue(uint32_t s, const std::string& addr, const std::string& port, boost::function)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r) { cLog.msg(Log::PRIO_ERROR) << "the resolver only supports udp and tcp"; } template<> -void waitAndEnqueue(u_int32_t s, const std::string& addr, const std::string& port, boost::function)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r) +void waitAndEnqueue(uint32_t s, const std::string& addr, const std::string& port, boost::function)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r) { boost::this_thread::sleep(boost::posix_time::milliseconds(s * 1000)); gResolver.resolveUdp(addr, port, onResolve, onError, r); } template<> -void waitAndEnqueue(u_int32_t s, const std::string& addr, const std::string& port, boost::function)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r) +void waitAndEnqueue(uint32_t s, const std::string& addr, const std::string& port, boost::function)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r) { boost::this_thread::sleep(boost::posix_time::milliseconds(s * 1000)); gResolver.resolveTcp(addr, port, onResolve, onError, r); @@ -71,9 +71,7 @@ void ResolveHandler::operator()(const boost::system::error_code& e, boost if(boost::system::posix_error::success == e) { try { onResolve_(endpointIt); - } - catch(const std::runtime_error& e) - { + } catch(const std::runtime_error& e) { onError_(e); } } else { @@ -90,9 +88,10 @@ Resolver& Resolver::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new Resolver(); - + } + return *inst; } @@ -102,14 +101,16 @@ Resolver::Resolver() : udp_resolver_(io_service_), tcp_resolver_(io_service_), t Resolver::~Resolver() { - if(thread_) + if(thread_) { delete thread_; + } } void Resolver::init() { - if(!thread_) - thread_ = new boost::thread(boost::bind(&Resolver::run, this)); + if(!thread_) { + thread_ = new boost::thread(boost::bind(&Resolver::run, this)); + } } void Resolver::run() @@ -121,13 +122,9 @@ void Resolver::run() io_service_.run(); io_service_.reset(); boost::this_thread::sleep(boost::posix_time::milliseconds(250)); - } - catch(const std::runtime_error& e) - { + } catch(const std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "resolver caught runtime error, restarting: " << e.what(); - } - catch(const std::exception& e) - { + } catch(const std::exception& e) { cLog.msg(Log::PRIO_ERROR) << "resolver caught exception, restarting: " << e.what(); } } @@ -141,16 +138,27 @@ void Resolver::resolveUdp(const std::string& addr, const std::string& port, UdpR std::auto_ptr query; if(addr != "") { switch(r) { - case IPV4_ONLY: query = std::auto_ptr(new udp::resolver::query(udp::v4(), addr, port)); break; - case IPV6_ONLY: query = std::auto_ptr(new udp::resolver::query(udp::v6(), addr, port)); break; - default: query = std::auto_ptr(new udp::resolver::query(addr, port)); break; + case IPV4_ONLY: + query = std::auto_ptr(new udp::resolver::query(udp::v4(), addr, port)); + break; + case IPV6_ONLY: + query = std::auto_ptr(new udp::resolver::query(udp::v6(), addr, port)); + break; + default: + query = std::auto_ptr(new udp::resolver::query(addr, port)); + break; } - } - else { + } else { switch(r) { - case IPV4_ONLY: query = std::auto_ptr(new udp::resolver::query(udp::v4(), port)); break; - case IPV6_ONLY: query = std::auto_ptr(new udp::resolver::query(udp::v6(), port)); break; - default: query = std::auto_ptr(new udp::resolver::query(port)); break; + case IPV4_ONLY: + query = std::auto_ptr(new udp::resolver::query(udp::v4(), port)); + break; + case IPV6_ONLY: + query = std::auto_ptr(new udp::resolver::query(udp::v6(), port)); + break; + default: + query = std::auto_ptr(new udp::resolver::query(port)); + break; } } UdpResolveHandler handler(addr, port, onResolve, onError, r); @@ -164,18 +172,29 @@ void Resolver::resolveTcp(const std::string& addr, const std::string& port, TcpR std::auto_ptr query; if(addr != "") { switch(r) { - case IPV4_ONLY: query = std::auto_ptr(new tcp::resolver::query(tcp::v4(), addr, port)); break; - case IPV6_ONLY: query = std::auto_ptr(new tcp::resolver::query(tcp::v6(), addr, port)); break; - default: query = std::auto_ptr(new tcp::resolver::query(addr, port)); break; + case IPV4_ONLY: + query = std::auto_ptr(new tcp::resolver::query(tcp::v4(), addr, port)); + break; + case IPV6_ONLY: + query = std::auto_ptr(new tcp::resolver::query(tcp::v6(), addr, port)); + break; + default: + query = std::auto_ptr(new tcp::resolver::query(addr, port)); + break; } - } - else { + } else { switch(r) { - case IPV4_ONLY: query = std::auto_ptr(new tcp::resolver::query(tcp::v4(), port)); break; - case IPV6_ONLY: query = std::auto_ptr(new tcp::resolver::query(tcp::v6(), port)); break; - default: query = std::auto_ptr(new tcp::resolver::query(port)); break; + case IPV4_ONLY: + query = std::auto_ptr(new tcp::resolver::query(tcp::v4(), port)); + break; + case IPV6_ONLY: + query = std::auto_ptr(new tcp::resolver::query(tcp::v6(), port)); + break; + default: + query = std::auto_ptr(new tcp::resolver::query(port)); + break; } } TcpResolveHandler handler(addr, port, onResolve, onError, r); - tcp_resolver_.async_resolve(*query, handler); + tcp_resolver_.async_resolve(*query, handler); } diff --git a/src/resolver.h b/src/resolver.h index 35c2bc4..4a82733 100644 --- a/src/resolver.h +++ b/src/resolver.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -62,7 +62,7 @@ private: typedef ResolveHandler UdpResolveHandler; typedef ResolveHandler TcpResolveHandler; -class Resolver +class Resolver { public: static Resolver& instance(); @@ -76,15 +76,18 @@ public: private: Resolver(); ~Resolver(); - Resolver(const Resolver &r); - void operator=(const Resolver &r); + Resolver(const Resolver& r); + void operator=(const Resolver& r); static Resolver* inst; static ::Mutex instMutex; - class instanceCleaner { - public: ~instanceCleaner() { - if(Resolver::inst != 0) + class instanceCleaner + { + public: + ~instanceCleaner() { + if(Resolver::inst != 0) { delete Resolver::inst; + } } }; friend class instanceCleaner; diff --git a/src/routingTable.cpp b/src/routingTable.cpp index c64366d..ab2515d 100644 --- a/src/routingTable.cpp +++ b/src/routingTable.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -46,8 +46,9 @@ RoutingTable& RoutingTable::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new RoutingTable(); + } return *inst; } @@ -58,137 +59,140 @@ RoutingTable::RoutingTable() RoutingTable::~RoutingTable() { -} +} -void RoutingTable::updateRouteTreeUnlocked(const NetworkPrefix & pref) +void RoutingTable::updateRouteTreeUnlocked(const NetworkPrefix& pref) { //Lock lock(mutex_); //deadlock - u_int8_t length=pref.getNetworkPrefixLength(); - network_address_type_t type=pref.getNetworkAddressType(); - u_int16_t mux = routes_[pref.getNetworkAddressType()].find(pref)->second; - RoutingTreeNode * node = &(root_[type]); - if (type==ipv4) - { - ipv4_bytes_type bytes(pref.to_bytes_v4()); - if (length>32) - length=32; - RoutingTree::walk(bytes, node, length, mux); - } else if (type==ipv6) { - ipv6_bytes_type bytes(pref.to_bytes_v6()); - if (length>128) - length=128; - RoutingTree::walk(bytes, node, length, mux); - } else if (type==ethernet) { - ethernet_bytes_type bytes(pref.to_bytes_ethernet()); - if (length>48) - length=48; - RoutingTree::walk(bytes, node, length, mux); - } else { - AnytunError::throwErr() << "illegal protocol type"; - } - //root_[type].print(0); + uint8_t length=pref.getNetworkPrefixLength(); + network_address_type_t type=pref.getNetworkAddressType(); + uint16_t mux = routes_[pref.getNetworkAddressType()].find(pref)->second; + RoutingTreeNode* node = &(root_[type]); + if(type==ipv4) { + ipv4_bytes_type bytes(pref.to_bytes_v4()); + if(length>32) { + length=32; + } + RoutingTree::walk(bytes, node, length, mux); + } else if(type==ipv6) { + ipv6_bytes_type bytes(pref.to_bytes_v6()); + if(length>128) { + length=128; + } + RoutingTree::walk(bytes, node, length, mux); + } else if(type==ethernet) { + ethernet_bytes_type bytes(pref.to_bytes_ethernet()); + if(length>48) { + length=48; + } + RoutingTree::walk(bytes, node, length, mux); + } else { + AnytunError::throwErr() << "illegal protocol type"; + } + //root_[type].print(0); } -void RoutingTable::addRoute(const NetworkPrefix & pref, u_int16_t mux) +void RoutingTable::addRoute(const NetworkPrefix& pref, uint16_t mux) { Lock lock(mutex_); - - network_address_type_t type=pref.getNetworkAddressType(); - if (type==ipv4 || type==ipv6) - { + network_address_type_t type=pref.getNetworkAddressType(); + + if(type==ipv4 || type==ipv6) { std::pair ret = routes_[type].insert(RoutingMap::value_type(pref,mux)); - if(!ret.second) - { + if(!ret.second) { routes_[pref.getNetworkAddressType()].erase(ret.first); routes_[pref.getNetworkAddressType()].insert(RoutingMap::value_type(pref,mux)); } - root_[pref.getNetworkAddressType()]=RoutingTreeNode(); - RoutingMap::iterator it = routes_[type].begin(); - for (;it!=routes_[pref.getNetworkAddressType()].end();++it) - updateRouteTreeUnlocked(it->first); - } else if (type==ethernet) { + root_[pref.getNetworkAddressType()]=RoutingTreeNode(); + RoutingMap::iterator it = routes_[type].begin(); + for(; it!=routes_[pref.getNetworkAddressType()].end(); ++it) { + updateRouteTreeUnlocked(it->first); + } + } else if(type==ethernet) { return; // TODO: add support for ethernet - } else { - AnytunError::throwErr() << "illegal protocol type"; - } + } else { + AnytunError::throwErr() << "illegal protocol type"; + } } -void RoutingTable::delRoute(const NetworkPrefix & pref ) +void RoutingTable::delRoute(const NetworkPrefix& pref) { Lock lock(mutex_); - - routes_[pref.getNetworkAddressType()].erase(routes_[pref.getNetworkAddressType()].find(pref)); + + routes_[pref.getNetworkAddressType()].erase(routes_[pref.getNetworkAddressType()].find(pref)); } -u_int16_t RoutingTable::getRoute(const NetworkAddress & addr) +uint16_t RoutingTable::getRoute(const NetworkAddress& addr) { - Lock lock(mutex_); - network_address_type_t type=addr.getNetworkAddressType(); - - if (routes_[type].empty()) - AnytunError::throwErr() << "no route"; - - if (type==ipv4) - { - ipv4_bytes_type bytes(addr.to_bytes_v4()); - return RoutingTree::find(bytes, root_[type]); - } else if (type==ipv6) { - ipv6_bytes_type bytes(addr.to_bytes_v6()); - return RoutingTree::find(bytes, root_[type]); - } else if (type==ethernet) { - //TODO Our model wont fit to ethernet addresses well. - // maybe use hashmap or something like that instead - ethernet_bytes_type bytes(addr.to_bytes_ethernet()); - return RoutingTree::find(bytes, root_[type]); - } else { - AnytunError::throwErr() << "illegal protocol type"; - } + Lock lock(mutex_); + network_address_type_t type=addr.getNetworkAddressType(); + + if(routes_[type].empty()) { + AnytunError::throwErr() << "no route"; + } + + if(type==ipv4) { + ipv4_bytes_type bytes(addr.to_bytes_v4()); + return RoutingTree::find(bytes, root_[type]); + } else if(type==ipv6) { + ipv6_bytes_type bytes(addr.to_bytes_v6()); + return RoutingTree::find(bytes, root_[type]); + } else if(type==ethernet) { + //TODO Our model wont fit to ethernet addresses well. + // maybe use hashmap or something like that instead + ethernet_bytes_type bytes(addr.to_bytes_ethernet()); + return RoutingTree::find(bytes, root_[type]); + } else { + AnytunError::throwErr() << "illegal protocol type"; + } return 0; } -u_int16_t* RoutingTable::getOrNewRoutingTEUnlocked(const NetworkPrefix & addr) +uint16_t* RoutingTable::getOrNewRoutingTEUnlocked(const NetworkPrefix& addr) { RoutingMap::iterator it = routes_[addr.getNetworkAddressType()].find(addr); - if(it!=routes_[addr.getNetworkAddressType()].end()) + if(it!=routes_[addr.getNetworkAddressType()].end()) { return &(it->second); + } routes_[addr.getNetworkAddressType()].insert(RoutingMap::value_type(addr, 1)); it = routes_[addr.getNetworkAddressType()].find(addr); return &(it->second); } -u_int16_t RoutingTable::getCountUnlocked(network_address_type_t type) +uint16_t RoutingTable::getCountUnlocked(network_address_type_t type) { - RoutingMap::iterator it = routes_[type].begin(); - u_int16_t routes=0; - for (;it!=routes_[type].end();++it) - routes++; - return routes; + RoutingMap::iterator it = routes_[type].begin(); + uint16_t routes=0; + for(; it!=routes_[type].end(); ++it) { + routes++; + } + return routes; } RoutingMap::iterator RoutingTable::getBeginUnlocked(network_address_type_t type) { - return routes_[type].begin(); + return routes_[type].begin(); } RoutingMap::iterator RoutingTable::getEndUnlocked(network_address_type_t type) { - return routes_[type].end(); + return routes_[type].end(); } void RoutingTable::clear(network_address_type_t type) { Lock lock(mutex_); - routes_[type].clear(); + routes_[type].clear(); } bool RoutingTable::empty(network_address_type_t type) { Lock lock(mutex_); - return routes_[type].empty(); + return routes_[type].empty(); } Mutex& RoutingTable::getMutex() diff --git a/src/routingTable.h b/src/routingTable.h index 4a60ec3..48e7617 100644 --- a/src/routingTable.h +++ b/src/routingTable.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,39 +42,42 @@ #include "networkPrefix.h" #include "routingTreeNode.h" #include "boost/array.hpp" -typedef std::map RoutingMap; +typedef std::map RoutingMap; class RoutingTable { public: - static RoutingTable& instance(); - RoutingTable(); - ~RoutingTable(); - void addRoute(const NetworkPrefix & ,u_int16_t); - void updateRouteTreeUnlocked(const NetworkPrefix & pref); - void delRoute(const NetworkPrefix & ); - u_int16_t getRoute(const NetworkAddress &); - bool empty(network_address_type_t type); - void clear(network_address_type_t type); + static RoutingTable& instance(); + RoutingTable(); + ~RoutingTable(); + void addRoute(const NetworkPrefix& ,uint16_t); + void updateRouteTreeUnlocked(const NetworkPrefix& pref); + void delRoute(const NetworkPrefix&); + uint16_t getRoute(const NetworkAddress&); + bool empty(network_address_type_t type); + void clear(network_address_type_t type); Mutex& getMutex(); - u_int16_t* getOrNewRoutingTEUnlocked(const NetworkPrefix & addr); - u_int16_t getCountUnlocked(network_address_type_t type); - RoutingMap::iterator getBeginUnlocked(network_address_type_t type); - RoutingMap::iterator getEndUnlocked(network_address_type_t type); + uint16_t* getOrNewRoutingTEUnlocked(const NetworkPrefix& addr); + uint16_t getCountUnlocked(network_address_type_t type); + RoutingMap::iterator getBeginUnlocked(network_address_type_t type); + RoutingMap::iterator getEndUnlocked(network_address_type_t type); private: static Mutex instMutex; - static RoutingTable* inst; - class instanceCleaner { - public: ~instanceCleaner() { - if(RoutingTable::inst != 0) - delete RoutingTable::inst; - } - }; - RoutingTable(const RoutingTable &s); - void operator=(const RoutingTable &s); - boost::array routes_; - boost::array root_; + static RoutingTable* inst; + class instanceCleaner + { + public: + ~instanceCleaner() { + if(RoutingTable::inst != 0) { + delete RoutingTable::inst; + } + } + }; + RoutingTable(const RoutingTable& s); + void operator=(const RoutingTable& s); + boost::array routes_; + boost::array root_; Mutex mutex_; }; diff --git a/src/routingTree.hpp b/src/routingTree.hpp index 89b7c18..9a55886 100644 --- a/src/routingTree.hpp +++ b/src/routingTree.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -35,30 +35,29 @@ #include "anytunError.h" -class RoutingTree { +class RoutingTree +{ public: template - static void walk(BinaryType bytes ,RoutingTreeNode * node,u_int8_t length,u_int16_t mux) - { - for (int i=0; i<(length/8); i++) - { - if (!node->nodes_[bytes[i]]) + static void walk(BinaryType bytes ,RoutingTreeNode* node,uint8_t length,uint16_t mux) { + for(int i=0; i<(length/8); i++) { + if(!node->nodes_[bytes[i]]) { node->nodes_[bytes[i]] = new RoutingTreeNode; + } node=node->nodes_[bytes[i]]; } - if (length%8) - { + if(length%8) { unsigned char idx=0xff; idx <<=8-(length%8); idx &= bytes[length/8]; unsigned char maxidx=0xff; maxidx>>=(length%8); maxidx|=idx; - for (unsigned char i=idx; i<=maxidx; i++) - { - if (!node->nodes_[i]) + for(unsigned char i=idx; i<=maxidx; i++) { + if(!node->nodes_[i]) { node->nodes_[i] = new RoutingTreeNode; + } node->nodes_[i]->valid_=true; node->nodes_[i]->mux_=mux; } @@ -67,25 +66,20 @@ public: node->mux_=mux; } } - + template - static u_int16_t find(BinaryType bytes ,RoutingTreeNode & root ) - { + static uint16_t find(BinaryType bytes ,RoutingTreeNode& root) { bool valid=0; - u_int16_t mux=0; - RoutingTreeNode * node = &root; - if (root.valid_) - { + uint16_t mux=0; + RoutingTreeNode* node = &root; + if(root.valid_) { mux=root.mux_; valid=1; } - for (size_t level=0;levelnodes_[bytes[level]]) - { + for(size_t level=0; levelnodes_[bytes[level]]) { node=node->nodes_[bytes[level]]; - if(node->valid_) - { + if(node->valid_) { mux=node->mux_; valid=1; } @@ -93,8 +87,9 @@ public: break; } } - if(!valid) + if(!valid) { AnytunError::throwErr() << "no route"; + } return mux; } diff --git a/src/routingTreeNode.cpp b/src/routingTreeNode.cpp index e50ff70..9d65248 100644 --- a/src/routingTreeNode.cpp +++ b/src/routingTreeNode.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -34,32 +34,32 @@ RoutingTreeNode::RoutingTreeNode():mux_(0),valid_(false) { - for(int i=0; i<256; i++) - nodes_[i]=NULL; + for(int i=0; i<256; i++) { + nodes_[i]=NULL; + } } void RoutingTreeNode::print(int level) const { - if (valid_) - { - std::cout << " -> " <print(level+1); - } - } + if(valid_) { + std::cout << " -> " <print(level+1); + } + } } RoutingTreeNode::~RoutingTreeNode() { - for(int i=0; i<256; i++) - if(nodes_[i]) - delete nodes_[i]; -} + for(int i=0; i<256; i++) + if(nodes_[i]) { + delete nodes_[i]; + } +} diff --git a/src/routingTreeNode.h b/src/routingTreeNode.h index 9efc6f2..a16f8de 100644 --- a/src/routingTreeNode.h +++ b/src/routingTreeNode.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,15 +43,15 @@ class RoutingTree; class RoutingTreeNode { public: - RoutingTreeNode(); - ~RoutingTreeNode(); - void print(int) const; + RoutingTreeNode(); + ~RoutingTreeNode(); + void print(int) const; private: -// Mutex mutex_; - u_int16_t mux_; - bool valid_; - boost::array nodes_; + // Mutex mutex_; + uint16_t mux_; + bool valid_; + boost::array nodes_; friend class RoutingTree; }; diff --git a/src/seqWindow.cpp b/src/seqWindow.cpp index 359ba63..992a71c 100644 --- a/src/seqWindow.cpp +++ b/src/seqWindow.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -44,16 +44,18 @@ SeqWindowElement::SeqWindowElement() SeqWindowElement::~SeqWindowElement() { - if(window_) + if(window_) { delete[] window_; + } } void SeqWindowElement::init(window_size_t w, seq_nr_t m) { - if(window_) + if(window_) { delete[] window_; - window_ = new u_int8_t[w]; - memset(window_, 0, w); + } + window_ = new uint8_t[w]; + memset(window_, 0, w); pos_ = 0; max_ = m; window_[pos_] = 1; @@ -70,8 +72,9 @@ SeqWindow::~SeqWindow() bool SeqWindow::checkAndAdd(sender_id_t sender, seq_nr_t seq_nr) { Lock lock(mutex_); - if (!window_size_) + if(!window_size_) { return false; + } SenderMap::iterator s = sender_.find(sender); if(s == sender_.end()) { @@ -84,67 +87,71 @@ bool SeqWindow::checkAndAdd(sender_id_t sender, seq_nr_t seq_nr) s->second.max_ += SEQ_NR_MAX/2; seq_nr += SEQ_NR_MAX/2; shifted = 1; - } - else if(s->second.max_ > (SEQ_NR_MAX - window_size_)) { + } else if(s->second.max_ > (SEQ_NR_MAX - window_size_)) { s->second.max_ -= SEQ_NR_MAX/2; seq_nr -= SEQ_NR_MAX/2; shifted = 2; } - + seq_nr_t min = s->second.max_ - window_size_ + 1; if(seq_nr < min || seq_nr == s->second.max_) { - if(shifted == 1) + if(shifted == 1) { s->second.max_ -= SEQ_NR_MAX/2; - else if(shifted == 2) + } else if(shifted == 2) { s->second.max_ += SEQ_NR_MAX/2; + } return true; } - + if(seq_nr > s->second.max_) { seq_nr_t diff = seq_nr - s->second.max_; - if(diff >= window_size_) + if(diff >= window_size_) { diff = window_size_; - + } + window_size_t new_pos = s->second.pos_ + diff; - + if(new_pos >= window_size_) { new_pos -= window_size_; - - if(s->second.pos_ < window_size_ - 1) + + if(s->second.pos_ < window_size_ - 1) { memset(&(s->second.window_[s->second.pos_ + 1]), 0, window_size_ - s->second.pos_ - 1); - + } + memset(s->second.window_, 0, new_pos); - } - else { + } else { memset(&(s->second.window_[s->second.pos_ + 1]), 0, diff); } s->second.pos_ = new_pos; s->second.window_[s->second.pos_] = 1; s->second.max_ = seq_nr; - - if(shifted == 1) + + if(shifted == 1) { s->second.max_ -= SEQ_NR_MAX/2; - else if(shifted == 2) + } else if(shifted == 2) { s->second.max_ += SEQ_NR_MAX/2; - + } + return false; } - + seq_nr_t diff = s->second.max_ - seq_nr; - window_size_t pos = diff > s->second.pos_ ? s->second.pos_ + window_size_ : s->second.pos_; + window_size_t pos = diff > s->second.pos_ ? s->second.pos_ + window_size_ : s->second.pos_; pos -= diff; - - if(shifted == 1) + + if(shifted == 1) { s->second.max_ -= SEQ_NR_MAX/2; - else if(shifted == 2) + } else if(shifted == 2) { s->second.max_ += SEQ_NR_MAX/2; - + } + int ret = s->second.window_[pos]; s->second.window_[pos] = 1; - - if(ret) + + if(ret) { return true; - + } + return false; } diff --git a/src/seqWindow.h b/src/seqWindow.h index 1090447..fa6adaa 100644 --- a/src/seqWindow.h +++ b/src/seqWindow.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,7 +42,8 @@ class SeqWindow; -class SeqWindowElement { +class SeqWindowElement +{ public: SeqWindowElement(); ~SeqWindowElement(); @@ -51,7 +52,7 @@ public: seq_nr_t max_; window_size_t pos_; - u_int8_t* window_; + uint8_t* window_; }; class SeqWindow @@ -71,21 +72,20 @@ private: Mutex mutex_; SenderMap sender_; - SeqWindow(const SeqWindow &s); - void operator=(const SeqWindow &s); + SeqWindow(const SeqWindow& s); + void operator=(const SeqWindow& s); - friend class boost::serialization::access; - template - void serialize(Archive & ar, const unsigned int version) - { - Lock lock(mutex_); - //unsigned int serial = (unsigned int) window_size_; - //window_size_t serial = (window_size_t) window_size_; - ar & window_size_; - //TODO: Do not sync complete Sender Map! - // ar & sender_; + friend class boost::serialization::access; + template + void serialize(Archive& ar, const unsigned int version) { + Lock lock(mutex_); + //unsigned int serial = (unsigned int) window_size_; + //window_size_t serial = (window_size_t) window_size_; + ar& window_size_; + //TODO: Do not sync complete Sender Map! + // ar & sender_; } - + }; diff --git a/src/signalController.cpp b/src/signalController.cpp index 6a20588..d0df71c 100644 --- a/src/signalController.cpp +++ b/src/signalController.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,12 +45,13 @@ SignalController& gSignalController = SignalController::instance(); SignalController& SignalController::instance() { - Lock lock(instMutex); - static instanceCleaner c; - if(!inst) - inst = new SignalController(); + Lock lock(instMutex); + static instanceCleaner c; + if(!inst) { + inst = new SignalController(); + } - return *inst; + return *inst; } int SigErrorHandler(int /*sig*/, const std::string& msg) @@ -64,11 +65,11 @@ int SigErrorHandler(int /*sig*/, const std::string& msg) #ifndef _MSC_VER #include "signalHandler.hpp" #else - #ifdef WIN_SERVICE - #include "win32/signalServiceHandler.hpp" - #else - #include "win32/signalHandler.hpp" - #endif +#ifdef WIN_SERVICE +#include "win32/signalServiceHandler.hpp" +#else +#include "win32/signalHandler.hpp" +#endif #endif void SignalController::init(DaemonService& service) @@ -89,8 +90,9 @@ void SignalController::inject(int sig, const std::string& msg) int SignalController::run() { for(CallbackMap::iterator it = callbacks.begin(); it != callbacks.end(); ++it) - if(it->first == CALLB_RUNNING) + if(it->first == CALLB_RUNNING) { it->second(); + } int ret = 0; while(1) { @@ -101,27 +103,28 @@ int SignalController::run() sig = sigQueue.front(); sigQueue.pop(); } - + HandlerMap::iterator it = handler.find(sig.first); - if(it != handler.end()) - { + if(it != handler.end()) { ret = it->second(sig.first, sig.second); - if(ret) + if(ret) { break; - } - else { + } + } else { it = handler.find(SIGUNKNOWN); - if(it != handler.end()) + if(it != handler.end()) { it->second(sig.first, sig.second); - else + } else { cLog.msg(Log::PRIO_NOTICE) << "SIG " << sig.first << " caught with message '" << sig.second << "' - ignoring"; + } } } for(CallbackMap::iterator it = callbacks.begin(); it != callbacks.end(); ++it) - if(it->first == CALLB_STOPPING) + if(it->first == CALLB_STOPPING) { it->second(); + } return ret; } diff --git a/src/signalController.h b/src/signalController.h index fa5f0fb..7a52fc7 100644 --- a/src/signalController.h +++ b/src/signalController.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -66,15 +66,18 @@ public: private: SignalController() {}; ~SignalController() {}; - SignalController(const SignalController &s); - void operator=(const SignalController &s); + SignalController(const SignalController& s); + void operator=(const SignalController& s); static SignalController* inst; static Mutex instMutex; - class instanceCleaner { - public: ~instanceCleaner() { - if(SignalController::inst != NULL) + class instanceCleaner + { + public: + ~instanceCleaner() { + if(SignalController::inst != NULL) { delete SignalController::inst; + } } }; friend class instanceCleaner; diff --git a/src/syncBuffer.cpp b/src/syncBuffer.cpp index 0ad2b4a..ca1eb09 100644 --- a/src/syncBuffer.cpp +++ b/src/syncBuffer.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/syncBuffer.h b/src/syncBuffer.h index a9aee4e..b68e9f5 100644 --- a/src/syncBuffer.h +++ b/src/syncBuffer.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -43,23 +43,23 @@ class SyncBuffer : public Buffer { public: - SyncBuffer() : Buffer(){}; - SyncBuffer(u_int32_t length) : Buffer(length){}; - SyncBuffer(Buffer b): Buffer(b) {}; - SyncBuffer(u_int8_t* data, u_int32_t length): Buffer(data,length) {}; - SyncBuffer(const SyncBuffer & src) : Buffer(src) {}; + SyncBuffer() : Buffer() {}; + SyncBuffer(uint32_t length) : Buffer(length) {}; + SyncBuffer(Buffer b): Buffer(b) {}; + SyncBuffer(uint8_t* data, uint32_t length): Buffer(data,length) {}; + SyncBuffer(const SyncBuffer& src) : Buffer(src) {}; private: -//TODO check if this is ok -// Mutex mutex_; - friend class boost::serialization::access; - template - void serialize(Archive & ar, const unsigned int version) - { -// Lock lock(mutex_); - ar & length_; - for(u_int32_t i = 0; i < length_; i++) - ar & (*this)[i]; - } + //TODO check if this is ok + // Mutex mutex_; + friend class boost::serialization::access; + template + void serialize(Archive& ar, const unsigned int version) { + // Lock lock(mutex_); + ar& length_; + for(uint32_t i = 0; i < length_; i++) { + ar & (*this)[i]; + } + } }; #endif diff --git a/src/syncClient.cpp b/src/syncClient.cpp index dd6a166..bca915a 100644 --- a/src/syncClient.cpp +++ b/src/syncClient.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -47,82 +47,79 @@ SyncClient::SyncClient(std::string hostname,std::string port) -:hostname_( hostname),port_(port) + :hostname_(hostname),port_(port) { } void SyncClient::run() { - bool connected(false); - for(;;) - { - try - { - boost::asio::io_service io_service; - SyncTcpConnection::proto::resolver resolver(io_service); - SyncTcpConnection::proto::resolver::query query( hostname_, port_); - SyncTcpConnection::proto::resolver::iterator endpoint_iterator = resolver.resolve(query); - SyncTcpConnection::proto::resolver::iterator end; + bool connected(false); + for(;;) { + try { + boost::asio::io_service io_service; + SyncTcpConnection::proto::resolver resolver(io_service); + SyncTcpConnection::proto::resolver::query query(hostname_, port_); + SyncTcpConnection::proto::resolver::iterator endpoint_iterator = resolver.resolve(query); + SyncTcpConnection::proto::resolver::iterator end; - SyncTcpConnection::proto::socket socket(io_service); - boost::system::error_code error = boost::asio::error::host_not_found; - while (error && endpoint_iterator != end) - { - socket.close(); - socket.connect(*endpoint_iterator++, error); - } - if (error) - throw boost::system::system_error(error); - if (!connected) - cLog.msg(Log::PRIO_NOTICE) << "sync: connected to " << hostname_ <<":"<< port_; - connected=true; - readAndProcess(socket); //endless loop - } - catch (std::exception& e) - { - if (connected) - cLog.msg(Log::PRIO_NOTICE) << "sync: connection to " << hostname_ <<":"<< port_<< " lost ("<< e.what() << ") retrying every 10sec"; - connected=false; - boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); - } - } + SyncTcpConnection::proto::socket socket(io_service); + boost::system::error_code error = boost::asio::error::host_not_found; + while(error && endpoint_iterator != end) { + socket.close(); + socket.connect(*endpoint_iterator++, error); + } + if(error) { + throw boost::system::system_error(error); + } + if(!connected) { + cLog.msg(Log::PRIO_NOTICE) << "sync: connected to " << hostname_ <<":"<< port_; + } + connected=true; + readAndProcess(socket); //endless loop + } catch(std::exception& e) { + if(connected) { + cLog.msg(Log::PRIO_NOTICE) << "sync: connection to " << hostname_ <<":"<< port_<< " lost ("<< e.what() << ") retrying every 10sec"; + } + connected=false; + boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); + } + } } -void SyncClient::readAndProcess(SyncTcpConnection::proto::socket & socket) +void SyncClient::readAndProcess(SyncTcpConnection::proto::socket& socket) { - ConnectionList & cl_ (gConnectionList); - size_t message_lenght ; - for (;;) - { - std::stringstream message_lenght_stream; - readExactly(socket,5,message_lenght_stream); - message_lenght_stream >> message_lenght; - std::stringstream void_stream; - readExactly(socket,1,void_stream); //skip space - std::stringstream sync_command_stream; - readExactly(socket,message_lenght, sync_command_stream); - //cLog.msg(Log::PRIO_NOTICE) << "recieved sync inforamtaion "<> scom; - } + ConnectionList& cl_(gConnectionList); + size_t message_lenght ; + for(;;) { + std::stringstream message_lenght_stream; + readExactly(socket,5,message_lenght_stream); + message_lenght_stream >> message_lenght; + std::stringstream void_stream; + readExactly(socket,1,void_stream); //skip space + std::stringstream sync_command_stream; + readExactly(socket,message_lenght, sync_command_stream); + //cLog.msg(Log::PRIO_NOTICE) << "recieved sync inforamtaion "<> scom; + } } -void SyncClient::readExactly(SyncTcpConnection::proto::socket & socket,size_t toread, std::iostream & result) +void SyncClient::readExactly(SyncTcpConnection::proto::socket& socket,size_t toread, std::iostream& result) { - size_t hasread = 0; - while (toread > hasread) - { - //TODO read bigger buffers - boost::array buf; - boost::system::error_code error; - size_t len = socket.read_some(boost::asio::buffer(buf), error); - if (error == boost::asio::error::eof) - break; // Connection closed cleanly by peer. - else if (error) - throw boost::system::system_error(error); // Some other error. - //for (size_t pos=0; pos hasread) { + //TODO read bigger buffers + boost::array buf; + boost::system::error_code error; + size_t len = socket.read_some(boost::asio::buffer(buf), error); + if(error == boost::asio::error::eof) { + break; // Connection closed cleanly by peer. + } else if(error) { + throw boost::system::system_error(error); // Some other error. + } + //for (size_t pos=0; pos * * This file is part of Anytun. @@ -37,14 +37,14 @@ class SyncClient { public: - SyncClient(std::string hostname,std::string port); + SyncClient(std::string hostname,std::string port); - void run(); + void run(); private: - void readAndProcess(SyncTcpConnection::proto::socket & socket); - void readExactly(SyncTcpConnection::proto::socket & socket,size_t toread, std::iostream &); - std::string hostname_; - std::string port_; + void readAndProcess(SyncTcpConnection::proto::socket& socket); + void readExactly(SyncTcpConnection::proto::socket& socket,size_t toread, std::iostream&); + std::string hostname_; + std::string port_; }; diff --git a/src/syncCommand.cpp b/src/syncCommand.cpp index 8668504..22dede8 100644 --- a/src/syncCommand.cpp +++ b/src/syncCommand.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -31,28 +31,30 @@ */ #include "syncCommand.h" -SyncCommand::SyncCommand(ConnectionList & cl ) -{ - scc_ = new SyncConnectionCommand(cl); - src_ = new SyncRouteCommand(); +SyncCommand::SyncCommand(ConnectionList& cl) +{ + scc_ = new SyncConnectionCommand(cl); + src_ = new SyncRouteCommand(); } -SyncCommand::SyncCommand(ConnectionList & cl, u_int16_t mux ) -{ - scc_ = new SyncConnectionCommand(cl,mux); - src_=NULL; +SyncCommand::SyncCommand(ConnectionList& cl, uint16_t mux) +{ + scc_ = new SyncConnectionCommand(cl,mux); + src_=NULL; } -SyncCommand::SyncCommand(NetworkPrefix np ) -{ - scc_ = NULL; - src_ = new SyncRouteCommand(np); +SyncCommand::SyncCommand(NetworkPrefix np) +{ + scc_ = NULL; + src_ = new SyncRouteCommand(np); } SyncCommand::~SyncCommand() { - if (scc_) - delete scc_; - if (src_) - delete src_; + if(scc_) { + delete scc_; + } + if(src_) { + delete src_; + } } diff --git a/src/syncCommand.h b/src/syncCommand.h index 71c1ffe..5179ae6 100644 --- a/src/syncCommand.h +++ b/src/syncCommand.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,36 +45,35 @@ class SyncCommand { public: - SyncCommand(ConnectionList & cl ); - SyncCommand(ConnectionList & cl ,u_int16_t mux); - SyncCommand(NetworkPrefix); - ~SyncCommand(); + SyncCommand(ConnectionList& cl); + SyncCommand(ConnectionList& cl ,uint16_t mux); + SyncCommand(NetworkPrefix); + ~SyncCommand(); private: - SyncCommand(const SyncCommand &); - SyncConnectionCommand * scc_; - SyncRouteCommand * src_; + SyncCommand(const SyncCommand&); + SyncConnectionCommand* scc_; + SyncRouteCommand* src_; friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - std::string syncstr; - if (scc_) - { - syncstr = "connection"; - } - if ( src_) - { - syncstr = "route"; - } - ar & syncstr; -// std::cout << "syncstr received " < * * This file is part of Anytun. @@ -31,17 +31,17 @@ */ #include "syncConnectionCommand.h" -SyncConnectionCommand::SyncConnectionCommand(ConnectionList & cl ) -:cl_(cl) -{ +SyncConnectionCommand::SyncConnectionCommand(ConnectionList& cl) + :cl_(cl) +{ } -SyncConnectionCommand::SyncConnectionCommand(ConnectionList & cl, u_int16_t mux ) -:cl_(cl),mux_(mux) -{ +SyncConnectionCommand::SyncConnectionCommand(ConnectionList& cl, uint16_t mux) + :cl_(cl),mux_(mux) +{ } -u_int16_t SyncConnectionCommand::getMux() const +uint16_t SyncConnectionCommand::getMux() const { - return mux_; + return mux_; } diff --git a/src/syncConnectionCommand.h b/src/syncConnectionCommand.h index 0c2eb43..282f392 100644 --- a/src/syncConnectionCommand.h +++ b/src/syncConnectionCommand.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,23 +42,22 @@ class SyncConnectionCommand { public: - SyncConnectionCommand(ConnectionList & cl ); - SyncConnectionCommand(ConnectionList & cl ,u_int16_t mux); - u_int16_t getMux() const; + SyncConnectionCommand(ConnectionList& cl); + SyncConnectionCommand(ConnectionList& cl ,uint16_t mux); + uint16_t getMux() const; private: - SyncConnectionCommand(const SyncConnectionCommand &); - ConnectionList & cl_; - u_int16_t mux_; + SyncConnectionCommand(const SyncConnectionCommand&); + ConnectionList& cl_; + uint16_t mux_; friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - Lock lock(cl_.getMutex()); - ar & mux_; - ConnectionParam & conn = cl_.getOrNewConnectionUnlocked(mux_); - ar & conn; - } + void serialize(Archive& ar, const unsigned int version) { + Lock lock(cl_.getMutex()); + ar& mux_; + ConnectionParam& conn = cl_.getOrNewConnectionUnlocked(mux_); + ar& conn; + } }; diff --git a/src/syncOnConnect.hpp b/src/syncOnConnect.hpp index 79df42f..fe8a0eb 100644 --- a/src/syncOnConnect.hpp +++ b/src/syncOnConnect.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -35,13 +35,12 @@ // TODO required headers -void syncOnConnect(SyncTcpConnection * connptr) +void syncOnConnect(SyncTcpConnection* connptr) { - //TODO Locking here - ConnectionList & cl_(gConnectionList); + //TODO Locking here + ConnectionList& cl_(gConnectionList); ConnectionMap::iterator cit = cl_.getBeginUnlocked(); - for (;cit!=cl_.getEndUnlocked();++cit) - { + for(; cit!=cl_.getEndUnlocked(); ++cit) { std::ostringstream sout; boost::archive::text_oarchive oa(sout); const SyncCommand scom(cl_,cit->first); @@ -51,25 +50,23 @@ void syncOnConnect(SyncTcpConnection * connptr) connptr->Send(lengthout.str()); connptr->Send(sout.str()); } - //TODO Locking here - network_address_type_t types[] = {ipv4,ipv6,ethernet}; - for (int types_idx=0; types_idx<3; types_idx++) - { - network_address_type_t type = types[types_idx]; - RoutingMap::iterator it = gRoutingTable.getBeginUnlocked(type); - for (;it!=gRoutingTable.getEndUnlocked(type);++it) - { - NetworkPrefix tmp(it->first); - std::ostringstream sout; - boost::archive::text_oarchive oa(sout); - const SyncCommand scom(tmp); - oa << scom; - std::stringstream lengthout; - lengthout << std::setw(5) << std::setfill('0') << sout.str().size()<< ' '; - connptr->Send(lengthout.str()); - connptr->Send(sout.str()); - } - } + //TODO Locking here + network_address_type_t types[] = {ipv4,ipv6,ethernet}; + for(int types_idx=0; types_idx<3; types_idx++) { + network_address_type_t type = types[types_idx]; + RoutingMap::iterator it = gRoutingTable.getBeginUnlocked(type); + for(; it!=gRoutingTable.getEndUnlocked(type); ++it) { + NetworkPrefix tmp(it->first); + std::ostringstream sout; + boost::archive::text_oarchive oa(sout); + const SyncCommand scom(tmp); + oa << scom; + std::stringstream lengthout; + lengthout << std::setw(5) << std::setfill('0') << sout.str().size()<< ' '; + connptr->Send(lengthout.str()); + connptr->Send(sout.str()); + } + } } #endif diff --git a/src/syncQueue.cpp b/src/syncQueue.cpp index 270bb26..8ddc743 100644 --- a/src/syncQueue.cpp +++ b/src/syncQueue.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -52,39 +52,41 @@ SyncQueue& SyncQueue::instance() { Lock lock(instMutex); static instanceCleaner c; - if(!inst) + if(!inst) { inst = new SyncQueue(); + } return *inst; } -void SyncQueue::push(const SyncCommand & scom ) +void SyncQueue::push(const SyncCommand& scom) { - std::ostringstream sout; - boost::archive::text_oarchive oa(sout); - oa << scom; + std::ostringstream sout; + boost::archive::text_oarchive oa(sout); + oa << scom; std::stringstream lengthout; lengthout << std::setw(5) << std::setfill('0') << sout.str().size()<< ' '; - push(lengthout.str()+sout.str()); + push(lengthout.str()+sout.str()); } -void SyncQueue::push(const std::string & str ) +void SyncQueue::push(const std::string& str) { Lock lock(mutex_); -// std::cout << "Debug" << std:endl; - if( syncServer_) - syncServer_->send(str); + // std::cout << "Debug" << std:endl; + if(syncServer_) { + syncServer_->send(str); + } } -void SyncQueue::setSyncServerPtr(SyncServer * ptr) +void SyncQueue::setSyncServerPtr(SyncServer* ptr) { Lock lock(mutex_); - syncServer_=ptr; + syncServer_=ptr; } bool SyncQueue::empty() { Lock lock(mutex_); - return 1; + return 1; } diff --git a/src/syncQueue.h b/src/syncQueue.h index 8da82b9..e5eb8d7 100644 --- a/src/syncQueue.h +++ b/src/syncQueue.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,28 +45,31 @@ class SyncQueue { public: - SyncQueue():syncServer_(NULL) {}; - ~SyncQueue() {}; + SyncQueue():syncServer_(NULL) {}; + ~SyncQueue() {}; static SyncQueue& instance(); - void setSyncServerPtr(SyncServer *); - void push(const std::string & ); - void push(const SyncCommand & ); - std::string pop(); - bool empty(); + void setSyncServerPtr(SyncServer*); + void push(const std::string&); + void push(const SyncCommand&); + std::string pop(); + bool empty(); private: static Mutex instMutex; - static SyncQueue* inst; - class instanceCleaner { - public: ~instanceCleaner() { - if(SyncQueue::inst != 0) - delete SyncQueue::inst; - } + static SyncQueue* inst; + class instanceCleaner + { + public: + ~instanceCleaner() { + if(SyncQueue::inst != 0) { + delete SyncQueue::inst; + } + } }; - SyncQueue(const SyncQueue &s); - void operator=(const SyncQueue &s); + SyncQueue(const SyncQueue& s); + void operator=(const SyncQueue& s); Mutex mutex_; - SyncServer * syncServer_; + SyncServer* syncServer_; }; extern SyncQueue& gSyncQueue; diff --git a/src/syncRouteCommand.cpp b/src/syncRouteCommand.cpp index 3c02a02..439b693 100644 --- a/src/syncRouteCommand.cpp +++ b/src/syncRouteCommand.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -32,16 +32,16 @@ #include "syncRouteCommand.h" SyncRouteCommand::SyncRouteCommand() -{ +{ } -SyncRouteCommand::SyncRouteCommand( const NetworkPrefix & addr ) -:addr_(addr) -{ +SyncRouteCommand::SyncRouteCommand(const NetworkPrefix& addr) + :addr_(addr) +{ } -NetworkPrefix SyncRouteCommand::getPrefix() const +NetworkPrefix SyncRouteCommand::getPrefix() const { - return addr_; + return addr_; } diff --git a/src/syncRouteCommand.h b/src/syncRouteCommand.h index e91ffd0..0d66ef3 100644 --- a/src/syncRouteCommand.h +++ b/src/syncRouteCommand.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,25 +42,24 @@ class SyncRouteCommand { public: - SyncRouteCommand(const NetworkPrefix & ); - SyncRouteCommand(); - NetworkPrefix getPrefix() const; + SyncRouteCommand(const NetworkPrefix&); + SyncRouteCommand(); + NetworkPrefix getPrefix() const; private: - SyncRouteCommand(const SyncRouteCommand &); - u_int16_t count_; - NetworkPrefix addr_; + SyncRouteCommand(const SyncRouteCommand&); + uint16_t count_; + NetworkPrefix addr_; friend class boost::serialization::access; template - void serialize(Archive & ar, const unsigned int version) - { - Lock lock(gRoutingTable.getMutex()); - ar & addr_; -// u_int16_t & mux (gRoutingTable.getOrNewRoutingTEUnlocked(addr_)); -// ar & mux; - ar & (*(gRoutingTable.getOrNewRoutingTEUnlocked(addr_))); - gRoutingTable.updateRouteTreeUnlocked(addr_); - }; + void serialize(Archive& ar, const unsigned int version) { + Lock lock(gRoutingTable.getMutex()); + ar& addr_; + // uint16_t & mux (gRoutingTable.getOrNewRoutingTEUnlocked(addr_)); + // ar & mux; + ar & (*(gRoutingTable.getOrNewRoutingTEUnlocked(addr_))); + gRoutingTable.updateRouteTreeUnlocked(addr_); + }; }; diff --git a/src/syncServer.cpp b/src/syncServer.cpp index e4f6434..71052b8 100644 --- a/src/syncServer.cpp +++ b/src/syncServer.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -37,18 +37,18 @@ //using asio::ip::tcp; -SyncServer::SyncServer(std::string localaddr, std::string port, ConnectCallback onConnect) +SyncServer::SyncServer(std::string localaddr, std::string port, ConnectCallback onConnect) : onConnect_(onConnect) { gResolver.resolveTcp(localaddr, port, boost::bind(&SyncServer::onResolve, this, _1), boost::bind(&SyncServer::onResolvError, this, _1)); } -SyncServer::~SyncServer() +SyncServer::~SyncServer() { std::list::iterator it = acceptors_.begin(); - for(;it != acceptors_.end(); ++it) { -/// this might be a needed by a running thread, TODO cleanup -// delete(it->acceptor_); + for(; it != acceptors_.end(); ++it) { + /// this might be a needed by a running thread, TODO cleanup + // delete(it->acceptor_); } } @@ -56,16 +56,18 @@ void SyncServer::onResolve(SyncTcpConnection::proto::resolver::iterator& it) { while(it != SyncTcpConnection::proto::resolver::iterator()) { SyncTcpConnection::proto::endpoint e = *it; - + AcceptorsElement acceptor; acceptor.acceptor_ = new SyncTcpConnection::proto::acceptor(io_service_); - if(!acceptor.acceptor_) + if(!acceptor.acceptor_) { AnytunError::throwErr() << "memory error"; + } acceptor.acceptor_->open(e.protocol()); #ifndef _MSC_VER - if(e.protocol() == boost::asio::ip::tcp::v6()) + if(e.protocol() == boost::asio::ip::tcp::v6()) { acceptor.acceptor_->set_option(boost::asio::ip::v6_only(true)); + } #endif acceptor.acceptor_->set_option(boost::asio::socket_base::reuse_address(true)); acceptor.acceptor_->bind(e); @@ -86,7 +88,7 @@ void SyncServer::onResolve(SyncTcpConnection::proto::resolver::iterator& it) void SyncServer::onResolvError(const std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "sync server bind/listen failed: " << e.what(); - // TODO: stop daemon?? + // TODO: stop daemon?? } void SyncServer::run() @@ -98,8 +100,9 @@ void SyncServer::run() void SyncServer::send(std::string message) { Lock lock(mutex_); - for(std::list::iterator it = conns_.begin() ;it != conns_.end(); ++it) + for(std::list::iterator it = conns_.begin() ; it != conns_.end(); ++it) { (*it)->Send(message); + } } void SyncServer::start_accept() @@ -107,12 +110,12 @@ void SyncServer::start_accept() Lock lock(mutex_); std::list::iterator it = acceptors_.begin(); - for(;it != acceptors_.end(); ++it) { + for(; it != acceptors_.end(); ++it) { if(!it->started_) { - SyncTcpConnection::pointer new_connection = SyncTcpConnection::create(it->acceptor_->io_service()); + SyncTcpConnection::pointer new_connection = SyncTcpConnection::create(it->acceptor_->get_io_service()); conns_.push_back(new_connection); it->acceptor_->async_accept(new_connection->socket(), - boost::bind(&SyncServer::handle_accept, this, new_connection, boost::asio::placeholders::error, it)); + boost::bind(&SyncServer::handle_accept, this, new_connection, boost::asio::placeholders::error, it)); it->started_ = true; } } @@ -120,7 +123,7 @@ void SyncServer::start_accept() void SyncServer::handle_accept(SyncTcpConnection::pointer new_connection, const boost::system::error_code& error, std::list::iterator it) { - if (!error) { + if(!error) { cLog.msg(Log::PRIO_INFO) << "new sync client connected from " << new_connection->socket().remote_endpoint(); new_connection->onConnect = onConnect_; diff --git a/src/syncServer.h b/src/syncServer.h index 032e975..983013d 100644 --- a/src/syncServer.h +++ b/src/syncServer.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -44,7 +44,7 @@ #include #include "syncTcpConnection.h" -typedef boost::function ConnectCallback; +typedef boost::function ConnectCallback; class SyncServer { @@ -53,12 +53,12 @@ public: ~SyncServer(); void onResolve(SyncTcpConnection::proto::resolver::iterator& it); void onResolvError(const std::runtime_error& e); - + void run(); void send(std::string message); - + std::list conns_; - + private: Mutex mutex_; //Mutex for list conns_ boost::asio::io_service io_service_; diff --git a/src/syncTcpConnection.cpp b/src/syncTcpConnection.cpp index 08875c7..bd6e6fb 100644 --- a/src/syncTcpConnection.cpp +++ b/src/syncTcpConnection.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -54,11 +54,11 @@ void SyncTcpConnection::Send(std::string message) boost::asio::placeholders::bytes_transferred)); } SyncTcpConnection::SyncTcpConnection(boost::asio::io_service& io_service) - : socket_(io_service) + : socket_(io_service) { } void SyncTcpConnection::handle_write(const boost::system::error_code& /*error*/, - size_t /*bytes_transferred*/) + size_t /*bytes_transferred*/) { } diff --git a/src/syncTcpConnection.h b/src/syncTcpConnection.h index e35c574..807d10e 100644 --- a/src/syncTcpConnection.h +++ b/src/syncTcpConnection.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -46,21 +46,20 @@ public: typedef boost::shared_ptr pointer; typedef boost::asio::ip::tcp proto; - static pointer create(boost::asio::io_service& io_service) - { - return pointer(new SyncTcpConnection(io_service)); - }; + static pointer create(boost::asio::io_service& io_service) { + return pointer(new SyncTcpConnection(io_service)); + }; - boost::function onConnect; + boost::function onConnect; proto::socket& socket(); void start(); - void Send(std::string message); + void Send(std::string message); private: SyncTcpConnection(boost::asio::io_service& io_service); void handle_write(const boost::system::error_code & /*error*/, - size_t /*bytes_transferred*/); + size_t /*bytes_transferred*/); proto::socket socket_; }; diff --git a/src/sysExec.cpp b/src/sysExec.cpp index a69349f..bf3714d 100644 --- a/src/sysExec.cpp +++ b/src/sysExec.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -66,7 +66,7 @@ SysExec::SysExec(std::string const& script, StringVector args, StringList env) : doExec(args, env); } -int SysExec::getReturnCode() const +int SysExec::getReturnCode() const { return return_code_; } diff --git a/src/sysExec.h b/src/sysExec.h index b5400b9..7b99638 100644 --- a/src/sysExec.h +++ b/src/sysExec.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -42,33 +42,33 @@ typedef std::list StringList; class SysExec { - public: - SysExec(std::string const& script); - SysExec(std::string const& script, StringVector args); - SysExec(std::string const& script, StringList env); - SysExec(std::string const& script, StringVector args, StringList env); - ~SysExec(); +public: + SysExec(std::string const& script); + SysExec(std::string const& script, StringVector args); + SysExec(std::string const& script, StringList env); + SysExec(std::string const& script, StringVector args, StringList env); + ~SysExec(); - int waitForScript(); - int getReturnCode() const; + int waitForScript(); + int getReturnCode() const; - static void waitAndDestroy(SysExec*& s); + static void waitAndDestroy(SysExec*& s); - private: - void doExec(StringVector args, StringList env); +private: + void doExec(StringVector args, StringList env); - std::string script_; - bool closed_; + std::string script_; + bool closed_; #ifdef _MSC_VER - PROCESS_INFORMATION process_info_; - DWORD return_code_; + PROCESS_INFORMATION process_info_; + DWORD return_code_; #else - pid_t pid_; - int pipefd_; - int return_code_; + pid_t pid_; + int pipefd_; + int return_code_; #endif - + }; #endif diff --git a/src/threadUtils.hpp b/src/threadUtils.hpp index 7e33302..6285b58 100644 --- a/src/threadUtils.hpp +++ b/src/threadUtils.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -50,20 +50,19 @@ class Semaphore { public: Semaphore(unsigned int initVal=0) - :count_(initVal){}; - void up() - { - boost::mutex::scoped_lock lock(mutex_); - count_++; - lock.unlock(); - cond_.notify_one(); + :count_(initVal) {}; + void up() { + boost::mutex::scoped_lock lock(mutex_); + count_++; + lock.unlock(); + cond_.notify_one(); } - void down() - { - boost::mutex::scoped_lock lock(mutex_); - while (count_ <= 0) - cond_.wait(lock); - count_--; + void down() { + boost::mutex::scoped_lock lock(mutex_); + while(count_ <= 0) { + cond_.wait(lock); + } + count_--; } private: boost::mutex mutex_; diff --git a/src/tunDevice.h b/src/tunDevice.h index 8b400a9..8b2d613 100644 --- a/src/tunDevice.h +++ b/src/tunDevice.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -45,37 +45,41 @@ class TunDevice { public: - TunDevice(std::string dev,std::string dev_type, std::string ifcfg_addr, u_int16_t ifcfg_prefix); + TunDevice(std::string dev,std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix); ~TunDevice(); - - int read(u_int8_t* buf, u_int32_t len); - int write(u_int8_t* buf, u_int32_t len); + + int read(uint8_t* buf, uint32_t len); + int write(uint8_t* buf, uint32_t len); const char* getActualName() const { return actual_name_.c_str(); } const char* getActualNode() const { return actual_node_.c_str(); } - device_type_t getType() const { return conf_.type_; } + device_type_t getType() const { return conf_.type_; } void waitUntilReady(); - const char* getTypeString() const - { + const char* getTypeString() const { #ifndef _MSC_VER if(fd_ < 0) #else if(handle_ == INVALID_HANDLE_VALUE) #endif return ""; - - switch(conf_.type_) - { - case TYPE_UNDEF: return "undef"; break; - case TYPE_TUN: return "tun"; break; - case TYPE_TAP: return "tap"; break; + + switch(conf_.type_) { + case TYPE_UNDEF: + return "undef"; + break; + case TYPE_TUN: + return "tun"; + break; + case TYPE_TAP: + return "tap"; + break; } return ""; } private: - void operator=(const TunDevice &src); - TunDevice(const TunDevice &src); + void operator=(const TunDevice& src); + TunDevice(const TunDevice& src); void init_post(); void do_ifconfig(); @@ -86,14 +90,14 @@ private: #else bool getAdapter(std::string const& dev_name); DWORD performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBufferSize, - LPVOID outBuffer, DWORD outBufferSize); + LPVOID outBuffer, DWORD outBufferSize); HANDLE handle_; OVERLAPPED roverlapped_, woverlapped_; #endif DeviceConfig conf_; #ifndef _MSC_VER - SysExec * sys_exec_; + SysExec* sys_exec_; #endif bool with_pi_; std::string actual_name_; diff --git a/src/win32/registryKey.cpp b/src/win32/registryKey.cpp index a9a0959..4c6240c 100644 --- a/src/win32/registryKey.cpp +++ b/src/win32/registryKey.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -64,14 +64,16 @@ std::string RegistryKey::getName() const DWORD RegistryKey::open(HKEY hkey, std::string subKey, REGSAM samDesired) { - if(opened_) + if(opened_) { RegCloseKey(key_); + } opened_ = false; name_ = ""; LONG err = RegOpenKeyExA(hkey, subKey.c_str(), 0, samDesired, &key_); - if(err != ERROR_SUCCESS) + if(err != ERROR_SUCCESS) { return err; + } name_ = subKey; opened_ = true; @@ -80,28 +82,32 @@ DWORD RegistryKey::open(HKEY hkey, std::string subKey, REGSAM samDesired) void RegistryKey::close() { - if(opened_) + if(opened_) { RegCloseKey(key_); + } opened_ = false; } std::string RegistryKey::operator[](std::string const& name) const { - if(!opened_) + if(!opened_) { throw AnytunErrno(ERROR_INVALID_HANDLE); + } char value[STRING_VALUE_LENGTH]; DWORD len = sizeof(value); LONG err = RegQueryValueExA(key_, name.c_str(), NULL, NULL, (LPBYTE)value, &len); - if(err != ERROR_SUCCESS) + if(err != ERROR_SUCCESS) { throw AnytunErrno(err); + } if(value[len-1] != 0) { - if(len < sizeof(value)) + if(len < sizeof(value)) { value[len++] = 0; - else + } else { throw AnytunErrno(ERROR_INSUFFICIENT_BUFFER); - } + } + } return std::string(value); } @@ -110,8 +116,9 @@ DWORD RegistryKey::getSubKey(DWORD index, RegistryKey& subKey, REGSAM sam) const char subkeyname[NAME_LENGTH]; DWORD len = sizeof(subkeyname); DWORD err = RegEnumKeyExA(key_, index, subkeyname, &len, NULL, NULL, NULL, NULL); - if(err != ERROR_SUCCESS) + if(err != ERROR_SUCCESS) { return err; + } return subKey.open(key_, subkeyname, sam); } diff --git a/src/win32/registryKey.h b/src/win32/registryKey.h index 6aceba0..9e42e29 100644 --- a/src/win32/registryKey.h +++ b/src/win32/registryKey.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -37,9 +37,9 @@ class RegistryKey { -public: - #define NAME_LENGTH 256 - #define STRING_VALUE_LENGTH 256 +public: +#define NAME_LENGTH 256 +#define STRING_VALUE_LENGTH 256 RegistryKey(); RegistryKey(HKEY hkey, std::string subKey, REGSAM samDesired); diff --git a/src/win32/signalHandler.hpp b/src/win32/signalHandler.hpp index 23872a6..6bcea18 100644 --- a/src/win32/signalHandler.hpp +++ b/src/win32/signalHandler.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -73,8 +73,9 @@ bool handleSignal(DWORD ctrlType) void registerSignalHandler(SignalController& ctrl, DaemonService& /*service*/) { - if(!SetConsoleCtrlHandler((PHANDLER_ROUTINE)handleSignal, true)) + if(!SetConsoleCtrlHandler((PHANDLER_ROUTINE)handleSignal, true)) { AnytunError::throwErr() << "Error on SetConsoleCtrlhandler: " << AnytunErrno(GetLastError()); + } ctrl.handler[CTRL_C_EVENT] = boost::bind(CtrlCHandler, _1, _2); ctrl.handler[CTRL_BREAK_EVENT] = boost::bind(CtrlBreakHandler, _1, _2); diff --git a/src/win32/signalServiceHandler.hpp b/src/win32/signalServiceHandler.hpp index da16de5..c897aa2 100644 --- a/src/win32/signalServiceHandler.hpp +++ b/src/win32/signalServiceHandler.hpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. diff --git a/src/win32/sysExec.hpp b/src/win32/sysExec.hpp index ed5be01..3807a63 100644 --- a/src/win32/sysExec.hpp +++ b/src/win32/sysExec.hpp @@ -1,160 +1,162 @@ -/* - * anytun - * - * The secure anycast tunneling protocol (satp) defines a protocol used - * for communication between any combination of unicast and anycast - * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel - * mode and allows tunneling of every ETHER TYPE protocol (e.g. - * ethernet, ip, arp ...). satp directly includes cryptography and - * message authentication based on the methodes used by SRTP. It is - * intended to deliver a generic, scaleable and secure solution for - * tunneling and relaying of packets of any protocol. - * - * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, - * Christian Pointner - * - * This file is part of Anytun. - * - * Anytun 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 3 of the License, or - * any later version. - * - * Anytun 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 anytun. If not, see . - */ -#pragma once -#ifndef ANYTUN_sysexec_hpp_INCLUDED -#define ANYTUN_sysexec_hpp_INCLUDED - -#include -#include // todo remove -#include - -SysExec::~SysExec() -{ - if(!closed_) { - CloseHandle(process_info_.hProcess); - CloseHandle(process_info_.hThread); - } -} - -STARTUPINFOA getStartupInfo() { - STARTUPINFOA startup_info; - startup_info.cb = sizeof(STARTUPINFOA); - GetStartupInfoA(&startup_info); - - //startup_info.dwFlags = STARTF_USESTDHANDLES; - //startup_info.hStdInput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; - //startup_info.hStdOutput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; - //startup_info.hStdError = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; - startup_info.dwFlags |= STARTF_USESHOWWINDOW; - startup_info.wShowWindow = SW_HIDE; - - return startup_info; -} - -char const * const BATCH_FILE_EXTS[] = { ".bat", ".cmd" }; -int const BATCH_FILE_EXTS_COUNT = sizeof(BATCH_FILE_EXTS) / sizeof(BATCH_FILE_EXTS[0]); - -bool endsWith(std::string const& string, std::string const& suffix) { - return string.find(suffix, string.size() - suffix.size()) != std::string::npos; -} - -void SysExec::doExec(StringVector args, StringList env) -{ - std::vector arguments; - - bool isBatchFile = false; - for(int i = 0; i < BATCH_FILE_EXTS_COUNT; ++i) { - if(endsWith(script_, BATCH_FILE_EXTS[i])) { - isBatchFile = true; - break; - } - } - - if(isBatchFile) { - std::string const BATCH_INTERPRETER = "cmd /c \""; - arguments.insert(arguments.end(), BATCH_INTERPRETER.begin(), BATCH_INTERPRETER.end()); - } - arguments.push_back('\"'); - arguments.insert(arguments.end(), script_.begin(), script_.end()); - arguments.push_back('\"'); - arguments.push_back(' '); - - for(StringVector::const_iterator it = args.begin(); it != args.end(); ++it) { - arguments.push_back('\"'); - arguments.insert(arguments.end(), it->begin(), it->end()); - arguments.push_back('\"'); - arguments.push_back(' '); - } - - if(isBatchFile) { - arguments.push_back('\"'); - } - arguments.push_back(0); - - STARTUPINFOA startup_info = getStartupInfo(); - - std::map envDict; - for(StringList::const_iterator it = env.begin(); it != env.begin(); ++it) { - size_t delimiter_pos = it->find('='); - envDict.insert(std::make_pair(it->substr(0, delimiter_pos), it->substr(delimiter_pos + 1))); - } - std::vector env; - for(std::map::iterator it = envDict.begin(); it != envDict.end(); ++it) { - env.insert(env.end(), it->first.begin(), it->first.end()); - env.push_back(0); - } - env.push_back(0); - - if(!CreateProcessA(NULL, - &arguments[0], - NULL, - NULL, - false, - NULL, - &env[0], - NULL, - &startup_info, - &process_info_ - )) - { - cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' CreateProcess() error: " << GetLastError(); - return; - } -} - -int SysExec::waitForScript() -{ - DWORD result = WaitForSingleObject(process_info_.hProcess, INFINITE); - assert(WAIT_OBJECT_0 == result); // WAIT_FAILED, WAIT_TIMEOUT ... ??? - bool success = GetExitCodeProcess(process_info_.hProcess, &return_code_) != 0; - assert(true == success); // false -> HU? - - CloseHandle(process_info_.hProcess); - CloseHandle(process_info_.hThread); - closed_ = true; - - return static_cast(return_code_); -} - -void SysExec::waitAndDestroy(SysExec*& s) -{ - if(!s) - return; - - s->waitForScript(); - cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << s->return_code_; - - delete(s); - s = NULL; -} - -#endif // ANYTUN_sysexec_hpp_INCLUDED +/* + * anytun + * + * The secure anycast tunneling protocol (satp) defines a protocol used + * for communication between any combination of unicast and anycast + * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel + * mode and allows tunneling of every ETHER TYPE protocol (e.g. + * ethernet, ip, arp ...). satp directly includes cryptography and + * message authentication based on the methodes used by SRTP. It is + * intended to deliver a generic, scaleable and secure solution for + * tunneling and relaying of packets of any protocol. + * + * + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Christian Pointner + * + * This file is part of Anytun. + * + * Anytun 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 3 of the License, or + * any later version. + * + * Anytun 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 anytun. If not, see . + */ +#pragma once +#ifndef ANYTUN_sysexec_hpp_INCLUDED +#define ANYTUN_sysexec_hpp_INCLUDED + +#include +#include // todo remove +#include + +SysExec::~SysExec() +{ + if(!closed_) { + CloseHandle(process_info_.hProcess); + CloseHandle(process_info_.hThread); + } +} + +STARTUPINFOA getStartupInfo() +{ + STARTUPINFOA startup_info; + startup_info.cb = sizeof(STARTUPINFOA); + GetStartupInfoA(&startup_info); + + //startup_info.dwFlags = STARTF_USESTDHANDLES; + //startup_info.hStdInput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; + //startup_info.hStdOutput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; + //startup_info.hStdError = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; + startup_info.dwFlags |= STARTF_USESHOWWINDOW; + startup_info.wShowWindow = SW_HIDE; + + return startup_info; +} + +char const* const BATCH_FILE_EXTS[] = { ".bat", ".cmd" }; +int const BATCH_FILE_EXTS_COUNT = sizeof(BATCH_FILE_EXTS) / sizeof(BATCH_FILE_EXTS[0]); + +bool endsWith(std::string const& string, std::string const& suffix) +{ + return string.find(suffix, string.size() - suffix.size()) != std::string::npos; +} + +void SysExec::doExec(StringVector args, StringList env) +{ + std::vector arguments; + + bool isBatchFile = false; + for(int i = 0; i < BATCH_FILE_EXTS_COUNT; ++i) { + if(endsWith(script_, BATCH_FILE_EXTS[i])) { + isBatchFile = true; + break; + } + } + + if(isBatchFile) { + std::string const BATCH_INTERPRETER = "cmd /c \""; + arguments.insert(arguments.end(), BATCH_INTERPRETER.begin(), BATCH_INTERPRETER.end()); + } + arguments.push_back('\"'); + arguments.insert(arguments.end(), script_.begin(), script_.end()); + arguments.push_back('\"'); + arguments.push_back(' '); + + for(StringVector::const_iterator it = args.begin(); it != args.end(); ++it) { + arguments.push_back('\"'); + arguments.insert(arguments.end(), it->begin(), it->end()); + arguments.push_back('\"'); + arguments.push_back(' '); + } + + if(isBatchFile) { + arguments.push_back('\"'); + } + arguments.push_back(0); + + STARTUPINFOA startup_info = getStartupInfo(); + + std::map envDict; + for(StringList::const_iterator it = env.begin(); it != env.begin(); ++it) { + size_t delimiter_pos = it->find('='); + envDict.insert(std::make_pair(it->substr(0, delimiter_pos), it->substr(delimiter_pos + 1))); + } + std::vector env; + for(std::map::iterator it = envDict.begin(); it != envDict.end(); ++it) { + env.insert(env.end(), it->first.begin(), it->first.end()); + env.push_back(0); + } + env.push_back(0); + + if(!CreateProcessA(NULL, + &arguments[0], + NULL, + NULL, + false, + NULL, + &env[0], + NULL, + &startup_info, + &process_info_ + )) { + cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' CreateProcess() error: " << GetLastError(); + return; + } +} + +int SysExec::waitForScript() +{ + DWORD result = WaitForSingleObject(process_info_.hProcess, INFINITE); + assert(WAIT_OBJECT_0 == result); // WAIT_FAILED, WAIT_TIMEOUT ... ??? + bool success = GetExitCodeProcess(process_info_.hProcess, &return_code_) != 0; + assert(true == success); // false -> HU? + + CloseHandle(process_info_.hProcess); + CloseHandle(process_info_.hThread); + closed_ = true; + + return static_cast(return_code_); +} + +void SysExec::waitAndDestroy(SysExec*& s) +{ + if(!s) { + return; + } + + s->waitForScript(); + cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << s->return_code_; + + delete(s); + s = NULL; +} + +#endif // ANYTUN_sysexec_hpp_INCLUDED diff --git a/src/win32/tunDevice.cpp b/src/win32/tunDevice.cpp index 6e6c83d..bd7794f 100644 --- a/src/win32/tunDevice.cpp +++ b/src/win32/tunDevice.cpp @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -47,21 +47,24 @@ #define MIN_TAP_VER_MAJOR 8 #define MIN_TAP_VER_MINOR 2 -TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, u_int16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400) +TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400) { - if(conf_.type_ != TYPE_TUN && conf_.type_ != TYPE_TAP) + if(conf_.type_ != TYPE_TUN && conf_.type_ != TYPE_TAP) { AnytunError::throwErr() << "unable to recognize type of device (tun or tap)"; + } handle_ = INVALID_HANDLE_VALUE; - if(!getAdapter(dev_name)) + if(!getAdapter(dev_name)) { AnytunError::throwErr() << "can't find any suitable device"; + } if(handle_ == INVALID_HANDLE_VALUE) { std::stringstream tapname; - tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX; + tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX; handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0); - if(handle_ == INVALID_HANDLE_VALUE) + if(handle_ == INVALID_HANDLE_VALUE) { AnytunError::throwErr() << "Unable to open device: " << actual_node_ << " (" << actual_name_ << "): " << AnytunErrno(GetLastError()); + } } DWORD err; @@ -90,15 +93,16 @@ TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifc } } - if(ifcfg_addr != "") + if(ifcfg_addr != "") { do_ifconfig(); + } int status = true; err = performIoControl(TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to set device media status: " << AnytunErrno(err); - } + } roverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); woverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); @@ -108,45 +112,50 @@ bool TunDevice::getAdapter(std::string const& dev_name) { RegistryKey akey; DWORD err = akey.open(HKEY_LOCAL_MACHINE, ADAPTER_KEY, KEY_ENUMERATE_SUB_KEYS); - if(err != ERROR_SUCCESS) + if(err != ERROR_SUCCESS) { AnytunError::throwErr() << "Unable to open registry key (HKLM\\" << ADAPTER_KEY << "): " << AnytunErrno(err); - + } + bool found = false; for(int i=0; ; ++i) { RegistryKey ckey; DWORD err = akey.getSubKey(i, ckey, KEY_QUERY_VALUE); - if(err == ERROR_NO_MORE_ITEMS) + if(err == ERROR_NO_MORE_ITEMS) { break; - if(err != ERROR_SUCCESS) + } + if(err != ERROR_SUCCESS) { continue; + } try { - if(ckey["ComponentId"] != TAP_COMPONENT_ID) + if(ckey["ComponentId"] != TAP_COMPONENT_ID) { continue; + } actual_node_ = ckey["NetCfgInstanceId"]; RegistryKey nkey; std::stringstream keyname; keyname << NETWORK_CONNECTIONS_KEY << "\\" << actual_node_ << "\\Connection"; err = nkey.open(HKEY_LOCAL_MACHINE, keyname.str().c_str(), KEY_QUERY_VALUE);; - if(err != ERROR_SUCCESS) + if(err != ERROR_SUCCESS) { continue; - - actual_name_ = nkey["Name"]; - } catch(AnytunErrno&) { continue; } + } + + actual_name_ = nkey["Name"]; + } catch(AnytunErrno&) { continue; } if(dev_name != "") { if(dev_name == actual_name_) { found = true; break; } - } - else { + } else { std::stringstream tapname; tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX; handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0); - if(handle_ == INVALID_HANDLE_VALUE) + if(handle_ == INVALID_HANDLE_VALUE) { continue; + } found = true; break; } @@ -163,18 +172,19 @@ DWORD TunDevice::performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBu OVERLAPPED overlapped; overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); overlapped.Offset = 0; - overlapped.OffsetHigh = 0; - + overlapped.OffsetHigh = 0; + DWORD len; if(!DeviceIoControl(handle_, controlCode, inBuffer, inBufferSize, outBuffer, outBufferSize, &len, &overlapped)) { DWORD err = GetLastError(); if(err == ERROR_IO_PENDING) { WaitForSingleObject(overlapped.hEvent, INFINITE); - if(!GetOverlappedResult(handle_, &overlapped, &len, FALSE)) + if(!GetOverlappedResult(handle_, &overlapped, &len, FALSE)) { return GetLastError(); - } - else + } + } else { return GetLastError(); + } } return ERROR_SUCCESS; } @@ -182,27 +192,30 @@ DWORD TunDevice::performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBu TunDevice::~TunDevice() { - if(handle_ != INVALID_HANDLE_VALUE) + if(handle_ != INVALID_HANDLE_VALUE) { CloseHandle(handle_); - if(roverlapped_.hEvent != INVALID_HANDLE_VALUE) + } + if(roverlapped_.hEvent != INVALID_HANDLE_VALUE) { CloseHandle(roverlapped_.hEvent); - if(woverlapped_.hEvent != INVALID_HANDLE_VALUE) + } + if(woverlapped_.hEvent != INVALID_HANDLE_VALUE) { CloseHandle(woverlapped_.hEvent); + } } int TunDevice::fix_return(int ret, size_t pi_length) const { -// nothing to be done here - return 0; + // nothing to be done here + return 0; } -int TunDevice::read(u_int8_t* buf, u_int32_t len) +int TunDevice::read(uint8_t* buf, uint32_t len) { DWORD lenout; roverlapped_.Offset = 0; - roverlapped_.OffsetHigh = 0; + roverlapped_.OffsetHigh = 0; ResetEvent(roverlapped_.hEvent); - + if(!ReadFile(handle_, buf, len, &lenout, &roverlapped_)) { DWORD err = GetLastError(); if(err == ERROR_IO_PENDING) { @@ -211,8 +224,7 @@ int TunDevice::read(u_int8_t* buf, u_int32_t len) cLog.msg(Log::PRIO_ERROR) << "Error while trying to get overlapped result: " << AnytunErrno(GetLastError()); return -1; } - } - else { + } else { cLog.msg(Log::PRIO_ERROR) << "Error while reading from device: " << AnytunErrno(GetLastError()); return -1; } @@ -220,14 +232,14 @@ int TunDevice::read(u_int8_t* buf, u_int32_t len) return lenout; } -int TunDevice::write(u_int8_t* buf, u_int32_t len) +int TunDevice::write(uint8_t* buf, uint32_t len) { DWORD lenout; woverlapped_.Offset = 0; - woverlapped_.OffsetHigh = 0; + woverlapped_.OffsetHigh = 0; ResetEvent(woverlapped_.hEvent); - if(!WriteFile(handle_, buf, len, &lenout, &woverlapped_)) { + if(!WriteFile(handle_, buf, len, &lenout, &woverlapped_)) { DWORD err = GetLastError(); if(err == ERROR_IO_PENDING) { WaitForSingleObject(woverlapped_.hEvent, INFINITE); @@ -235,18 +247,17 @@ int TunDevice::write(u_int8_t* buf, u_int32_t len) cLog.msg(Log::PRIO_ERROR) << "Error while trying to get overlapped result: " << AnytunErrno(GetLastError()); return -1; } - } - else { + } else { cLog.msg(Log::PRIO_ERROR) << "Error while writing to device: " << AnytunErrno(GetLastError()); return -1; } } - return lenout; + return lenout; } void TunDevice::init_post() { -// nothing to be done here + // nothing to be done here } void TunDevice::do_ifconfig() @@ -260,18 +271,18 @@ void TunDevice::do_ifconfig() if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to set device dhcp masq mode: " << AnytunErrno(err); - } + } u_long mtu; err = performIoControl(TAP_IOCTL_GET_MTU, &mtu, sizeof(mtu), &mtu, sizeof(mtu)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to get device mtu: " << AnytunErrno(err); - } - conf_.mtu_ = static_cast(mtu); + } + conf_.mtu_ = static_cast(mtu); } void TunDevice::waitUntilReady() { -// nothing to be done here + // nothing to be done here } diff --git a/src/win32/winService.cpp b/src/win32/winService.cpp index 8c17420..084fa85 100644 --- a/src/win32/winService.cpp +++ b/src/win32/winService.cpp @@ -1,197 +1,205 @@ -/* - * anytun - * - * The secure anycast tunneling protocol (satp) defines a protocol used - * for communication between any combination of unicast and anycast - * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel - * mode and allows tunneling of every ETHER TYPE protocol (e.g. - * ethernet, ip, arp ...). satp directly includes cryptography and - * message authentication based on the methodes used by SRTP. It is - * intended to deliver a generic, scaleable and secure solution for - * tunneling and relaying of packets of any protocol. - * - * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, - * Christian Pointner - * - * This file is part of Anytun. - * - * Anytun 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 3 of the License, or - * any later version. - * - * Anytun 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 anytun. If not, see . - */ - -#ifdef WIN_SERVICE - -#include - -#include - -#include "winService.h" -#include "../log.h" -#include "../anytunError.h" -#include "../threadUtils.hpp" - -void WinService::install() -{ - SC_HANDLE schSCManager; - SC_HANDLE schService; - char szPath[MAX_PATH]; - - if(!GetModuleFileNameA(NULL, szPath, MAX_PATH)) - AnytunError::throwErr() << "Error on GetModuleFileName: " << AnytunErrno(GetLastError()); - - schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if(NULL == schSCManager) - AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError()); - - schService = CreateServiceA(schSCManager, SVC_NAME, SVC_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, - SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, NULL, NULL); - if(schService == NULL) { - CloseServiceHandle(schSCManager); - AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError()); - } - - std::cout << "Service installed successfully" << std::endl; - - CloseServiceHandle(schService); - CloseServiceHandle(schSCManager); -} - -void WinService::uninstall() -{ - SC_HANDLE schSCManager; - SC_HANDLE schService; - - schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if(NULL == schSCManager) - AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError()); - - schService = OpenServiceA(schSCManager, SVC_NAME, SERVICE_ALL_ACCESS); - if(schService == NULL) { - CloseServiceHandle(schSCManager); - AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError()); - } - - if(!DeleteService(schService)) { - CloseServiceHandle(schService); - CloseServiceHandle(schSCManager); - AnytunError::throwErr() << "Error on DeleteService: " << AnytunErrno(GetLastError()); - } - - std::cout << "Service uninstalled successfully" << std::endl; - - CloseServiceHandle(schService); - CloseServiceHandle(schSCManager); -} - -void WinService::start() -{ - SERVICE_TABLE_ENTRY DispatchTable[] = { - {SVC_NAME, (LPSERVICE_MAIN_FUNCTION)WinService::main }, - {NULL, NULL} - }; - - if(!StartServiceCtrlDispatcherA(DispatchTable)) - AnytunError::throwErr() << "Error on StartServiceCtrlDispatcher: " << AnytunErrno(GetLastError()); -} - -int real_main(int argc, char* argv[], WinService& service); - -VOID WINAPI WinService::main(DWORD dwArgc, LPTSTR *lpszArgv) -{ - WinService service; - - service.status_handle_ = RegisterServiceCtrlHandlerA(SVC_NAME, WinService::ctrlHandler); - if(!service.status_handle_) { - cLog.msg(Log::PRIO_ERROR) << "Error on RegisterServiceCtrlHandler: " << AnytunErrno(GetLastError()); - return; - } - service.status_.dwServiceType = SERVICE_WIN32_OWN_PROCESS; - service.status_.dwServiceSpecificExitCode = 0; - service.reportStatus(SERVICE_START_PENDING, NO_ERROR); - - real_main(dwArgc, lpszArgv, service); - - service.reportStatus(SERVICE_STOPPED, NO_ERROR); -} - -VOID WINAPI WinService::ctrlHandler(DWORD dwCtrl) -{ - gSignalController.inject(dwCtrl); -} - -int WinService::handleCtrlSignal(int sig, const std::string& msg) -{ - switch(sig) { - case SERVICE_CONTROL_STOP: { - reportStatus(SERVICE_STOP_PENDING, NO_ERROR); - cLog.msg(Log::PRIO_NOTICE) << "received service stop signal, exitting"; - return 1; - } - case SERVICE_CONTROL_INTERROGATE: break; - default: break; - } - reportStatus(status_.dwCurrentState, NO_ERROR); - - return 0; -} - -void WinService::reportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode) -{ - static DWORD dwCheckPoint = 1; - - status_.dwCurrentState = dwCurrentState; - status_.dwWin32ExitCode = dwWin32ExitCode; - status_.dwWaitHint = 0; - - if((dwCurrentState == SERVICE_START_PENDING) || - (dwCurrentState == SERVICE_STOP_PENDING)) - status_.dwControlsAccepted = 0; - else - status_.dwControlsAccepted = SERVICE_ACCEPT_STOP; - - if((dwCurrentState == SERVICE_RUNNING) || - (dwCurrentState == SERVICE_STOPPED)) - status_.dwCheckPoint = 0; - else - status_.dwCheckPoint = dwCheckPoint++; - - SetServiceStatus(status_handle_, &status_); -} - -void WinService::initPrivs(std::string const& username, std::string const& groupname) -{ -// nothing here -} - -void WinService::dropPrivs() -{ -// nothing here -} - -void WinService::chroot(std::string const& dir) -{ -// nothing here -} - -void WinService::daemonize() -{ -// nothing here -} - -bool WinService::isDaemonized() -{ - return true; -} - -#endif +/* + * anytun + * + * The secure anycast tunneling protocol (satp) defines a protocol used + * for communication between any combination of unicast and anycast + * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel + * mode and allows tunneling of every ETHER TYPE protocol (e.g. + * ethernet, ip, arp ...). satp directly includes cryptography and + * message authentication based on the methodes used by SRTP. It is + * intended to deliver a generic, scaleable and secure solution for + * tunneling and relaying of packets of any protocol. + * + * + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Christian Pointner + * + * This file is part of Anytun. + * + * Anytun 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 3 of the License, or + * any later version. + * + * Anytun 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 anytun. If not, see . + */ + +#ifdef WIN_SERVICE + +#include + +#include + +#include "winService.h" +#include "../log.h" +#include "../anytunError.h" +#include "../threadUtils.hpp" + +void WinService::install() +{ + SC_HANDLE schSCManager; + SC_HANDLE schService; + char szPath[MAX_PATH]; + + if(!GetModuleFileNameA(NULL, szPath, MAX_PATH)) { + AnytunError::throwErr() << "Error on GetModuleFileName: " << AnytunErrno(GetLastError()); + } + + schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(NULL == schSCManager) { + AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError()); + } + + schService = CreateServiceA(schSCManager, SVC_NAME, SVC_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, + SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, NULL, NULL); + if(schService == NULL) { + CloseServiceHandle(schSCManager); + AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError()); + } + + std::cout << "Service installed successfully" << std::endl; + + CloseServiceHandle(schService); + CloseServiceHandle(schSCManager); +} + +void WinService::uninstall() +{ + SC_HANDLE schSCManager; + SC_HANDLE schService; + + schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(NULL == schSCManager) { + AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError()); + } + + schService = OpenServiceA(schSCManager, SVC_NAME, SERVICE_ALL_ACCESS); + if(schService == NULL) { + CloseServiceHandle(schSCManager); + AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError()); + } + + if(!DeleteService(schService)) { + CloseServiceHandle(schService); + CloseServiceHandle(schSCManager); + AnytunError::throwErr() << "Error on DeleteService: " << AnytunErrno(GetLastError()); + } + + std::cout << "Service uninstalled successfully" << std::endl; + + CloseServiceHandle(schService); + CloseServiceHandle(schSCManager); +} + +void WinService::start() +{ + SERVICE_TABLE_ENTRY DispatchTable[] = { + {SVC_NAME, (LPSERVICE_MAIN_FUNCTION)WinService::main }, + {NULL, NULL} + }; + + if(!StartServiceCtrlDispatcherA(DispatchTable)) { + AnytunError::throwErr() << "Error on StartServiceCtrlDispatcher: " << AnytunErrno(GetLastError()); + } +} + +int real_main(int argc, char* argv[], WinService& service); + +VOID WINAPI WinService::main(DWORD dwArgc, LPTSTR* lpszArgv) +{ + WinService service; + + service.status_handle_ = RegisterServiceCtrlHandlerA(SVC_NAME, WinService::ctrlHandler); + if(!service.status_handle_) { + cLog.msg(Log::PRIO_ERROR) << "Error on RegisterServiceCtrlHandler: " << AnytunErrno(GetLastError()); + return; + } + service.status_.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + service.status_.dwServiceSpecificExitCode = 0; + service.reportStatus(SERVICE_START_PENDING, NO_ERROR); + + real_main(dwArgc, lpszArgv, service); + + service.reportStatus(SERVICE_STOPPED, NO_ERROR); +} + +VOID WINAPI WinService::ctrlHandler(DWORD dwCtrl) +{ + gSignalController.inject(dwCtrl); +} + +int WinService::handleCtrlSignal(int sig, const std::string& msg) +{ + switch(sig) { + case SERVICE_CONTROL_STOP: { + reportStatus(SERVICE_STOP_PENDING, NO_ERROR); + cLog.msg(Log::PRIO_NOTICE) << "received service stop signal, exitting"; + return 1; + } + case SERVICE_CONTROL_INTERROGATE: + break; + default: + break; + } + reportStatus(status_.dwCurrentState, NO_ERROR); + + return 0; +} + +void WinService::reportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode) +{ + static DWORD dwCheckPoint = 1; + + status_.dwCurrentState = dwCurrentState; + status_.dwWin32ExitCode = dwWin32ExitCode; + status_.dwWaitHint = 0; + + if((dwCurrentState == SERVICE_START_PENDING) || + (dwCurrentState == SERVICE_STOP_PENDING)) { + status_.dwControlsAccepted = 0; + } else { + status_.dwControlsAccepted = SERVICE_ACCEPT_STOP; + } + + if((dwCurrentState == SERVICE_RUNNING) || + (dwCurrentState == SERVICE_STOPPED)) { + status_.dwCheckPoint = 0; + } else { + status_.dwCheckPoint = dwCheckPoint++; + } + + SetServiceStatus(status_handle_, &status_); +} + +void WinService::initPrivs(std::string const& username, std::string const& groupname) +{ + // nothing here +} + +void WinService::dropPrivs() +{ + // nothing here +} + +void WinService::chroot(std::string const& dir) +{ + // nothing here +} + +void WinService::daemonize() +{ + // nothing here +} + +bool WinService::isDaemonized() +{ + return true; +} + +#endif diff --git a/src/win32/winService.h b/src/win32/winService.h index 9c95400..91853fe 100644 --- a/src/win32/winService.h +++ b/src/win32/winService.h @@ -11,7 +11,7 @@ * tunneling and relaying of packets of any protocol. * * - * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, + * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. @@ -41,12 +41,12 @@ class WinService { public: - #define SVC_NAME "anytun" +#define SVC_NAME "anytun" static void install(); static void uninstall(); static void start(); - static VOID WINAPI main(DWORD dwArgc, LPTSTR *lpszArgv); + static VOID WINAPI main(DWORD dwArgc, LPTSTR* lpszArgv); static VOID WINAPI ctrlHandler(DWORD dwCtrl); void reportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode); @@ -61,8 +61,8 @@ public: private: WinService() {}; ~WinService() {}; - WinService(const WinService &w); - void operator=(const WinService &w); + WinService(const WinService& w); + void operator=(const WinService& w); SERVICE_STATUS status_; SERVICE_STATUS_HANDLE status_handle_; diff --git a/version b/version index 1c09c74..42045ac 100644 --- a/version +++ b/version @@ -1 +1 @@ -0.3.3 +0.3.4 -- 2.1.4