-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
* 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
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
----------
# sudo make remove
-This removes everytthing except for the config files
+This removes everything except for the config files
# sudo make purge
'\" t
.\" Title: anytun-config
.\" Author: [see the "AUTHORS" section]
-.\" Generator: DocBook XSL Stylesheets v1.75.1 <http://docbook.sf.net/>
-.\" Date: 02/16/2010
-.\" Manual: anytun-config user manual
-.\" Source: anytun 0.3.3
+.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
+.\" 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
.\" -----------------------------------------------------------------
.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<kd\-prf type>\fR\fR
'\" t
.\" Title: anytun-controld
.\" Author: [see the "AUTHORS" section]
-.\" Generator: DocBook XSL Stylesheets v1.75.1 <http://docbook.sf.net/>
-.\" Date: 02/16/2010
-.\" Manual: anytun-controld user manual
-.\" Source: anytun 0.3.3
+.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
+.\" 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
.\" -----------------------------------------------------------------
'\" t
.\" Title: anytun-showtables
.\" Author: [see the "AUTHORS" section]
-.\" Generator: DocBook XSL Stylesheets v1.75.1 <http://docbook.sf.net/>
-.\" Date: 02/16/2010
-.\" Manual: anytun-showtables user manual
-.\" Source: anytun 0.3.3
+.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
+.\" 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
.\" -----------------------------------------------------------------
.RS 4
.\}
.nf
-# perl \-ne \'chomp; print\' < routingtable | \&./anytun\-showtables
+# perl \-ne \*(Aqchomp; print\*(Aq < routingtable | \&./anytun\-showtables
.fi
.if n \{\
.RE
'\" t
.\" Title: anytun
.\" Author: [see the "AUTHORS" section]
-.\" Generator: DocBook XSL Stylesheets v1.75.1 <http://docbook.sf.net/>
-.\" Date: 02/16/2010
-.\" Manual: anytun user manual
-.\" Source: anytun 0.3.3
+.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
+.\" 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
.\" -----------------------------------------------------------------
.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<kd\-prf type>\fR\fR
#! /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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
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;
SyncQueue* queue_ = reinterpret_cast<SyncQueue*>(p);
std::map<std::string, ListenerData*> 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<std::string, ListenerData*>::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());
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();
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)
}
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()
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<ThreadParam*>(p);
+ ThreadParam* param = reinterpret_cast<ThreadParam*>(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;
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);
}
}
}
- 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();
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<boost::thread *> 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<boost::thread *> 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<pthread_t> 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<pthread_t> 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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new CallIdQueue();
-
+ }
+
return *inst;
}
CallIdQueue::~CallIdQueue()
{
- while(!callids_.empty())
+ while(!callids_.empty()) {
pop();
+ }
}
std::string& CallIdQueue::front()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
class CallIdQueue
{
public:
- static CallIdQueue& instance();
-
+ static CallIdQueue& instance();
+
std::string& front();
void push(std::string c);
void pop();
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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);
{
CommandHandler* self = reinterpret_cast<CommandHandler*>(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);
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;
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]);
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;
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());
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);
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
}
}
{
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
proto::socket control_sock_;
std::string local_address_;
std::string local_port_;
- PortWindow& port_window_;
+ PortWindow& port_window_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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()
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()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include "../datatypes.h"
#include "../connectionParam.h"
#include "../networkAddress.h"
-typedef std::map<u_int16_t, ConnectionParam> ConnectionMap;
+typedef std::map<uint16_t, ConnectionParam> 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_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new Options();
-
+ }
+
return *inst;
}
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);
}
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
}
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()
progname_ = argv[0];
std::queue<std::string> 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_)
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;
}
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include <list>
#include <sstream>
-typedef struct OptionConnectTo
-{
+typedef struct OptionConnectTo {
std::string host;
std::string port;
};
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);
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;
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_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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)
{
}
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_ && ports_.find(port) !=ports_.end())
- port++;
- if (port>=end_port_)
- return 0;
- ports_.insert(port);
- return port;
+ uint16_t port= start_port_;
+ while(port<end_port_ && ports_.find(port) !=ports_.end()) {
+ port++;
+ }
+ if(port>=end_port_) {
+ return 0;
+ }
+ ports_.insert(port);
+ return port;
}
void PortWindow::clear()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
class PortWindow
{
public:
- typedef std::set<u_int16_t> PortSet;
+ typedef std::set<uint16_t> 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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
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<class Archive>
- 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?
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new RtpSessionTable();
+ }
return *inst;
}
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<RtpSessionMap::iterator, bool> ret = map_.insert(RtpSessionMap::value_type(call_id, NULL));
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");
}
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()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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_;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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);
+ };
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
-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;
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);
}
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
std::list<std::string> config_;
-void syncOnConnect(SyncTcpConnection * connptr)
+void syncOnConnect(SyncTcpConnection* connptr)
{
- for(std::list<std::string>::const_iterator it=config_.begin(); it!=config_.end();++it)
- {
+ for(std::list<std::string>::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();
}
}
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;
+ }
}
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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
}
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();
}
}
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<Cipher> c(CipherFactory::create(gOpt.getCipher(), KD_OUTBOUND));
- std::auto_ptr<AuthAlgo> a(AuthAlgoFactory::create(gOpt.getAuthAlgo(), KD_OUTBOUND) );
-
+ std::auto_ptr<AuthAlgo> 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<u_int32_t>(len) < PlainPacket::getHeaderLength())
- continue; // ignore short packets
+ if(static_cast<uint32_t>(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 "<<plain_packet.getDstAddr().toString();
- ConnectionMap::iterator cit;
+ }
+ //std::cout << "got Packet for plain "<<plain_packet.getDstAddr().toString();
+ ConnectionMap::iterator cit;
#ifndef NO_ROUTING
- if (!disableRouting)
- try {
- mux = gRoutingTable.getRoute(plain_packet.getDstAddr());
- //std::cout << " -> "<<mux << std::endl;
- cit = gConnectionList.getConnection(mux);
- } catch (std::exception&) { continue; } // no route
- else
- cit = gConnectionList.getBegin();
+ if(!disableRouting)
+ try {
+ mux = gRoutingTable.getRoute(plain_packet.getDstAddr());
+ //std::cout << " -> "<<mux << std::endl;
+ cit = gConnectionList.getConnection(mux);
+ } catch(std::exception&) { continue; } // no route
+ else {
+ cit = gConnectionList.getBegin();
+ }
#else
- cit = gConnectionList.getBegin();
+ cit = gConnectionList.getBegin();
#endif
- if(cit==gConnectionList.getEnd())
- continue; //no connection
- ConnectionParam & conn = cit->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();
}
}
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<Cipher> c(CipherFactory::create(gOpt.getCipher(), KD_INBOUND));
std::auto_ptr<AuthAlgo> 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<u_int32_t>(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<uint32_t>(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();
}
}
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));
}
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;
}
}
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);
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());
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();
}
}
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<u_int8_t>(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<uint8_t>(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;
}
-
-
+
+
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
};
std::ostream& operator<<(std::ostream& stream, AnytunErrno const& value);
-class ErrorStringBuilder
+class ErrorStringBuilder
{
public:
ErrorStringBuilder(ErrorStringBuilder const& src) { stream << src.stream.str(); };
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
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);
}
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
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) {\r
+ return false;\r
+ }\r
+\r
return true;
-
}
#endif
-
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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
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
#else
HMAC_CTX ctx_;
#endif
-
+
Buffer key_;
};
#endif
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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");
+ }
}
-
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
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();
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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;
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) {
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__)
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);
}
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;
}
#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<size_t>(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<struct ip*>(buf);
-
+ uint32_t type;
+ struct ip* hdr = reinterpret_cast<struct ip*>(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()
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);
void TunDevice::waitUntilReady()
{
- if(sys_exec_)
+ if(sys_exec_) {
SysExec::waitAndDestroy(sys_exec_);
+ }
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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;
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;
return;
}
- buf_ = new u_int8_t[real_length_];
+ buf_ = new uint8_t[real_length_];
if(!buf_) {
length_ = 0;
real_length_ = 0;
std::memcpy(buf_, data, length_);
}
-Buffer::Buffer(std::string hex_data, bool allow_realloc) : length_(static_cast<u_int32_t>(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<uint32_t>(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<length_; ++i)
- {
- u_int32_t tmp;
+
+ for(uint32_t i=0; i<length_; ++i) {
+ uint32_t tmp;
std::istringstream ss(std::string(hex_data.c_str(), i*2, 2));
- if(!(ss >> std::hex >> tmp)) tmp = 0;
- buf_[i] = static_cast<u_int8_t>(tmp);
+ if(!(ss >> std::hex >> tmp)) { tmp = 0; }
+ buf_[i] = static_cast<uint8_t>(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;
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;
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_;
}
{
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();
}
{
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();
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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;
}
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
}
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;
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_);
#endif
calcCtr(kd, seq_nr, sender_id, mux);
-
+
#ifndef USE_SSL_CRYPTO
err = gcry_cipher_setctr(handle_, ctr_.buf_, CTR_LENGTH);
if(err) {
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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_;
};
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
{
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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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");
+ }
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
# 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 <satp@wirdorange.org>
#
# This file is part of Anytun.
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
;;
--no-crypto)
CRYPTO_LIB='none'
- ;;
+ ;;
--enable-passphrase)
PASSPHRASE=1
;;
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
;;
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
;;
none)
CXXFLAGS=$CXXFLAGS' -DNO_CRYPT'
- echo "NO_CRYPT_OBJ = 1" >> include.mk
echo "disabling crypto"
;;
esac
EXAMPLESDIR=$PREFIX/share/examples
fi
-cat >> include.mk <<EOF
+cat > include.mk <<EOF
# this file was created automatically
-# do not edit this file directly
+# do not edit this file directly
# use ./configure instead
TARGET = $TARGET
-CXX = gcc
+CXX = g++
CXXFLAGS = $CXXFLAGS
-LD = gcc
+LD = g++
LDFLAGS = $LDFLAGS
STRIP = strip
INSTALL = install
ETCDIR := $ETCDIR
EOF
+if [ $CRYPTO_LIB = "none" ]; then
+ echo "NO_CRYPT_OBJ = 1" >> include.mk
+fi
+
if [ $INSTALLMANPAGE -eq 1 ]; then
echo "MANDIR := $MANDIR" >> include.mk
echo "installing manpage"
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
HOSTNAME=`hostname`
DATE=`date +"%d.%m.%Y %H:%M:%S %Z"`
-cat >> version.h <<EOF
-/*
+cat > version.h <<EOF
+/*
* anytun version info
*
* this file was created automatically
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new ConnectionList();
+ }
return *inst;
}
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<ConnectionMap::iterator, bool> 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));
}
const ConnectionMap::iterator ConnectionList::getEnd()
{
- Lock lock(mutex_);
- return connections_.end();
+ Lock lock(mutex_);
+ return connections_.end();
}
ConnectionMap::iterator ConnectionList::getBeginUnlocked()
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()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include "datatypes.h"
#include "connectionParam.h"
#include "networkAddress.h"
-typedef std::map<u_int16_t, ConnectionParam> ConnectionMap;
+typedef std::map<uint16_t, ConnectionParam> 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_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
}
-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_()
{
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include <gcrypt.h>
// 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<boost::mutex*>(*lock);
return 0;
}
-static int boost_mutex_lock(void **lock)
+static int boost_mutex_lock(void** lock)
{
reinterpret_cast<boost::mutex*>(*lock)->lock();
return 0;
}
-static int boost_mutex_unlock(void **lock)
+static int boost_mutex_unlock(void** lock)
{
reinterpret_cast<boost::mutex*>(*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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include <boost/cstdint.hpp>
#include <boost/integer_traits.hpp>
-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 <stdint.h> 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;
#include <windows.h>
#define ATTR_PACKED
typedef DWORD system_error_t;
-#endif
+#endif
#define MAX_PACKET_LENGTH 1600
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
}
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;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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<struct HeaderStruct*>(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<struct HeaderStruct*>(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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
/**
* 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
* 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
* 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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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) {
}
#ifndef USE_SSL_CRYPTO
- Buffer digest(static_cast<u_int32_t>(gcry_md_get_algo_dlen(GCRY_MD_SHA256)));
+ Buffer digest(static_cast<uint32_t>(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<const unsigned char*>(passphrase.c_str()), passphrase.length(), digest.getBuf());
#endif
master_key_.setLength(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) {
}
#ifndef USE_SSL_CRYPTO
- Buffer digest(static_cast<u_int32_t>(gcry_md_get_algo_dlen(GCRY_MD_SHA1)));
+ Buffer digest(static_cast<uint32_t>(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<const unsigned char*>(passphrase.c_str()), passphrase.length(), digest.getBuf());
#endif
master_salt_.setLength(length);
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;
}
#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
}
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
}
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);
#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;
}
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);
is_initialized_ = true;
}
-std::string AesIcmKeyDerivation::printType()
+std::string AesIcmKeyDerivation::printType()
{
ReadersLock lock(mutex_);
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) {
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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
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);
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<class Archive>
- 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<class Archive>
+ 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);
private:
void updateMasterKey() {};
- friend class boost::serialization::access;
- template<class Archive>
- void serialize(Archive & ar, const unsigned int version)
- {
- ar & boost::serialization::base_object<KeyDerivation>(*this);
- }
+ friend class boost::serialization::access;
+ template<class Archive>
+ void serialize(Archive& ar, const unsigned int version) {
+ ar& boost::serialization::base_object<KeyDerivation>(*this);
+ }
};
{
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);
bool calcCtr(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr);
- friend class boost::serialization::access;
- template<class Archive>
- void serialize(Archive & ar, const unsigned int version)
- {
- ar & boost::serialization::base_object<KeyDerivation>(*this);
- }
+ friend class boost::serialization::access;
+ template<class Archive>
+ void serialize(Archive& ar, const unsigned int version) {
+ ar& boost::serialization::base_object<KeyDerivation>(*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
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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");
+ }
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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<size_t>(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<struct iphdr *>(buf);
-
+ struct iphdr* hdr = reinterpret_cast<struct iphdr*>(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()
void TunDevice::waitUntilReady()
{
- if(sys_exec_)
+ if(sys_exec_) {
SysExec::waitAndDestroy(sys_exec_);
+ }
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
}
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new Log();
-
+ }
+
return *inst;
}
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)
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)
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";
}
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
class Log;
-class LogStringBuilder
+class LogStringBuilder
{
public:
LogStringBuilder(LogStringBuilder const& src);
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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";
}
}
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<size_t>(s.tellg()) - 1 : 0);
+ }
s.get(buff, 100);
- }
- else
+ } else {
buff[0] = 0;
+ }
return add(targetTypeFromString(type), prio, buff);
}
{
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;
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);
+ }
}
}
#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;
}
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 "";
}
}
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()
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;
}
LogTargetSyslog& LogTargetSyslog::setFacility(int f)
{
facility = f;
- if(opened)
+ if(opened) {
close();
+ }
open();
return *this;
}
{
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()
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;
LogTargetFile& LogTargetFile::setLogFilename(std::string l)
{
logfilename = l;
- if(opened)
+ if(opened) {
close();
+ }
open();
return *this;
}
LogTargetStdout::~LogTargetStdout()
{
- if(opened)
+ if(opened) {
close();
+ }
}
void LogTargetStdout::open()
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;
{
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;
}
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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
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);
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:
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;
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;
void open();
void close();
- void log(std::string msg, int prio);
+ void log(std::string msg, int prio);
static bool duplicateAllowed() { return false; };
private:
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:
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
}
{
}
-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<unsigned char,6> 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<unsigned char,6> 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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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++)
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
}
-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_<right.length_);
- return static_cast<NetworkAddress>(*this)<static_cast<NetworkAddress>(right);
+ if(network_address_type_!=right.network_address_type_) {
+ return false;
+ }
+ if(right.length_!=length_) {
+ return (length_<right.length_);
+ }
+ return static_cast<NetworkAddress>(*this)<static_cast<NetworkAddress>(right);
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- void serialize(Archive & ar, const unsigned int version)
- {
- ar & length_;
- ar & boost::serialization::base_object<NetworkAddress>(*this);
+ void serialize(Archive& ar, const unsigned int version) {
+ ar& length_;
+ ar& boost::serialization::base_object<NetworkAddress>(*this);
};
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
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;
}
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
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
}
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;
}
{
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";
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; \
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; \
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]); \
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])); \
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]; \
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]); \
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
#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
}
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()
#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] <username> change to this user" << std::endl;
std::cout << " [-g|--groupname] <groupname> change to this group" << std::endl;
std::cout << " [-C|--chroot] <path> chroot to this directory" << std::endl;
std::cout << " [-P|--write-pid] <path> write pid to this file" << std::endl;
- #endif
+#endif
#endif
#endif
#if defined(ANYTUN_OPTIONS) || defined(ANYCONF_OPTIONS)
- #ifndef NO_ROUTING
+#ifndef NO_ROUTING
std::cout << " [-R|--route] <net>/<prefix length> add a route to connection, can be invoked several times" << std::endl;
- #endif
+#endif
std::cout << " [-m|--mux] <mux-id> the multiplex id to use" << std::endl;
std::cout << " [-w|--window-size] <window size> seqence number window size" << std::endl;
- #ifndef NO_CRYPT
+#ifndef NO_CRYPT
std::cout << " [-k|--kd-prf] <kd-prf type> key derivation pseudo random function" << std::endl;
std::cout << " [-e|--role] <role> left (alice) or right (bob)" << std::endl;
- #ifndef NO_PASSPHRASE
+#ifndef NO_PASSPHRASE
std::cout << " [-E|--passphrase] <pass phrase> a passprhase to generate master key and salt from" << std::endl;
- #endif
+#endif
std::cout << " [-K|--key] <master key> master key to use for encryption" << std::endl;
std::cout << " [-A|--salt] <master 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] <cipher type> payload encryption algorithm" << std::endl;
std::cout << " [-a|--auth-algo] <algo type> message authentication algorithm" << std::endl;
std::cout << " [-b|--auth-tag-length] length of the auth tag" << std::endl;
- #endif
+#endif
#endif
}
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;
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;
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;
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;
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;
std::string Options::getBindToPort()
{
ReadersLock lock(mutex);
- return bind_to_.port;
+ return bind_to_.port;
}
Options& Options::setBindToPort(std::string b)
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
void init(std::string addrPort);
std::string addr;
- std::string port;
+ std::string port;
};
typedef std::list<OptionHost> HostList;
std::istream& operator>>(std::istream& stream, OptionHost& host);
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<OptionNetwork> NetworkList;
std::istream& operator>>(std::istream& stream, OptionNetwork& network);
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);
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();
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;
OptionHost remote_;
OptionHost local_sync_;
- HostList remote_sync_hosts_;
+ HostList remote_sync_hosts_;
std::string dev_name_;
std::string dev_type_;
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_;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
UDPPacketSource::~UDPPacketSource()
{
std::list<SocketsElement>::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_);
}
}
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);
it++;
}
- // prepare multi-socket recv
+ // prepare multi-socket recv
if(sockets_.size() > 1) {
std::list<SocketsElement>::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_);
result.it_ = it;
for(;;) {
it->sem_->down();
- result.len_ = static_cast<u_int32_t>(it->sock_->receive_from(boost::asio::buffer(it->buf_, it->len_), result.remote_));
+ result.len_ = static_cast<uint32_t>(it->sock_->receive_from(boost::asio::buffer(it->buf_, it->len_), result.remote_));
{
Lock lock(thread_result_mutex_);
thread_result_queue_.push(result);
}
}
-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<u_int32_t>(sockets_.front().sock_->receive_from(boost::asio::buffer(buf, len), remote));
+ if(sockets_.size() == 1) {
+ return static_cast<uint32_t>(sockets_.front().sock_->receive_from(boost::asio::buffer(buf, len), remote));
+ }
thread_result_sem_.down();
ThreadResult result;
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<SocketsElement>::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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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();
};
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;
void recv_thread(std::list<SocketsElement>::iterator it);
typedef struct {
- u_int32_t len_;
+ uint32_t len_;
PacketSourceEndpoint remote_;
std::list<SocketsElement>::iterator it_;
} ThreadResult;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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<payload_type_t*>(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<char *>(payload_);
- char ip_version = ip_version_ptr[0];
- ip_version >>=4;
- if(ip_version == 4)
+ char* ip_version_ptr = reinterpret_cast<char*>(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()
payload_type_ = reinterpret_cast<payload_type_t*>(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_;
}
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<char *>(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<char *>(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<char*>(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<char*>(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();
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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
* 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;
* 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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
}
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);
void registerSignalHandler(SignalController& ctrl, DaemonService& /*service*/)
{
sigset_t signal_set;
-
+
sigemptyset(&signal_set);
sigaddset(&signal_set, SIGINT);
sigaddset(&signal_set, SIGQUIT);
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);
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
SysExec::~SysExec()
{
- if(!closed_)
+ if(!closed_) {
close(pipefd_);
+ }
}
{
char** new_array;
new_array = static_cast<char**>(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;
}
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);
}
}
// 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);
}
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
using ::boost::asio::ip::tcp;
template<class Proto>
-void waitAndEnqueue(u_int32_t s, const std::string& addr, const std::string& port, boost::function<void(boost::asio::ip::basic_resolver_iterator<Proto>)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r)
+void waitAndEnqueue(uint32_t s, const std::string& addr, const std::string& port, boost::function<void(boost::asio::ip::basic_resolver_iterator<Proto>)> 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<void(boost::asio::ip::basic_resolver_iterator<udp>)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r)
+void waitAndEnqueue(uint32_t s, const std::string& addr, const std::string& port, boost::function<void(boost::asio::ip::basic_resolver_iterator<udp>)> 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<void(boost::asio::ip::basic_resolver_iterator<tcp>)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r)
+void waitAndEnqueue(uint32_t s, const std::string& addr, const std::string& port, boost::function<void(boost::asio::ip::basic_resolver_iterator<tcp>)> const& onResolve, ErrorCallback const& onError, ResolvAddrType r)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(s * 1000));
gResolver.resolveTcp(addr, port, onResolve, onError, r);
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 {
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new Resolver();
-
+ }
+
return *inst;
}
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()
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();
}
}
std::auto_ptr<udp::resolver::query> query;
if(addr != "") {
switch(r) {
- case IPV4_ONLY: query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v4(), addr, port)); break;
- case IPV6_ONLY: query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v6(), addr, port)); break;
- default: query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(addr, port)); break;
+ case IPV4_ONLY:
+ query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v4(), addr, port));
+ break;
+ case IPV6_ONLY:
+ query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v6(), addr, port));
+ break;
+ default:
+ query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(addr, port));
+ break;
}
- }
- else {
+ } else {
switch(r) {
- case IPV4_ONLY: query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v4(), port)); break;
- case IPV6_ONLY: query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v6(), port)); break;
- default: query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(port)); break;
+ case IPV4_ONLY:
+ query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v4(), port));
+ break;
+ case IPV6_ONLY:
+ query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(udp::v6(), port));
+ break;
+ default:
+ query = std::auto_ptr<udp::resolver::query>(new udp::resolver::query(port));
+ break;
}
}
UdpResolveHandler handler(addr, port, onResolve, onError, r);
std::auto_ptr<tcp::resolver::query> query;
if(addr != "") {
switch(r) {
- case IPV4_ONLY: query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v4(), addr, port)); break;
- case IPV6_ONLY: query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v6(), addr, port)); break;
- default: query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(addr, port)); break;
+ case IPV4_ONLY:
+ query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v4(), addr, port));
+ break;
+ case IPV6_ONLY:
+ query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v6(), addr, port));
+ break;
+ default:
+ query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(addr, port));
+ break;
}
- }
- else {
+ } else {
switch(r) {
- case IPV4_ONLY: query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v4(), port)); break;
- case IPV6_ONLY: query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v6(), port)); break;
- default: query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(port)); break;
+ case IPV4_ONLY:
+ query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v4(), port));
+ break;
+ case IPV6_ONLY:
+ query = std::auto_ptr<tcp::resolver::query>(new tcp::resolver::query(tcp::v6(), port));
+ break;
+ default:
+ query = std::auto_ptr<tcp::resolver::query>(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);
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
typedef ResolveHandler<boost::asio::ip::udp> UdpResolveHandler;
typedef ResolveHandler<boost::asio::ip::tcp> TcpResolveHandler;
-class Resolver
+class Resolver
{
public:
static Resolver& instance();
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
Lock lock(instMutex);
static instanceCleaner c;
- if(!inst)
+ if(!inst) {
inst = new RoutingTable();
+ }
return *inst;
}
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<RoutingMap::iterator, bool> 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()
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include "networkPrefix.h"
#include "routingTreeNode.h"
#include "boost/array.hpp"
-typedef std::map<NetworkPrefix,u_int16_t> RoutingMap;
+typedef std::map<NetworkPrefix,uint16_t> 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<RoutingMap,3> routes_;
- boost::array<RoutingTreeNode,3> 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<RoutingMap,3> routes_;
+ boost::array<RoutingTreeNode,3> root_;
Mutex mutex_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include "anytunError.h"
-class RoutingTree {
+class RoutingTree
+{
public:
template <class BinaryType>
- 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;
}
node->mux_=mux;
}
}
-
+
template <class BinaryType>
- 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;level<bytes.size();level++)
- {
- if (node->nodes_[bytes[level]])
- {
+ for(size_t level=0; level<bytes.size(); level++) {
+ if(node->nodes_[bytes[level]]) {
node=node->nodes_[bytes[level]];
- if(node->valid_)
- {
+ if(node->valid_) {
mux=node->mux_;
valid=1;
}
break;
}
}
- if(!valid)
+ if(!valid) {
AnytunError::throwErr() << "no route";
+ }
return mux;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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 << " -> " <<mux_ ;
- }
- std::cout << std::endl;
- for(int i=0; i<256; i++)
- {
- if ( nodes_[i])
- {
- for(int l=0;l<level;l++)
- std::cout << " ";
- std::cout << (int) i;
- nodes_[i]->print(level+1);
- }
- }
+ if(valid_) {
+ std::cout << " -> " <<mux_ ;
+ }
+ std::cout << std::endl;
+ for(int i=0; i<256; i++) {
+ if(nodes_[i]) {
+ for(int l=0; l<level; l++) {
+ std::cout << " ";
+ }
+ std::cout << (int) i;
+ nodes_[i]->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];
+ }
+}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<RoutingTreeNode *,256> nodes_;
+ // Mutex mutex_;
+ uint16_t mux_;
+ bool valid_;
+ boost::array<RoutingTreeNode*,256> nodes_;
friend class RoutingTree;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
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()) {
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
class SeqWindow;
-class SeqWindowElement {
+class SeqWindowElement
+{
public:
SeqWindowElement();
~SeqWindowElement();
seq_nr_t max_;
window_size_t pos_;
- u_int8_t* window_;
+ uint8_t* window_;
};
class SeqWindow
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<class Archive>
- 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<class Archive>
+ 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_;
}
-
+
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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)
#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)
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) {
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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<class Archive>
+ 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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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 "<<tmp.str()<< std::endl;
- boost::archive::text_iarchive ia(sync_command_stream);
- SyncCommand scom(cl_);
- ia >> 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 "<<tmp.str()<< std::endl;
+ boost::archive::text_iarchive ia(sync_command_stream);
+ SyncCommand scom(cl_);
+ ia >> 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<char, 1> 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<len; pos++)
- result<<buf[0];
- hasread+=len;
- }
+ size_t hasread = 0;
+ while(toread > hasread) {
+ //TODO read bigger buffers
+ boost::array<char, 1> 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<len; pos++)
+ result<<buf[0];
+ hasread+=len;
+ }
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
*/
#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_;
+ }
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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 " <<syncstr << std::endl;
- if (syncstr == "connection")
- ar & *scc_;
- if (syncstr == "route")
- ar & *src_;
-// std::cout << "syncstr done " <<syncstr << std::endl;
- }
+ 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 " <<syncstr << std::endl;
+ if(syncstr == "connection") {
+ ar & *scc_;
+ }
+ if(syncstr == "route") {
+ ar & *src_;
+ }
+ // std::cout << "syncstr done " <<syncstr << std::endl;
+ }
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
*/
#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_;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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;
+ }
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
// 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);
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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
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;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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_;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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<class Archive>
- 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_);
+ };
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
//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<AcceptorsElement>::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_);
}
}
{
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);
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()
void SyncServer::send(std::string message)
{
Lock lock(mutex_);
- for(std::list<SyncTcpConnection::pointer>::iterator it = conns_.begin() ;it != conns_.end(); ++it)
+ for(std::list<SyncTcpConnection::pointer>::iterator it = conns_.begin() ; it != conns_.end(); ++it) {
(*it)->Send(message);
+ }
}
void SyncServer::start_accept()
Lock lock(mutex_);
std::list<AcceptorsElement>::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;
}
}
void SyncServer::handle_accept(SyncTcpConnection::pointer new_connection, const boost::system::error_code& error, std::list<AcceptorsElement>::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_;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#include <list>
#include "syncTcpConnection.h"
-typedef boost::function<void (SyncTcpConnection *)> ConnectCallback;
+typedef boost::function<void (SyncTcpConnection*)> ConnectCallback;
class SyncServer
{
~SyncServer();
void onResolve(SyncTcpConnection::proto::resolver::iterator& it);
void onResolvError(const std::runtime_error& e);
-
+
void run();
void send(std::string message);
-
+
std::list<SyncTcpConnection::pointer> conns_;
-
+
private:
Mutex mutex_; //Mutex for list conns_
boost::asio::io_service io_service_;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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*/)
{
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
typedef boost::shared_ptr<SyncTcpConnection> 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<void(SyncTcpConnection *)> onConnect;
+ boost::function<void(SyncTcpConnection*)> 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_;
};
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
doExec(args, env);
}
-int SysExec::getReturnCode() const
+int SysExec::getReturnCode() const
{
return return_code_;
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
{
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_;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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();
#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_;
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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;
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);
}
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);
}
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
-/*\r
- * anytun\r
- *\r
- * The secure anycast tunneling protocol (satp) defines a protocol used\r
- * for communication between any combination of unicast and anycast\r
- * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel\r
- * mode and allows tunneling of every ETHER TYPE protocol (e.g.\r
- * ethernet, ip, arp ...). satp directly includes cryptography and\r
- * message authentication based on the methodes used by SRTP. It is\r
- * intended to deliver a generic, scaleable and secure solution for\r
- * tunneling and relaying of packets of any protocol.\r
- *\r
- *\r
- * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, \r
- * Christian Pointner <satp@wirdorange.org>\r
- *\r
- * This file is part of Anytun.\r
- *\r
- * Anytun is free software: you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation, either version 3 of the License, or\r
- * any later version.\r
- *\r
- * Anytun is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with anytun. If not, see <http://www.gnu.org/licenses/>.\r
- */\r
-#pragma once\r
-#ifndef ANYTUN_sysexec_hpp_INCLUDED\r
-#define ANYTUN_sysexec_hpp_INCLUDED\r
-\r
-#include <algorithm>\r
-#include <iostream> // todo remove\r
-#include <windows.h>\r
-\r
-SysExec::~SysExec()\r
-{\r
- if(!closed_) {\r
- CloseHandle(process_info_.hProcess);\r
- CloseHandle(process_info_.hThread);\r
- }\r
-}\r
-\r
-STARTUPINFOA getStartupInfo() {\r
- STARTUPINFOA startup_info;\r
- startup_info.cb = sizeof(STARTUPINFOA);\r
- GetStartupInfoA(&startup_info);\r
-\r
- //startup_info.dwFlags = STARTF_USESTDHANDLES;\r
- //startup_info.hStdInput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE;\r
- //startup_info.hStdOutput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE;\r
- //startup_info.hStdError = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE;\r
- startup_info.dwFlags |= STARTF_USESHOWWINDOW;\r
- startup_info.wShowWindow = SW_HIDE;\r
- \r
- return startup_info;\r
-}\r
-\r
-char const * const BATCH_FILE_EXTS[] = { ".bat", ".cmd" };\r
-int const BATCH_FILE_EXTS_COUNT = sizeof(BATCH_FILE_EXTS) / sizeof(BATCH_FILE_EXTS[0]);\r
-\r
-bool endsWith(std::string const& string, std::string const& suffix) {\r
- return string.find(suffix, string.size() - suffix.size()) != std::string::npos;\r
-}\r
-\r
-void SysExec::doExec(StringVector args, StringList env)\r
-{\r
- std::vector<char> arguments;\r
- \r
- bool isBatchFile = false;\r
- for(int i = 0; i < BATCH_FILE_EXTS_COUNT; ++i) {\r
- if(endsWith(script_, BATCH_FILE_EXTS[i])) {\r
- isBatchFile = true;\r
- break;\r
- }\r
- }\r
-\r
- if(isBatchFile) {\r
- std::string const BATCH_INTERPRETER = "cmd /c \"";\r
- arguments.insert(arguments.end(), BATCH_INTERPRETER.begin(), BATCH_INTERPRETER.end());\r
- }\r
- arguments.push_back('\"');\r
- arguments.insert(arguments.end(), script_.begin(), script_.end());\r
- arguments.push_back('\"');\r
- arguments.push_back(' ');\r
- \r
- for(StringVector::const_iterator it = args.begin(); it != args.end(); ++it) {\r
- arguments.push_back('\"');\r
- arguments.insert(arguments.end(), it->begin(), it->end());\r
- arguments.push_back('\"');\r
- arguments.push_back(' ');\r
- }\r
-\r
- if(isBatchFile) {\r
- arguments.push_back('\"');\r
- }\r
- arguments.push_back(0);\r
- \r
- STARTUPINFOA startup_info = getStartupInfo();\r
-\r
- std::map<std::string, std::string> envDict;\r
- for(StringList::const_iterator it = env.begin(); it != env.begin(); ++it) {\r
- size_t delimiter_pos = it->find('=');\r
- envDict.insert(std::make_pair(it->substr(0, delimiter_pos), it->substr(delimiter_pos + 1)));\r
- }\r
- std::vector<char> env;\r
- for(std::map<std::string, std::string>::iterator it = envDict.begin(); it != envDict.end(); ++it) {\r
- env.insert(env.end(), it->first.begin(), it->first.end());\r
- env.push_back(0);\r
- }\r
- env.push_back(0);\r
-\r
- if(!CreateProcessA(NULL,\r
- &arguments[0],\r
- NULL,\r
- NULL,\r
- false,\r
- NULL,\r
- &env[0],\r
- NULL,\r
- &startup_info,\r
- &process_info_\r
- ))\r
- {\r
- cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' CreateProcess() error: " << GetLastError();\r
- return;\r
- }\r
-}\r
-\r
-int SysExec::waitForScript()\r
-{\r
- DWORD result = WaitForSingleObject(process_info_.hProcess, INFINITE);\r
- assert(WAIT_OBJECT_0 == result); // WAIT_FAILED, WAIT_TIMEOUT ... ???\r
- bool success = GetExitCodeProcess(process_info_.hProcess, &return_code_) != 0;\r
- assert(true == success); // false -> HU?\r
-\r
- CloseHandle(process_info_.hProcess);\r
- CloseHandle(process_info_.hThread);\r
- closed_ = true;\r
-\r
- return static_cast<int>(return_code_);\r
-}\r
-\r
-void SysExec::waitAndDestroy(SysExec*& s)\r
-{\r
- if(!s)\r
- return;\r
-\r
- s->waitForScript();\r
- cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << s->return_code_;\r
-\r
- delete(s);\r
- s = NULL;\r
-}\r
-\r
-#endif // ANYTUN_sysexec_hpp_INCLUDED\r
+/*
+ * 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 <satp@wirdorange.org>
+ *
+ * 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 <http://www.gnu.org/licenses/>.
+ */
+#pragma once
+#ifndef ANYTUN_sysexec_hpp_INCLUDED
+#define ANYTUN_sysexec_hpp_INCLUDED
+
+#include <algorithm>
+#include <iostream> // todo remove
+#include <windows.h>
+
+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<char> 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<std::string, std::string> 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<char> env;
+ for(std::map<std::string, std::string>::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<int>(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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
#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;
}
}
- 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);
{
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;
}
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;
}
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) {
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;
}
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);
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()
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<u_int16_t>(mtu);
+ }
+ conf_.mtu_ = static_cast<uint16_t>(mtu);
}
void TunDevice::waitUntilReady()
{
-// nothing to be done here
+ // nothing to be done here
}
-/*\r
- * anytun\r
- *\r
- * The secure anycast tunneling protocol (satp) defines a protocol used\r
- * for communication between any combination of unicast and anycast\r
- * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel\r
- * mode and allows tunneling of every ETHER TYPE protocol (e.g.\r
- * ethernet, ip, arp ...). satp directly includes cryptography and\r
- * message authentication based on the methodes used by SRTP. It is\r
- * intended to deliver a generic, scaleable and secure solution for\r
- * tunneling and relaying of packets of any protocol.\r
- *\r
- *\r
- * Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl, \r
- * Christian Pointner <satp@wirdorange.org>\r
- *\r
- * This file is part of Anytun.\r
- *\r
- * Anytun is free software: you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation, either version 3 of the License, or\r
- * any later version.\r
- *\r
- * Anytun is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with anytun. If not, see <http://www.gnu.org/licenses/>.\r
- */\r
-\r
-#ifdef WIN_SERVICE\r
-\r
-#include <iostream>\r
-\r
-#include <windows.h>\r
-\r
-#include "winService.h"\r
-#include "../log.h"\r
-#include "../anytunError.h"\r
-#include "../threadUtils.hpp"\r
-\r
-void WinService::install()\r
-{\r
- SC_HANDLE schSCManager;\r
- SC_HANDLE schService;\r
- char szPath[MAX_PATH];\r
-\r
- if(!GetModuleFileNameA(NULL, szPath, MAX_PATH))\r
- AnytunError::throwErr() << "Error on GetModuleFileName: " << AnytunErrno(GetLastError());\r
-\r
- schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);\r
- if(NULL == schSCManager)\r
- AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError());\r
-\r
- schService = CreateServiceA(schSCManager, SVC_NAME, SVC_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, \r
- SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, NULL, NULL);\r
- if(schService == NULL) {\r
- CloseServiceHandle(schSCManager);\r
- AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError());\r
- }\r
-\r
- std::cout << "Service installed successfully" << std::endl; \r
-\r
- CloseServiceHandle(schService); \r
- CloseServiceHandle(schSCManager);\r
-}\r
-\r
-void WinService::uninstall()\r
-{\r
- SC_HANDLE schSCManager;\r
- SC_HANDLE schService;\r
-\r
- schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);\r
- if(NULL == schSCManager)\r
- AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError());\r
-\r
- schService = OpenServiceA(schSCManager, SVC_NAME, SERVICE_ALL_ACCESS);\r
- if(schService == NULL) {\r
- CloseServiceHandle(schSCManager);\r
- AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError());\r
- }\r
-\r
- if(!DeleteService(schService)) {\r
- CloseServiceHandle(schService); \r
- CloseServiceHandle(schSCManager);\r
- AnytunError::throwErr() << "Error on DeleteService: " << AnytunErrno(GetLastError());\r
- }\r
-\r
- std::cout << "Service uninstalled successfully" << std::endl; \r
-\r
- CloseServiceHandle(schService); \r
- CloseServiceHandle(schSCManager);\r
-}\r
-\r
-void WinService::start()\r
-{\r
- SERVICE_TABLE_ENTRY DispatchTable[] = {\r
- {SVC_NAME, (LPSERVICE_MAIN_FUNCTION)WinService::main },\r
- {NULL, NULL}\r
- };\r
-\r
- if(!StartServiceCtrlDispatcherA(DispatchTable))\r
- AnytunError::throwErr() << "Error on StartServiceCtrlDispatcher: " << AnytunErrno(GetLastError());\r
-}\r
-\r
-int real_main(int argc, char* argv[], WinService& service);\r
-\r
-VOID WINAPI WinService::main(DWORD dwArgc, LPTSTR *lpszArgv)\r
-{\r
- WinService service;\r
-\r
- service.status_handle_ = RegisterServiceCtrlHandlerA(SVC_NAME, WinService::ctrlHandler);\r
- if(!service.status_handle_) { \r
- cLog.msg(Log::PRIO_ERROR) << "Error on RegisterServiceCtrlHandler: " << AnytunErrno(GetLastError());\r
- return;\r
- }\r
- service.status_.dwServiceType = SERVICE_WIN32_OWN_PROCESS; \r
- service.status_.dwServiceSpecificExitCode = 0; \r
- service.reportStatus(SERVICE_START_PENDING, NO_ERROR);\r
- \r
- real_main(dwArgc, lpszArgv, service);\r
- \r
- service.reportStatus(SERVICE_STOPPED, NO_ERROR);\r
-}\r
-\r
-VOID WINAPI WinService::ctrlHandler(DWORD dwCtrl)\r
-{\r
- gSignalController.inject(dwCtrl);\r
-}\r
-\r
-int WinService::handleCtrlSignal(int sig, const std::string& msg)\r
-{\r
- switch(sig) {\r
- case SERVICE_CONTROL_STOP: {\r
- reportStatus(SERVICE_STOP_PENDING, NO_ERROR);\r
- cLog.msg(Log::PRIO_NOTICE) << "received service stop signal, exitting";\r
- return 1;\r
- }\r
- case SERVICE_CONTROL_INTERROGATE: break;\r
- default: break;\r
- }\r
- reportStatus(status_.dwCurrentState, NO_ERROR);\r
-\r
- return 0;\r
-}\r
-\r
-void WinService::reportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode)\r
-{\r
- static DWORD dwCheckPoint = 1;\r
-\r
- status_.dwCurrentState = dwCurrentState;\r
- status_.dwWin32ExitCode = dwWin32ExitCode;\r
- status_.dwWaitHint = 0;\r
-\r
- if((dwCurrentState == SERVICE_START_PENDING) ||\r
- (dwCurrentState == SERVICE_STOP_PENDING))\r
- status_.dwControlsAccepted = 0;\r
- else \r
- status_.dwControlsAccepted = SERVICE_ACCEPT_STOP;\r
-\r
- if((dwCurrentState == SERVICE_RUNNING) ||\r
- (dwCurrentState == SERVICE_STOPPED))\r
- status_.dwCheckPoint = 0;\r
- else\r
- status_.dwCheckPoint = dwCheckPoint++;\r
-\r
- SetServiceStatus(status_handle_, &status_);\r
-}\r
-\r
-void WinService::initPrivs(std::string const& username, std::string const& groupname)\r
-{\r
-// nothing here\r
-}\r
-\r
-void WinService::dropPrivs()\r
-{\r
-// nothing here\r
-}\r
-\r
-void WinService::chroot(std::string const& dir)\r
-{\r
-// nothing here\r
-}\r
-\r
-void WinService::daemonize()\r
-{\r
-// nothing here\r
-}\r
-\r
-bool WinService::isDaemonized()\r
-{\r
- return true;\r
-}\r
-\r
-#endif\r
+/*
+ * 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 <satp@wirdorange.org>
+ *
+ * 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 <http://www.gnu.org/licenses/>.
+ */
+
+#ifdef WIN_SERVICE
+
+#include <iostream>
+
+#include <windows.h>
+
+#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
* 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 <satp@wirdorange.org>
*
* This file is part of Anytun.
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);
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_;