github.com/ratrocket/u-root@v0.0.0-20180201221235-1cf9f48ee2cf/cmds/wifi/wifi.go (about)

     1  // Copyright 2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"io/ioutil"
    11  	"log"
    12  	"os"
    13  	"os/exec"
    14  )
    15  
    16  const (
    17  	cmd          = "wifi [options] essid [passphrase]"
    18  	nopassphrase = `network={
    19  	ssid="%s"
    20  	proto=RSN
    21  	key_mgmt=NONE
    22  }
    23  `
    24  	eap = `network={
    25  		ssid="%s"
    26  		key_mgmt=WPA-EAP
    27  		identity="%s"
    28  		password="%s"
    29  	}`
    30  )
    31  
    32  func init() {
    33  	defUsage := flag.Usage
    34  	flag.Usage = func() {
    35  		os.Args[0] = cmd
    36  		defUsage()
    37  	}
    38  }
    39  
    40  func main() {
    41  	var (
    42  		iface = flag.String("i", "wlan0", "interface to use")
    43  		essid string
    44  		conf  []byte
    45  	)
    46  
    47  	flag.Parse()
    48  	a := flag.Args()
    49  	essid = a[0]
    50  
    51  	switch {
    52  	case len(a) == 3:
    53  		conf = []byte(fmt.Sprintf(eap, essid, a[1], a[2]))
    54  	case len(a) == 2:
    55  		pass := a[1]
    56  		o, err := exec.Command("wpa_passphrase", essid, pass).CombinedOutput()
    57  		if err != nil {
    58  			log.Fatalf("%v %v: %v", essid, pass, err)
    59  		}
    60  		conf = o
    61  	case len(a) == 1:
    62  		conf = []byte(fmt.Sprintf(nopassphrase, essid))
    63  	default:
    64  		flag.Usage()
    65  		os.Exit(1)
    66  	}
    67  
    68  	if err := ioutil.WriteFile("/tmp/wifi.conf", conf, 0444); err != nil {
    69  		log.Fatalf("/tmp/wifi.conf: %v", err)
    70  	}
    71  
    72  	// There's no telling how long the supplicant will take, but on the other hand,
    73  	// it's been almost instantaneous. But, further, it needs to keep running.
    74  	go func() {
    75  		if o, err := exec.Command("wpa_supplicant", "-i"+*iface, "-c/tmp/wifi.conf").CombinedOutput(); err != nil {
    76  			log.Fatalf("wpa_supplicant: %v (%v)", o, err)
    77  		}
    78  	}()
    79  
    80  	cmd := exec.Command("dhclient", "-ipv4=true", "-ipv6=false", "-verbose", *iface)
    81  	cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
    82  	if err := cmd.Run(); err != nil {
    83  		log.Fatalf("%v: %v", cmd, err)
    84  	}
    85  
    86  }