github.com/qinghon/debinterface@v0.0.6/interface.go (about) 1 package debinterface 2 3 import ( 4 "fmt" 5 "net" 6 "os" 7 "strings" 8 ) 9 10 type Interface map[string]interface{} 11 12 type FloatKey struct { 13 Option []string 14 Key string 15 } 16 17 // return only iface line Interface 18 func NewAdapter(name, AddrFam, AddrSource string) Interface { 19 var adapter = make(Interface) 20 adapter.SetName(name) 21 adapter.SetAddrFam(AddrFam) 22 adapter.SetAddrSource(AddrSource) 23 return adapter 24 } 25 26 func (adapter Interface) Set(key string, v interface{}) { 27 adapter[key] = v 28 } 29 30 // Set Selection for iface, like "auto", "iface", "allow-hotplug", "no-auto-down", 31 // "no-scripts" or custom ... 32 func (adapter Interface) SetSelection(sel string) { 33 if adapter["selection"] == nil { 34 adapter["selection"] = []string{} 35 } 36 adapter["selection"] = append(adapter["selection"].([]string), sel) 37 } 38 func (adapter Interface) SetAuto(f bool) { 39 adapter.SetSelection("auto") 40 } 41 func (adapter Interface) SetHotplug(f bool) { 42 adapter.SetSelection("allow-hotplug") 43 } 44 func (adapter Interface) SetName(name string) { 45 adapter.Set("name", name) 46 } 47 48 // Set iface address family 49 // The interface name is followed by the name of the address family that the interface uses. This 50 // will be "inet" for TCP/IP networking, but there is also some support for IPX networking ("ipx"), 51 // and IPv6 networking ("inet6"). Following that is the name of the method used to configure the interface. 52 func (adapter Interface) SetAddrFam(addrFam string) { 53 switch addrFam { 54 case "inet", "inet6", "ipx", "can": 55 adapter.Set("addrFam", addrFam) 56 } 57 } 58 59 // Set address method 60 // The method of the interface (e.g., static), or "none" (see below). 61 func (adapter Interface) SetAddrSource(methodName string) { 62 switch methodName { 63 case "dhcp", "static", "loopback", "manual", 64 "bootp", "ppp", "wvdial", "dynamic", 65 "ipv4ll", "v4tunnel", "auto", "6to4", "tunnel": 66 adapter.Set("method_name", methodName) 67 } 68 } 69 70 // The loopback method 71 func (adapter Interface) SetLookBack(turn bool) { 72 if turn { 73 adapter.Set("lookback", "on") 74 } else { 75 adapter.Set("lookback", "off") 76 } 77 } 78 79 // "static" Method 80 // Set static ip address 81 func (adapter Interface) SetAddress(address net.IP) { 82 adapter.Set("address", address) 83 } 84 85 // Set netmask 86 func (adapter Interface) SetNetmask(mask net.IPMask) { 87 adapter.Set("netmask", mask) 88 } 89 90 // Set Broadcast address (dotted quad, + or -). Default value: "+" 91 func (adapter Interface) SetBroadcast(broadcast net.IP) { 92 adapter.Set("broadcast", broadcast) 93 } 94 95 // Metric for added routes (dhclient) 96 func (adapter Interface) SetMetric(metric int) { 97 adapter.Set("metric", metric) 98 } 99 100 // Set Default gateway (dotted quad) 101 func (adapter Interface) SetGateWay(ip net.IP) { 102 adapter.Set("gateway", ip) 103 } 104 105 // Address of other end point (dotted quad). Note the spelling of "point-to". 106 func (adapter Interface) SetPoinToPoint(ip net.IP) error { 107 adapter.Set("pointopoint", ip) 108 return nil 109 } 110 111 // Hardware address. 112 // "manual" "static" "dhcp" Method 113 func (adapter Interface) SetHwAddress(hwaddress net.HardwareAddr) error { 114 adapter.Set("hwaddress", hwaddress) 115 return nil 116 } 117 118 // Set MTU size 119 // 120 // In "manual" "static" "dhcp" Method 121 func (adapter Interface) SetMtu(mtu int) { 122 adapter.Set("mtu", mtu) 123 } 124 125 // Set Scope: "global", "link", "host" 126 func (adapter Interface) SetScope(scope string) error { 127 switch scope { 128 case "global", "link", "host": 129 adapter["scope"] = scope 130 default: 131 return os.ErrInvalid 132 } 133 return nil 134 } 135 136 // Set Use the IP address address to communicate with the server. 137 // In "bootp" Method 138 func (adapter Interface) SetServer(server net.IP) { 139 adapter.Set("server", server) 140 } 141 func (adapter Interface) SetDstAddr(dstaddr net.IP) { 142 adapter.Set("dstaddr", dstaddr) 143 } 144 func (adapter Interface) SetLocal(local net.IP) { 145 adapter.Set("local", local) 146 } 147 148 // Set "dns-nameserver" 149 func (adapter Interface) SetDnsNameServer(ipList []net.IP) { 150 adapter.Set("dns-nameserver", ipList) 151 } 152 153 // Set "dns-search" ,like "local", "lan" 154 func (adapter Interface) SetDnsSearch(ipList []string) { 155 adapter.Set("dns-search", ipList) 156 } 157 158 // Set "dns-domain" ,like "example.com" 159 func (adapter Interface) SetDnsDomain(domainList []string) { 160 adapter.Set("dns-domain", domainList) 161 } 162 163 // IFACE OPTIONS 164 // The following "command" options are available for every family and method. Each of these options can be given multiple times in a single stanza, 165 // in which case the commands are executed in the order in which they appear in the stanza. (You can ensure a command never fails by suffixing them 166 // with "|| true".) 167 func (adapter Interface) SetScript(action string, script string) { 168 switch action { 169 case "up": 170 adapter.SetUpScript(script) 171 case "down": 172 adapter.SetDownScript(script) 173 case "pre-up": 174 adapter.SetPreUpScript(script) 175 case "pre-down": 176 adapter.SetPreDownScript(script) 177 case "post-up": 178 adapter.SetPostUpScript(script) 179 case "post-down": 180 adapter.SetPostDownScript(script) 181 } 182 } 183 184 // Run command before bringing the interface up. If this command fails then ifup aborts, 185 // refraining from marking the interface as configured, 186 // prints an error message, and exits with status 0. This behavior may change in the future. 187 func (adapter Interface) SetPreUpScript(command string) { 188 if adapter["pre-up"] == nil { 189 adapter["pre-up"] = []string{} 190 } 191 adapter["pre-up"] = append(adapter["pre-up"].([]string), command) 192 } 193 194 // up command 195 func (adapter Interface) SetUpScript(command string) { 196 if adapter["up"] == nil { 197 adapter["up"] = []string{} 198 } 199 adapter["up"] = append(adapter["up"].([]string), command) 200 } 201 202 // Run command after bringing the interface up. If this command fails then ifup aborts, refraining from 203 // marking the interface as configured (even though it has really been configured), prints an error 204 // message, and exits with status 0. This behavior may change in the future. 205 func (adapter Interface) SetPostUpScript(command string) { 206 if adapter["post-up"] == nil { 207 adapter["post-up"] = []string{} 208 } 209 adapter["post-up"] = append(adapter["post-up"].([]string), command) 210 } 211 func (adapter Interface) SetDownScript(command string) { 212 if adapter["down"] == nil { 213 adapter["down"] = []string{} 214 } 215 adapter["down"] = append(adapter["down"].([]string), command) 216 } 217 218 // Run command before taking the interface down. If this command fails then ifdown 219 // aborts, marks the interface as deconfigured (even though it has not really been 220 // deconfigured), and exits with status 0. This behavior may change in the future. 221 func (adapter Interface) SetPreDownScript(command string) { 222 if adapter["pre-down"] == nil { 223 adapter["pre-down"] = []string{} 224 } 225 adapter["pre-down"] = append(adapter["pre-down"].([]string), command) 226 } 227 228 // Run command after taking the interface down. If this command fails then ifdown 229 // aborts, marks the interface as deconfigured, and exits with status 0. 230 // This behavior may change in the future. 231 func (adapter Interface) SetPostDownScript(command string) { 232 if adapter["post-down"] == nil { 233 adapter["post-down"] = []string{} 234 } 235 adapter["post-down"] = append(adapter["post-down"].([]string), command) 236 } 237 238 // "dhcp" Method (pump, dhcpcd, udhcpc) 239 // Hostname to be requested (pump, dhcpcd, udhcpc) 240 func (adapter Interface) SetHostName(hostname string) { 241 adapter.Set("hostname", hostname) 242 } 243 244 // Preferred lease time in hours (pump) 245 func (adapter Interface) SetLeaseHours(leasehours string) { 246 adapter.Set("leasehours", leasehours) 247 } 248 249 // Preferred lease time in seconds (dhcpcd) 250 func (adapter Interface) SetLeaseTime(leasetime string) { 251 adapter.Set("leasetime", leasetime) 252 } 253 254 // Vendor class identifier (dhcpcd) 255 func (adapter Interface) SetVendor(vendor string) { 256 adapter.Set("vendor", vendor) 257 } 258 259 // Client identifier (dhcpcd) 260 func (adapter Interface) SetClient(client string) { 261 adapter.Set("client", client) 262 } 263 264 // The bootp Method. 265 func (adapter Interface) SetBootFile(bootfile string) { 266 adapter.Set("bootfile", bootfile) 267 } 268 269 // The ppp Method. 270 // Use name as the provider (from /etc/ppp/peers). 271 func (adapter Interface) SetProvider(provider string) { 272 adapter.Set("provider", provider) 273 } 274 275 // Set bridge Spanning Tree Protocol 276 func (adapter Interface) SetBridgeStp(off bool) { 277 adapter.Set("bridge_stp", off) 278 } 279 280 // Set delay before a port becomes available 281 func (adapter Interface) SetBridgeWaitPort(delay int) { 282 adapter.Set("bridge_waitport", delay) 283 } 284 285 // Forwarding delay 286 func (adapter Interface) SetBridgeFd(delay int) { 287 adapter.Set("bridge_fd", delay) 288 } 289 290 // Set bridge adapter bridge to define ports. 291 // The option: 292 // "none": not bind to any ports. 293 // "regex": use a regular expression to define ports 294 // Default option is "" 295 func (adapter Interface) SetBridgePorts(option, eth string) { 296 if option == "" && eth == "" { 297 return 298 } 299 adapter.Set("bridge_ports", FloatKey{Option: []string{option}, Key: eth}) 300 } 301 302 // Use number as the ppp unit number. 303 func (adapter Interface) SetUnit(unit string) { 304 adapter.Set("unit", unit) 305 } 306 307 // Pass string as additional options to pon. 308 func (adapter Interface) SetOptions(options string) { 309 adapter.Set("options", options) 310 } 311 312 // parsed from file ,only this package 313 func (adapter Interface) SetFromFile(_filepath string) { 314 adapter["fromfile"] = _filepath 315 } 316 317 // Set unknow key, "Export()" together 318 func (adapter Interface) SetUnknown(unknown string) { 319 if adapter["unknown"] == nil { 320 adapter["unknown"] = []string{} 321 } 322 adapter["unknown"] = append(adapter["unknown"].([]string), unknown) 323 } 324 325 // Get adapter name ,like "eth0", "br0" 326 func (adapter Interface) GetName() string { 327 if adapter["name"] == nil { 328 return "<nil>" 329 } 330 return adapter["name"].(string) 331 } 332 333 // convert Interface to debian network file format 334 func (adapter Interface) Export() string { 335 var output string 336 337 output += fmt.Sprintf("iface %s %s %s\n", adapter["name"], adapter["addrFam"], adapter["method_name"]) 338 for k, v := range adapter { 339 if k == "method_name" || k == "addrFam" || k == "name" || k == "fromfile" { 340 continue 341 } 342 switch v.(type) { 343 case string: 344 output += fmt.Sprintf("\t%s %s\n", k, v) 345 case net.IP: 346 output += fmt.Sprintf("\t%s %s\n", k, v.(net.IP).String()) 347 case net.IPMask: 348 output += fmt.Sprintf("\t%s %s\n", k, ToIPv4(v.(net.IPMask))) 349 case []string: 350 switch k { 351 case "pre-up", "up", "post-up", "down", "pre-down", "post-down": 352 for _, str := range v.([]string) { 353 output += fmt.Sprintf("\t%s %s\n", k, str) 354 } 355 case "unknown": 356 for _, str := range v.([]string) { 357 output += fmt.Sprintf("\t%s\n", str) 358 } 359 case "selection": 360 for _, str := range v.([]string) { 361 output = fmt.Sprintf("%s %s\n", str, adapter["name"]) + output 362 } 363 default: 364 output += fmt.Sprintf("\t%s %s\n", k, strings.Join(v.([]string), "")) 365 } 366 case []net.IP: 367 ipList := []string{} 368 for _, ip := range v.([]net.IP) { 369 ipList = append(ipList, ip.String()) 370 } 371 output += fmt.Sprintf("\t%s %s\n", k, strings.Join(ipList, " ")) 372 case int: 373 output += fmt.Sprintf("\t%s %d\n", k, v) 374 case FloatKey: 375 output += fmt.Sprintf("\t%s %s\n", k, v.(FloatKey).String()) 376 case bool: 377 if v.(bool) { 378 output += fmt.Sprintf("\t%s on\n", k) 379 } else { 380 output += fmt.Sprintf("\t%s off\n", k) 381 } 382 } 383 } 384 return output 385 } 386 387 // Convert ipv4 mask to ip format, skip ipv6 convert 388 func ToIPv4(m net.IPMask) string { 389 p := m[len(m)-4:] 390 391 if len(m) == 0 { 392 return "<nil>" 393 } 394 // If IPv4, use dotted notation. 395 if len(p) == net.IPv4len { 396 const maxIPv4StringLen = len("255.255.255.255") 397 b := make([]byte, maxIPv4StringLen) 398 399 n := ubtoa(b, 0, p[0]) 400 b[n] = '.' 401 n++ 402 403 n += ubtoa(b, n, p[1]) 404 b[n] = '.' 405 n++ 406 407 n += ubtoa(b, n, p[2]) 408 b[n] = '.' 409 n++ 410 411 n += ubtoa(b, n, p[3]) 412 return string(b[:n]) 413 } 414 return m.String() 415 } 416 417 // ubtoa encodes the string form of the integer v to dst[start:] and 418 // returns the number of bytes written to dst. The caller must ensure 419 // that dst has sufficient length. 420 func ubtoa(dst []byte, start int, v byte) int { 421 if v < 10 { 422 dst[start] = v + '0' 423 return 1 424 } else if v < 100 { 425 dst[start+1] = v%10 + '0' 426 dst[start] = v/10 + '0' 427 return 2 428 } 429 430 dst[start+2] = v%10 + '0' 431 dst[start+1] = (v/10)%10 + '0' 432 dst[start] = v/100 + '0' 433 return 3 434 } 435 436 func (fk FloatKey) String() string { 437 return strings.Join(fk.Option, " ") + " " + fk.Key 438 }