Imported Upstream version 0.3
[anytun.git] / src / bsd / tunDevice.cpp
1 /*
2  *  anytun
3  *
4  *  The secure anycast tunneling protocol (satp) defines a protocol used
5  *  for communication between any combination of unicast and anycast
6  *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
7  *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
8  *  ethernet, ip, arp ...). satp directly includes cryptography and
9  *  message authentication based on the methodes used by SRTP.  It is
10  *  intended to deliver a generic, scaleable and secure solution for
11  *  tunneling and relaying of packets of any protocol.
12  *
13  *
14  *  Copyright (C) 2007-2008 Othmar Gsenger, Erwin Nindl, 
15  *                          Christian Pointner <satp@wirdorange.org>
16  *
17  *  This file is part of Anytun.
18  *
19  *  Anytun is free software: you can redistribute it and/or modify
20  *  it under the terms of the GNU General Public License version 3 as
21  *  published by the Free Software Foundation.
22  *
23  *  Anytun is distributed in the hope that it will be useful,
24  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  *  GNU General Public License for more details.
27  *
28  *  You should have received a copy of the GNU General Public License
29  *  along with anytun.  If not, see <http://www.gnu.org/licenses/>.
30  */
31
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <sys/socket.h>
36 #include <net/if.h>
37 #include <net/if_tun.h>
38 #include <sys/ioctl.h>
39 #include <sys/types.h>
40 #include <sys/uio.h>
41 #include <netinet/in_systm.h>
42 #include <netinet/in.h>
43 #include <netinet/ip.h>
44
45 #include <sstream>
46
47 #include "tunDevice.h"
48 #include "threadUtils.hpp"
49 #include "log.h"
50 #include "anytunError.h"
51
52 #define DEVICE_FILE_MAX 255
53
54 TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, std::string ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400)
55 {
56   std::string device_file = "/dev/";
57   bool dynamic = true;
58   if(dev_name != "") {
59     device_file.append(dev_name);
60     dynamic = false;
61   }
62 #if defined(__GNUC__) && defined(__OpenBSD__)
63   else if(conf_.type_ == TYPE_TUN || conf_.type_ == TYPE_TAP) {
64     device_file.append("tun");
65     actual_name_ = "tun";
66   }
67 #else
68   else if(conf_.type_ == TYPE_TUN) {
69     device_file.append("tun");
70     actual_name_ = "tun";
71   }
72   else if(conf_.type_ == TYPE_TAP) {
73     device_file.append("tap");
74     actual_name_ = "tap";
75   }
76 #endif
77   else
78     AnytunError::throwErr() << "unable to recognize type of device (tun or tap)";
79
80   u_int32_t dev_id=0;
81   if(dynamic) {
82     for(; dev_id <= DEVICE_FILE_MAX; ++dev_id) {
83       std::ostringstream ds;
84       ds << device_file;
85       ds << dev_id;
86       fd_ = ::open(ds.str().c_str(), O_RDWR);
87       if(fd_ >= 0)
88         break;
89     }
90   }
91   else
92     fd_ = ::open(device_file.c_str(), O_RDWR);
93
94   if(fd_ < 0) {
95     if(dynamic)
96       AnytunError::throwErr() << "can't open device file dynamically: no unused node left";
97     else
98       AnytunError::throwErr() << "can't open device file (" << device_file << "): " << AnytunErrno(errno);
99   }
100
101   if(dynamic) {
102     std::stringstream s;
103     s << actual_name_;
104     s << dev_id;
105     actual_name_ = s.str();
106   }
107   else
108     actual_name_ = dev_name;
109   
110   actual_node_ = device_file;
111
112   init_post();
113
114   if(ifcfg_addr != "")
115     do_ifconfig();
116 }
117
118 TunDevice::~TunDevice()
119 {
120   if(fd_ > 0)
121     ::close(fd_);
122 }
123
124 #if defined(__GNUC__) && defined(__OpenBSD__)
125
126 void TunDevice::init_post()
127 {
128   with_pi_ = true;
129   if(conf_.type_ == TYPE_TAP)
130     with_pi_ = false;
131   
132   struct tuninfo ti;  
133
134   if (ioctl(fd_, TUNGIFINFO, &ti) < 0) {
135     ::close(fd_);
136     AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno);
137   }
138   
139   ti.flags |= IFF_MULTICAST;
140   if(conf_.type_ == TYPE_TUN)
141     ti.flags &= ~IFF_POINTOPOINT;
142   
143   if (ioctl(fd_, TUNSIFINFO, &ti) < 0) {
144     ::close(fd_);
145     AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno);
146   }
147 }
148
149 #elif defined(__GNUC__) && defined(__FreeBSD__)
150
151 void TunDevice::init_post()
152 {
153   with_pi_ = true;
154   if(conf_.type_ == TYPE_TAP)
155     with_pi_ = false;
156
157   if(dev->type_ == TYPE_TUN) {
158     int arg = 0;
159     if(ioctl(dev->fd_, TUNSLMODE, &arg) < 0) {
160       ::close(fd_);
161       AnytunError::throwErr() << "can't disable link-layer mode for interface: " << AnytunErrno(errno);
162     }
163
164     arg = 1;
165     if(ioctl(dev->fd_, TUNSIFHEAD, &arg) < 0) {
166       ::close(fd_);
167       AnytunError::throwErr() << "can't enable multi-af modefor interface: " << AnytunErrno(errno);
168     }
169
170     arg = IFF_BROADCAST;
171     arg |= IFF_MULTICAST;
172     if(ioctl(dev->fd_, TUNSIFMODE, &arg) < 0) {
173       ::close(fd_);
174       AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno);
175     }
176   }
177 }
178
179 #elif defined(__GNUC__) && defined(__NetBSD__)
180
181 void TunDevice::init_post()
182 {
183   with_pi_ = false;
184
185   int arg = IFF_POINTOPOINT|IFF_MULTICAST;
186   ioctl(fd_, TUNSIFMODE, &arg);
187   arg = 0;
188   ioctl(fd_, TUNSLMODE, &arg);
189 }
190
191 #else
192  #error This Device works just for OpenBSD, FreeBSD or NetBSD
193 #endif
194
195 int TunDevice::fix_return(int ret, size_t pi_length) const
196 {
197   if(ret < 0)
198     return ret;
199
200   return (static_cast<size_t>(ret) > type_length ? (ret - type_length) : 0);
201 }
202
203 int TunDevice::read(u_int8_t* buf, u_int32_t len)
204 {
205   if(fd_ < 0)
206     return -1;
207   
208   if(with_pi_) {
209     struct iovec iov[2];
210     u_int32_t type;
211     
212     iov[0].iov_base = &type;
213     iov[0].iov_len = sizeof(type);
214     iov[1].iov_base = buf;
215     iov[1].iov_len = len;
216     return(fix_return(::readv(fd_, iov, 2), sizeof(type)));
217   }
218   else
219     return(::read(fd_, buf, len));
220 }
221
222 int TunDevice::write(u_int8_t* buf, u_int32_t len)
223 {
224   if(fd_ < 0)
225     return -1;
226   
227   if(!buf)
228     return 0;
229
230   if(with_pi_) {
231     struct iovec iov[2];
232     u_int32_t type;
233     struct ip *hdr = reinterpret_cast<struct ip*>(buf);
234     
235     type = 0;
236     if(hdr->ip_v == 4)
237       type = htonl(AF_INET);
238     else
239       type = htonl(AF_INET6);
240     
241     iov[0].iov_base = &type;
242     iov[0].iov_len = sizeof(type);
243     iov[1].iov_base = buf;
244     iov[1].iov_len = len;
245     return(fix_return(::writev(fd_, iov, 2), sizeof(type)));
246   }
247   else
248     return(::write(fd_, buf, len));
249 }
250
251 void TunDevice::do_ifconfig()
252 {
253   std::ostringstream command;
254   command << "/sbin/ifconfig " << actual_name_ << " " << conf_.addr_.toString()
255           << " netmask " << conf_.netmask_.toString() << " mtu " << conf_.mtu_;
256
257   if(conf_.type_ == TYPE_TUN)
258     command << " up";
259   else {
260 #if defined(__GNUC__) && defined(__OpenBSD__)
261     command << " link0";
262 #elif defined(__GNUC__) && defined(__FreeBSD__)
263     command << " up";
264 #elif defined(__GNUC__) && defined(__NetBSD__)
265     command << "";
266 #else
267  #error This Device works just for OpenBSD, FreeBSD or NetBSD
268 #endif
269   }
270
271   int result = system(command.str().c_str());
272   if(result == -1)
273     cLog.msg(Log::PRIO_ERROR) << "Execution of ifconfig failed" << AnytunErrno(errno);
274   else {
275     if(WIFEXITED(result))
276       cLog.msg(Log::PRIO_NOTICE) << "ifconfig returned " << WEXITSTATUS(result);  
277     else if(WIFSIGNALED(result))
278       cLog.msg(Log::PRIO_NOTICE) << "ifconfig terminated after signal " << WTERMSIG(result);
279     else
280       cLog.msg(Log::PRIO_ERROR) << "Execution of ifconfig: unkown error";
281   }
282
283 }