cproxy.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2015 flannel authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package udp
  15. //#include "proxy.h"
  16. import "C"
  17. import (
  18. "net"
  19. "os"
  20. "reflect"
  21. "unsafe"
  22. log "github.com/golang/glog"
  23. "github.com/coreos/flannel/pkg/ip"
  24. )
  25. func runCProxy(tun *os.File, conn *net.UDPConn, ctl *os.File, tunIP ip.IP4, tunMTU int) {
  26. var log_errors int
  27. if log.V(1) {
  28. log_errors = 1
  29. }
  30. c, err := conn.File()
  31. if err != nil {
  32. log.Error("Converting UDPConn to File failed: ", err)
  33. return
  34. }
  35. defer c.Close()
  36. C.run_proxy(
  37. C.int(tun.Fd()),
  38. C.int(c.Fd()),
  39. C.int(ctl.Fd()),
  40. C.in_addr_t(tunIP.NetworkOrder()),
  41. C.size_t(tunMTU),
  42. C.int(log_errors),
  43. )
  44. }
  45. func writeCommand(f *os.File, cmd *C.command) {
  46. hdr := reflect.SliceHeader{
  47. Data: uintptr(unsafe.Pointer(cmd)),
  48. Len: int(unsafe.Sizeof(*cmd)),
  49. Cap: int(unsafe.Sizeof(*cmd)),
  50. }
  51. buf := *(*[]byte)(unsafe.Pointer(&hdr))
  52. f.Write(buf)
  53. }
  54. func setRoute(ctl *os.File, dst ip.IP4Net, nextHopIP ip.IP4, nextHopPort int) {
  55. cmd := C.command{
  56. cmd: C.CMD_SET_ROUTE,
  57. dest_net: C.in_addr_t(dst.IP.NetworkOrder()),
  58. dest_net_len: C.int(dst.PrefixLen),
  59. next_hop_ip: C.in_addr_t(nextHopIP.NetworkOrder()),
  60. next_hop_port: C.short(nextHopPort),
  61. }
  62. writeCommand(ctl, &cmd)
  63. }
  64. func removeRoute(ctl *os.File, dst ip.IP4Net) {
  65. cmd := C.command{
  66. cmd: C.CMD_DEL_ROUTE,
  67. dest_net: C.in_addr_t(dst.IP.NetworkOrder()),
  68. dest_net_len: C.int(dst.PrefixLen),
  69. }
  70. writeCommand(ctl, &cmd)
  71. }
  72. func stopProxy(ctl *os.File) {
  73. cmd := C.command{
  74. cmd: C.CMD_STOP,
  75. }
  76. writeCommand(ctl, &cmd)
  77. }