| 287 | } |
| 288 | |
| 289 | func NewDevice(tunDevice tun.Device, bind conn.Bind, logger *Logger) *Device { |
| 290 | device := new(Device) |
| 291 | device.state.state.Store(uint32(deviceStateDown)) |
| 292 | device.closed = make(chan struct{}) |
| 293 | device.Log = logger |
| 294 | device.net.bind = bind |
| 295 | device.tun.device = tunDevice |
| 296 | mtu, err := device.tun.device.MTU() |
| 297 | if err != nil { |
| 298 | device.Log.Errorf("Trouble determining MTU, assuming default: %v", err) |
| 299 | mtu = DefaultMTU |
| 300 | } |
| 301 | device.tun.mtu.Store(int32(mtu)) |
| 302 | device.peers.keyMap = make(map[NoisePublicKey]*Peer) |
| 303 | device.rate.limiter.Init() |
| 304 | device.indexTable.Init() |
| 305 | device.TCFilters = append(device.TCFilters, TCFDrop) |
| 306 | device.TCFilters = append(device.TCFilters, TCFBounce) |
| 307 | device.TCFilters = append(device.TCFilters, TCFAllowedip) |
| 308 | |
| 309 | device.PopulatePools() |
| 310 | |
| 311 | // create queues |
| 312 | |
| 313 | device.queue.handshake = newHandshakeQueue() |
| 314 | device.queue.encryption = newOutboundQueue() |
| 315 | device.queue.decryption = newInboundQueue() |
| 316 | |
| 317 | // start workers |
| 318 | |
| 319 | cpus := runtime.NumCPU() |
| 320 | device.state.stopping.Wait() |
| 321 | device.queue.encryption.wg.Add(cpus) // One for each RoutineHandshake |
| 322 | for i := 0; i < cpus; i++ { |
| 323 | go device.RoutineEncryption(i + 1) |
| 324 | go device.RoutineDecryption(i + 1) |
| 325 | go device.RoutineHandshake(i + 1) |
| 326 | } |
| 327 | |
| 328 | device.state.stopping.Add(1) // RoutineReadFromTUN |
| 329 | device.queue.encryption.wg.Add(1) // RoutineReadFromTUN |
| 330 | go device.RoutineReadFromTUN() |
| 331 | go device.RoutineTUNEventReader() |
| 332 | |
| 333 | return device |
| 334 | } |
| 335 | |
| 336 | // BatchSize returns the BatchSize for the device as a whole which is the max of |
| 337 | // the bind batch size and the tun batch size. The batch size reported by device |