示例#1
0
文件: http.go 项目: npe9/minimega
func httpTLSServer(p string) {
	log.Debugln("httpTLSServer")
	httpSetup()
	hitTLSChan = make(chan uint64, 1024)
	go hitTLSCounter()
	cert, key := generateCerts()

	//log.Fatalln(http.ListenAndServeTLS(":https", cert, key, nil))
	server := &http.Server{
		Addr:    ":https",
		Handler: nil,
	}
	config := &tls.Config{}
	if config.NextProtos == nil {
		config.NextProtos = []string{"http/1.1"}
	}

	var err error
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0], err = tls.LoadX509KeyPair(cert, key)
	if err != nil {
		log.Fatalln(err)
	}

	conn, err := net.Listen(p, ":https")
	if err != nil {
		log.Fatalln(err)
	}

	tlsListener := tls.NewListener(conn, config)
	log.Fatalln(server.Serve(tlsListener))
}
示例#2
0
文件: smtp.go 项目: cdshann/minimega
func smtpServer(p string) {
	log.Debugln("smtpServer")

	certfile, keyfile := generateCerts()
	cert, err := tls.LoadX509KeyPair(certfile, keyfile)
	if err != nil {
		log.Fatalln("couldn't get cert: ", err)
	}
	TLSconfig = &tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.VerifyClientCertIfGiven, ServerName: myFQDN}
	listener, err := net.Listen(p, "0.0.0.0"+smtpPort)
	if err != nil {
		log.Fatalln(err)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Debugln(err)
			continue
		}

		client := NewSMTPClientSession(conn)

		go client.Handler()

		smtpReportChan <- 1
	}
}
示例#3
0
文件: main.go 项目: cdshann/minimega
func main() {
	flag.Parse()

	logSetup()

	log.Debug("using minimega: %v", *f_minimega)

	// invoke minimega and get the doc json
	doc, err := exec.Command(*f_minimega, "-cli").Output()
	if err != nil {
		log.Fatalln(err)
	}
	log.Debug("got doc: %v", string(doc))

	// decode the JSON for our template
	if err := json.Unmarshal(doc, &handlers); err != nil {
		log.Fatalln(err)
	}

	exclude = strings.Split(*f_exclude, ",")
	values = strings.Split(*f_values, ",")

	for {
		if err := fuzz(); err != nil {
			log.Fatal("fuzz: %v", err)
		}
		if err := cleanup(); err != nil {
			log.Fatal("cleanup: %v", err)
		}
	}
}
示例#4
0
// client connection handler and transport. Messages on chan out are sent to
// the ron server. Incoming messages are put on the message queue to be routed
// by the mux. The entry to handler() also creates the tunnel transport.
func (c *Client) handler() {
	log.Debug("ron handler")

	enc := gob.NewEncoder(c.conn)
	dec := gob.NewDecoder(c.conn)

	tunnelQuit := make(chan bool)
	defer func() { tunnelQuit <- true }()

	// create a tunnel
	go c.handleTunnel(false, tunnelQuit)

	// handle client i/o
	go func() {
		for {
			m := <-c.out
			err := enc.Encode(m)
			if err != nil {
				log.Fatalln(err)
			}
		}
	}()

	for {
		var m Message
		err := dec.Decode(&m)
		if err != nil {
			log.Fatalln(err)
		}
		c.in <- &m
	}
}
示例#5
0
func main() {
	flag.Parse()

	logSetup()

	log.Debug("using minimega: %v", *f_minimega)
	log.Debug("using doc template: %v", *f_template)

	// invoke minimega and get the doc json
	doc, err := exec.Command(*f_minimega, "-cli").Output()
	if err != nil {
		log.Fatalln(err)
	}
	log.Debug("got doc: %v", string(doc))

	// decode the JSON for our template
	var handlers []*minicli.Handler
	err = json.Unmarshal(doc, &handlers)
	if err != nil {
		log.Fatalln(err)
	}

	// populate the apigen date for the template
	year, month, day := time.Now().Date()
	api := apigen{
		Date: fmt.Sprintf("%v %v %v", day, month, year),
	}

	// populate the major sections for the template
	for _, v := range handlers {
		var p string
		if strings.HasPrefix(v.SharedPrefix, "clear") {
			p = strings.TrimPrefix(v.SharedPrefix, "clear ")
		} else {
			p = v.SharedPrefix
		}
		if strings.HasPrefix(p, ".") {
			api.Builtins = append(api.Builtins, v)
		} else if strings.HasPrefix(p, "mesh") {
			api.Mesh = append(api.Mesh, v)
		} else if strings.HasPrefix(p, "vm") {
			api.VM = append(api.VM, v)
		} else {
			api.Host = append(api.Host, v)
		}
	}

	// run the template and print to stdout
	var out bytes.Buffer
	t, err := template.ParseFiles(*f_template)
	if err != nil {
		log.Fatalln(err)
	}
	err = t.Execute(&out, api)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(out.String())
}
示例#6
0
func main() {
	// flags
	flag.Parse()

	logSetup()

	if *f_u != "" {
		log.Debug("updating with file: %v", *f_u)

		err := update(filepath.Join(*f_path, "minirouter"), *f_u)
		if err != nil {
			log.Errorln(err)
		}

		return
	}

	// check for a running instance of minirouter
	_, err := os.Stat(filepath.Join(*f_path, "minirouter"))
	if err == nil {
		if !*f_force {
			log.Fatalln("minirouter appears to already be running, override with -force")
		}
		log.Warn("minirouter may already be running, proceed with caution")
		err = os.Remove(filepath.Join(*f_path, "minirouter"))
		if err != nil {
			log.Fatalln(err)
		}
	}

	log.Debug("using path: %v", *f_path)

	// attempt to set up the base path
	err = os.MkdirAll(*f_path, os.FileMode(0770))
	if err != nil {
		log.Fatal("mkdir base path: %v", err)
	}

	// start the domain socket service
	go commandSocketStart()

	// signal handling
	sig := make(chan os.Signal, 1024)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	<-sig

	// cleanup
	err = os.Remove(filepath.Join(*f_path, "minirouter"))
	if err != nil {
		log.Fatalln(err)
	}
}
示例#7
0
func cliVmConfigField(c *minicli.Command, field string) *minicli.Response {
	resp := &minicli.Response{Host: hostname}

	// If there are no args it means that we want to display the current value
	nArgs := len(c.StringArgs) + len(c.ListArgs) + len(c.BoolArgs)

	var ok bool
	var fns VMConfigFns
	var config interface{}

	// Find the right config functions, baseConfigFns has highest priority
	if fns, ok = baseConfigFns[field]; ok {
		config = &vmConfig.BaseConfig
	} else if fns, ok = kvmConfigFns[field]; ok {
		config = &vmConfig.KVMConfig
	} else {
		log.Fatalln("unknown config field: `%s`", field)
	}

	if nArgs == 0 {
		resp.Response = fns.Print(config)
	} else {
		if err := fns.Update(config, c); err != nil {
			resp.Error = err.Error()
		}
	}

	return resp
}
示例#8
0
func cliClearVmConfig(c *minicli.Command) *minicli.Response {
	resp := &minicli.Response{Host: hostname}

	var clearAll = len(c.BoolArgs) == 0
	var clearKVM = clearAll || (len(c.BoolArgs) == 1 && c.BoolArgs["kvm"])
	var cleared bool

	for k, fns := range baseConfigFns {
		if clearAll || c.BoolArgs[k] {
			fns.Clear(&vmConfig.BaseConfig)
			cleared = true
		}
	}
	for k, fns := range kvmConfigFns {
		if clearKVM || c.BoolArgs[k] {
			fns.Clear(&vmConfig.KVMConfig)
			cleared = true
		}
	}

	if !cleared {
		log.Fatalln("no callback defined for clear")
	}

	return resp
}
示例#9
0
文件: main.go 项目: cdshann/minimega
func teardown() {
	// Clear namespace so that we hit all the VMs
	SetNamespace("")

	vncClear()
	clearAllCaptures()
	vms.Kill(Wildcard)
	dnsmasqKillAll()
	ksmDisable()
	vms.Flush()
	vms.CleanDirs()
	containerTeardown()

	if err := bridgesDestroy(); err != nil {
		log.Errorln(err)
	}

	commandSocketRemove()
	goreadline.Rlcleanup()

	if err := os.Remove(filepath.Join(*f_base, "minimega.pid")); err != nil {
		log.Fatalln(err)
	}

	if cpuProfileOut != nil {
		pprof.StopCPUProfile()
		cpuProfileOut.Close()
	}

	os.Exit(0)
}
示例#10
0
// client heartbeat sent periodically be periodic(). heartbeat() sends the
// client info and any queued responses.
func (c *Client) heartbeat() {
	log.Debugln("heartbeat")

	hostname, err := os.Hostname()
	if err != nil {
		log.Fatalln(err)
	}

	cin := &Client{
		UUID:     c.UUID,
		Arch:     runtime.GOARCH,
		OS:       runtime.GOOS,
		Hostname: hostname,
	}

	macs, ips := getNetworkInfo()
	cin.MAC = macs
	cin.IP = ips

	c.responseLock.Lock()
	cin.Responses = c.Responses
	c.Responses = []*Response{}
	c.responseLock.Unlock()

	m := &Message{
		Type:   MESSAGE_CLIENT,
		UUID:   c.UUID,
		Client: cin,
	}

	log.Debug("heartbeat %v", cin)

	c.out <- m
	c.lastHeartbeat = time.Now()
}
示例#11
0
文件: http.go 项目: npe9/minimega
func httpServer(p string) {
	log.Debugln("httpServer")
	httpSetup()
	hitChan = make(chan uint64, 1024)
	go hitCounter()
	server := &http.Server{
		Addr:    ":http",
		Handler: nil,
	}

	conn, err := net.Listen(p, ":http")
	if err != nil {
		log.Fatalln(err)
	}

	log.Fatalln(server.Serve(conn))
}
示例#12
0
文件: external.go 项目: npe9/minimega
func process(p string) string {
	path, err := exec.LookPath(externalProcesses[p])
	if err != nil {
		log.Fatalln(err)
		return ""
	}
	return path
}
示例#13
0
文件: ssh.go 项目: cdshann/minimega
func sshServer(p string) {
	log.Debugln("sshServer")

	config := &ssh.ServerConfig{
		PasswordCallback: func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
			if conn.User() == "protonuke" && string(password) == "password" {
				return &ssh.Permissions{}, nil
			}

			return nil, errors.New("invalid user/password")
		},
	}

	private, err := ssh.ParsePrivateKey([]byte(id_rsa))
	if err != nil {
		log.Fatalln(err)
	}

	config.AddHostKey(private)

	// Once a ServerConfig has been configured, connections can be accepted.
	listener, err := net.Listen(p, PORT)
	if err != nil {
		log.Fatalln(err)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Errorln(err)
			continue
		}

		// Before use, a handshake must be performed on the incoming net.Conn.
		_, chans, reqs, err := ssh.NewServerConn(conn, config)
		if err != nil {
			log.Errorln(err)
			continue
		}

		// The incoming Request channel must be serviced.
		go ssh.DiscardRequests(reqs)

		go sshHandleChannels(conn, chans)
	}
}
示例#14
0
// register a transaction ID, adding a return channel to the mux
func (t *Tunnel) registerTID(TID int32) chan *tunnelMessage {
	if _, ok := t.tids[TID]; ok {
		log.Fatalln(fmt.Sprintf("tid %v already exists!", TID))
	}
	c := make(chan *tunnelMessage, 1024)
	t.tids[TID] = c
	return c
}
示例#15
0
文件: cc.go 项目: cdshann/minimega
func ccStart() {
	var err error
	ccNode, err = ron.NewServer(*f_ccPort, *f_iomBase)
	if err != nil {
		log.Fatalln(fmt.Errorf("creating cc node %v", err))
	}

	log.Debug("created ron node at %v %v", ccPort, *f_base)
}
示例#16
0
// called with bridgeLock set
func updateBridgeInfo() {
	log.Debugln("updateBridgeInfo")
	i := bridgeInfo()
	path := filepath.Join(*f_base, "bridges")
	err := ioutil.WriteFile(path, []byte(i), 0644)
	if err != nil {
		log.Fatalln(err)
	}
}
示例#17
0
文件: bird.go 项目: cdshann/minimega
func getRouterID() string {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	p := make([]byte, 4)
	_, err := r.Read(p)
	if err != nil {
		log.Fatalln(err)
	}
	ip := net.IPv4(p[0], p[1], p[2], p[3])
	return ip.String()
}
示例#18
0
// Transfer a single filepart to a temporary transfer directory.
func (iom *IOMeshage) Xfer(filename string, part int64, from string) error {
	TID := genTID()
	c := make(chan *IOMMessage)
	err := iom.registerTID(TID, c)
	defer iom.unregisterTID(TID)

	if err != nil {
		// a collision in int64, we should tell someone about this
		log.Fatalln(err)
	}

	m := &IOMMessage{
		From:     iom.node.Name(),
		Type:     TYPE_XFER,
		Filename: filename,
		TID:      TID,
		Part:     part,
	}
	_, err = iom.node.Set([]string{from}, m)
	if err != nil {
		return err
	}

	// wait for a response, or a timeout
	select {
	case resp := <-c:
		if log.WillLog(log.DEBUG) {
			log.Debugln("got part: ", resp.Part)
		}
		if resp.ACK {
			if log.WillLog(log.DEBUG) {
				log.Debugln("got part from: ", resp.From)
			}
			// write the part out to disk
			iom.transferLock.RLock()
			defer iom.transferLock.RUnlock()
			if t, ok := iom.transfers[filename]; ok {
				outfile := fmt.Sprintf("%v/%v.part_%v", t.Dir, filepath.Base(filename), part)
				err := ioutil.WriteFile(outfile, resp.Data, 0664)
				if err != nil {
					return err
				}
			} else {
				return fmt.Errorf("no transfer temporary directory to write to!")
			}
		} else {
			return fmt.Errorf("received NACK from xfer node")
		}
	case <-time.After(timeout):
		return fmt.Errorf("timeout")
	}
	return nil
}
示例#19
0
文件: pattern.go 项目: npe9/minimega
// enforceEOF makes sure that we are at the end of the line if the item we're
// building requires it.
func (l *patternLexer) enforceEOF() error {
	if l.newItem.Type == 0 {
		log.Fatalln("cannot enforce EOF when item type not specified")
	}

	if l.newItem.Type&requireEOLItems != 0 {
		if l.s.Scan() {
			return errors.New("trailing characters when EOF expected")
		}
	}

	return nil
}
示例#20
0
文件: ssh.go 项目: npe9/minimega
func sshServer(p string) {
	log.Debugln("sshServer")

	config := &ssh.ServerConfig{
		PasswordCallback: func(conn *ssh.ServerConn, user, pass string) bool {
			return user == "protonuke" && pass == "password"
		},
	}

	private, err := ssh.ParsePrivateKey([]byte(id_rsa))
	if err != nil {
		log.Fatalln(err)
	}

	config.AddHostKey(private)

	l, err := ssh.Listen(p, PORT, config)
	if err != nil {
		log.Fatalln(err)
	}

	for {
		conn, err := l.Accept()
		if err != nil {
			log.Errorln(err)
			continue
		}

		if err := conn.Handshake(); err != nil {
			if err != io.EOF {
				log.Errorln(err)
			}
			continue
		}

		go sshHandleConn(conn)
	}
}
示例#21
0
func vmConfigBool(fn func(interface{}) *bool, defaultVal bool) VMConfigFns {
	return VMConfigFns{
		Update: func(vm interface{}, c *minicli.Command) error {
			if c.BoolArgs["true"] || c.BoolArgs["false"] {
				*fn(vm) = c.BoolArgs["true"]
			} else {
				log.Fatalln("someone goofed on the patterns, bool args should be true/false")
			}
			return nil
		},
		Clear: func(vm interface{}) { *fn(vm) = defaultVal },
		Print: func(vm interface{}) string { return fmt.Sprintf("%v", *fn(vm)) },
	}
}
示例#22
0
文件: main.go 项目: cdshann/minimega
func main() {
	flag.Usage = usage
	flag.Parse()

	if *f_version {
		fmt.Println("miniccc", version.Revision, version.Date)
		fmt.Println(version.Copyright)
		os.Exit(0)
	}

	logSetup()

	if *f_tag {
		if runtime.GOOS == "windows" {
			log.Fatalln("tag updates are not available on windows miniccc clients")
		}

		if err := updateTag(); err != nil {
			log.Errorln(err)
		}
		return
	}

	// attempt to set up the base path
	if err := os.MkdirAll(*f_path, os.FileMode(0777)); err != nil {
		log.Fatal("mkdir base path: %v", err)
	}

	log.Debug("starting ron client with UUID: %v", Client.UUID)

	if err := dial(); err != nil {
		log.Fatal("unable to connect: %v", err)
	}

	go mux()
	go periodic()
	go commandHandler()
	heartbeat() // handshake is first heartbeat

	// create a listening domain socket for tag updates
	if runtime.GOOS != "windows" {
		go commandSocketStart()
	}

	// wait for SIGTERM
	sig := make(chan os.Signal, 1024)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
	<-sig
}
示例#23
0
文件: node.go 项目: summits/minimega
// connectionListener accepts connections on tcp/port for both solicited and unsolicited
// client connections.
func (n *Node) connectionListener() {
	log.Debugln("connectionListener")
	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", n.port))
	if err != nil {
		log.Fatalln(err)
	}
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Warnln(err)
			continue
		}
		n.newConnection(conn)
	}
}
示例#24
0
func ksmGetIntFromFile(filename string) int {
	buffer, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalln(err)
	}
	b := strings.TrimSpace(string(buffer))
	log.Info("read: %v", b)
	run, err := strconv.Atoi(b)
	if err != nil {
		log.Errorln(err)
		teardown()
	}
	log.Info("got %v from %v", int(run), filename)
	return int(run)
}
示例#25
0
文件: main.go 项目: cdshann/minimega
func commandSocketStart() {
	l, err := net.Listen("unix", filepath.Join(*f_path, "miniccc"))
	if err != nil {
		log.Fatalln(err)
	}

	for {
		conn, err := l.Accept()
		if err != nil {
			log.Error("command socket: %v", err)
		}
		log.Debugln("client connected")
		go commandSocketHandle(conn)
	}
}
示例#26
0
func cliVmConfigField(c *minicli.Command, field string) *minicli.Response {
	var err error
	resp := &minicli.Response{Host: hostname}

	fns := vmConfigFns[field]

	// If there are no args it means that we want to display the current value
	if len(c.StringArgs) == 0 && len(c.ListArgs) == 0 && len(c.BoolArgs) == 0 {
		resp.Response = fns.Print(info)
		return resp
	}

	// We expect exactly one key in either the String, List, or Bool Args for
	// most configs. For some, there is more complex processing and they need
	// the whole command.
	if fns.UpdateCommand != nil {
		err = fns.UpdateCommand(c)
	} else if len(c.StringArgs) == 1 && fns.Update != nil {
		for _, arg := range c.StringArgs {
			err = fns.Update(info, arg)
		}
	} else if len(c.ListArgs) == 1 && fns.Update != nil {
		// Lists need to be cleared first since they process each arg
		// individually to build state
		fns.Clear(info)

		for _, args := range c.ListArgs {
			for _, arg := range args {
				if err = fns.Update(info, arg); err != nil {
					break
				}
			}
		}
	} else if len(c.BoolArgs) == 1 && fns.UpdateBool != nil {
		// Special case, look for key "true" (there should only be two options,
		// "true" or "false" and, therefore, not "true" implies "false").
		err = fns.UpdateBool(info, c.BoolArgs["true"])
	} else {
		log.Fatalln("someone goofed on the patterns")
	}

	if err != nil {
		resp.Error = err.Error()
	}

	return resp
}
示例#27
0
文件: main.go 项目: ITLivLab/minimega
func teardown() {
	vncClear()
	clearAllCaptures()
	vms.kill(Wildcard)
	dnsmasqKillAll()
	err := bridgesDestroy()
	if err != nil {
		log.Errorln(err)
	}
	ksmDisable()
	vms.cleanDirs()
	commandSocketRemove()
	goreadline.Rlcleanup()
	err = os.Remove(*f_base + "minimega.pid")
	if err != nil {
		log.Fatalln(err)
	}
	os.Exit(0)
}
示例#28
0
func cliClearVmConfig(c *minicli.Command) *minicli.Response {
	resp := &minicli.Response{Host: hostname}

	var clearAll = len(c.BoolArgs) == 0
	var cleared bool

	for k, fns := range vmConfigFns {
		if clearAll || c.BoolArgs[k] {
			fns.Clear(info)
			cleared = true
		}
	}

	if !cleared {
		log.Fatalln("no callback defined for clear")
	}

	return resp
}
示例#29
0
文件: main.go 项目: cdshann/minimega
func main() {
	flag.Usage = usage
	flag.Parse()

	if flag.NArg() != 1 && flag.NArg() != 2 {
		usage()
		os.Exit(1)
	}

	logSetup()

	addr := ":" + strconv.Itoa(*f_port)
	log.Info("serving recordings from %s on %s", flag.Arg(0), addr)

	switch flag.NArg() {
	case 1: // just serve a directory and mjpeg streams
		// Ensure that the first arg is an existent directory
		if fi, err := os.Stat(flag.Arg(0)); err != nil || !fi.IsDir() {
			fmt.Print("Invalid argument: must be an existent directory\n\n")
			usage()
			os.Exit(1)
		}
		http.Handle("/", &playbackServer{http.Dir(flag.Arg(0))})
		http.ListenAndServe(addr, nil)
	case 2: // transcode with ffmpeg
		in := flag.Arg(0)
		out := flag.Arg(1)
		log.Debug("transcoding %v to %v", in, out)

		path := filepath.Dir(in)
		fname := filepath.Base(in)
		http.Handle("/", &playbackServer{http.Dir(path)})
		go http.ListenAndServe(addr, nil)

		err := transcode(fname, out)
		if err != nil {
			log.Fatalln(err)
		}
	default:
		usage()
		os.Exit(1)
	}
}
示例#30
0
func affinitySelectCPU(vm *KvmVM) string {
	// find a key with the fewest number of entries, add vm to it and
	// return the key
	var key string
	for k, v := range affinityCPUSets {
		if key == "" {
			key = k
			continue
		}
		if len(v) < len(affinityCPUSets[key]) {
			key = k
		}
	}
	if key == "" {
		log.Fatalln("could not find a valid CPU set!")
	}
	affinityCPUSets[key] = append(affinityCPUSets[key], vm)
	return key
}