<commit_before>package main

import (
	"encoding/binary"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"path/filepath"
	"regexp"
	"syscall"
)

func handleConn(conn net.Conn) {
	var err error
	buf := make([]byte, 4096*1024) // 4MB
	openedFile := map[uintptr]*os.File{}
	reGetattr := regexp.MustCompile("^getattr(.*)")
	reReaddir := regexp.MustCompile("^readdir(.*)")
	reOpen := regexp.MustCompile("^open(.*)")
	reRead := regexp.MustCompile("^read(.*)")
	reWrite := regexp.MustCompile("^write(.*)")
	reTruncate := regexp.MustCompile("^truncate(.*)")
	reRelease := regexp.MustCompile("^release(.*)")
	reMkdir := regexp.MustCompile("^mkdir(.*)")
	reRmdir := regexp.MustCompile("^rmdir(.*)")
	reUnlink := regexp.MustCompile("^unlink(.*)")
	reCreate := regexp.MustCompile("^create(.*)")
	reUtime := regexp.MustCompile("^utime(.*)")
	reChmod := regexp.MustCompile("^chmod(.*)")
	rootdir := "/home/gle/code_repo/cloud_lib/tcfs-go/rootdir"
	for {
		_, err = io.ReadFull(conn, buf[:4])
		if err != nil {
			break
		}
		msglen := binary.BigEndian.Uint32(buf[:4])
		_, err = io.ReadFull(conn, buf[:msglen])
		// println(string(buf))
		if matched := reGetattr.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			fixpath := rootdir + matched[1]
			var stat syscall.Stat_t
			err = syscall.Lstat(fixpath, &stat)
			if err != nil {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				var ret int32 = -2
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 11*4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			binary.BigEndian.PutUint32(buf[8:12], uint32(stat.Dev))
			binary.BigEndian.PutUint32(buf[12:16], uint32(stat.Ino))
			binary.BigEndian.PutUint32(buf[16:20], stat.Mode)
			binary.BigEndian.PutUint32(buf[20:24], uint32(stat.Nlink))
			binary.BigEndian.PutUint32(buf[24:28], stat.Uid)
			binary.BigEndian.PutUint32(buf[28:32], stat.Gid)
			binary.BigEndian.PutUint32(buf[32:36], uint32(stat.Size))
			binary.BigEndian.PutUint32(buf[36:40], uint32(stat.Atim.Sec))
			binary.BigEndian.PutUint32(buf[40:44], uint32(stat.Mtim.Sec))
			binary.BigEndian.PutUint32(buf[44:48], uint32(stat.Ctim.Sec))
			conn.Write(buf[:48])

		} else if matched := reReaddir.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			fixpath := rootdir + matched[1]
			fileList := []byte{}
			err = filepath.Walk(fixpath, func(path string, f os.FileInfo, err error) error {
				rp, _ := filepath.Rel(rootdir, path)
				fileList = append(fileList, rp...)
				fileList = append(fileList, 0)
				return nil
			})
			binary.BigEndian.PutUint32(buf[:4], uint32(len(fileList))+4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			copy(buf[8:], fileList)
			conn.Write(buf[:len(fileList)+8])
		} else if matched := reOpen.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			flag := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			f, err := os.OpenFile(fixpath, int(flag), os.ModePerm)
			if err != nil {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				var ret int32 = -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			fd := f.Fd()
			openedFile[fd] = f
			binary.BigEndian.PutUint32(buf[0:4], 8)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			binary.BigEndian.PutUint32(buf[8:12], uint32(fd))
			conn.Write(buf[:12])
		} else if matched := reRead.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			findex := binary.BigEndian.Uint32([]byte(matched[1])[:4])
			offset := binary.BigEndian.Uint32([]byte(matched[1])[4:8])
			size := binary.BigEndian.Uint32([]byte(matched[1])[8:12])
			// fixpath := rootdir + matched[1][12:]
			f := openedFile[uintptr(findex)]
			readbuf := make([]byte, size)
			readed, err := f.ReadAt(readbuf, int64(offset))
			if err != nil && err != io.EOF {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				var ret int32 = -9
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			if readed == 0 {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				binary.BigEndian.PutUint32(buf[4:8], 0)
				conn.Write(buf[:8])
			} else if readed > 0 {
				binary.BigEndian.PutUint32(buf[0:4], 4+uint32(readed))
				binary.BigEndian.PutUint32(buf[4:8], uint32(readed))
				copy(buf[8:], readbuf)
				conn.Write(buf[:8+readed])
			}
		} else if matched := reWrite.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			findex := binary.BigEndian.Uint32([]byte(matched[1])[:4])
			offset := binary.BigEndian.Uint32([]byte(matched[1])[4:8])
			size := binary.BigEndian.Uint32([]byte(matched[1])[8:12])
			fmt.Println(size)
			wbuf := []byte(matched[1])[12 : 12+size]
			f := openedFile[uintptr(findex)]
			writed, _ := f.WriteAt(wbuf, int64(offset))
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], uint32(writed))
			conn.Write(buf[:8])
		} else if matched := reTruncate.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			newSize := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			err := os.Truncate(fixpath, int64(newSize))
			if err != nil {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13 // EACCES
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reRelease.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			findex := binary.BigEndian.Uint32([]byte(matched[1])[:4])
			f := openedFile[uintptr(findex)]
			err := f.Close()
			if err != nil {
				fmt.Println(err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -9
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reMkdir.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			mode := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			if err := os.MkdirAll(fixpath, os.FileMode(mode)); err != nil {
				log.Fatal("Can't create dir", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reRmdir.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			fixpath := rootdir + matched[1]
			if err := os.Remove(fixpath); err != nil {
				log.Fatal("Can't rmdir", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reUnlink.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			// FIXME
			fixpath := rootdir + matched[1]
			if err := os.Remove(fixpath); err != nil {
				log.Fatal("Can't rmdir", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reCreate.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			// mode := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			f, err := os.Create(fixpath)
			if err != nil {
				log.Fatal("Can't create", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			fd := f.Fd()
			openedFile[fd] = f
			binary.BigEndian.PutUint32(buf[0:4], 8)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			binary.BigEndian.PutUint32(buf[8:12], uint32(fd))
			conn.Write(buf[:12])
		} else if matched := reUtime.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			// TODO
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reChmod.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			mode := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			err := os.Chmod(fixpath, os.FileMode(mode))
			if err != nil {
				log.Fatal("Can't chmod", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else {
			fmt.Println("error, badmsg")
		}
	}
	fmt.Println("xxxxxxxxxxx, close")
}

var (
	port = flag.String("port", ":9876", "port to listen to")
)

func main() {
	flag.Parse()
	l, e := net.Listen("tcp", *port)
	if e != nil {
		log.Fatal(e)
		return
	}
	for {
		conn, e := l.Accept()
		if e != nil {
			log.Fatal(e)
			continue
		}
		go handleConn(conn)
	}
}
<commit_msg>utime<commit_after>package main

import (
	"encoding/binary"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"path/filepath"
	"regexp"
	"syscall"
)

func handleConn(conn net.Conn) {
	var err error
	buf := make([]byte, 4096*1024) // 4MB
	openedFile := map[uintptr]*os.File{}
	reGetattr := regexp.MustCompile("^getattr(.*)")
	reReaddir := regexp.MustCompile("^readdir(.*)")
	reOpen := regexp.MustCompile("^open(.*)")
	reRead := regexp.MustCompile("^read(.*)")
	reWrite := regexp.MustCompile("^write(.*)")
	reTruncate := regexp.MustCompile("^truncate(.*)")
	reRelease := regexp.MustCompile("^release(.*)")
	reMkdir := regexp.MustCompile("^mkdir(.*)")
	reRmdir := regexp.MustCompile("^rmdir(.*)")
	reUnlink := regexp.MustCompile("^unlink(.*)")
	reCreate := regexp.MustCompile("^create(.*)")
	reUtime := regexp.MustCompile("^utime(.*)")
	reChmod := regexp.MustCompile("^chmod(.*)")
	rootdir := "/home/gle/code_repo/cloud_lib/tcfs-go/rootdir"
	for {
		_, err = io.ReadFull(conn, buf[:4])
		if err != nil {
			break
		}
		msglen := binary.BigEndian.Uint32(buf[:4])
		_, err = io.ReadFull(conn, buf[:msglen])
		// println(string(buf))
		if matched := reGetattr.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			fixpath := rootdir + matched[1]
			var stat syscall.Stat_t
			err = syscall.Lstat(fixpath, &stat)
			if err != nil {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				var ret int32 = -2
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 11*4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			binary.BigEndian.PutUint32(buf[8:12], uint32(stat.Dev))
			binary.BigEndian.PutUint32(buf[12:16], uint32(stat.Ino))
			binary.BigEndian.PutUint32(buf[16:20], stat.Mode)
			binary.BigEndian.PutUint32(buf[20:24], uint32(stat.Nlink))
			binary.BigEndian.PutUint32(buf[24:28], stat.Uid)
			binary.BigEndian.PutUint32(buf[28:32], stat.Gid)
			binary.BigEndian.PutUint32(buf[32:36], uint32(stat.Size))
			binary.BigEndian.PutUint32(buf[36:40], uint32(stat.Atim.Sec))
			binary.BigEndian.PutUint32(buf[40:44], uint32(stat.Mtim.Sec))
			binary.BigEndian.PutUint32(buf[44:48], uint32(stat.Ctim.Sec))
			conn.Write(buf[:48])

		} else if matched := reReaddir.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			fixpath := rootdir + matched[1]
			fileList := []byte{}
			err = filepath.Walk(fixpath, func(path string, f os.FileInfo, err error) error {
				rp, _ := filepath.Rel(rootdir, path)
				fileList = append(fileList, rp...)
				fileList = append(fileList, 0)
				return nil
			})
			binary.BigEndian.PutUint32(buf[:4], uint32(len(fileList))+4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			copy(buf[8:], fileList)
			conn.Write(buf[:len(fileList)+8])
		} else if matched := reOpen.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			flag := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			f, err := os.OpenFile(fixpath, int(flag), os.ModePerm)
			if err != nil {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				var ret int32 = -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			fd := f.Fd()
			openedFile[fd] = f
			binary.BigEndian.PutUint32(buf[0:4], 8)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			binary.BigEndian.PutUint32(buf[8:12], uint32(fd))
			conn.Write(buf[:12])
		} else if matched := reRead.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			findex := binary.BigEndian.Uint32([]byte(matched[1])[:4])
			offset := binary.BigEndian.Uint32([]byte(matched[1])[4:8])
			size := binary.BigEndian.Uint32([]byte(matched[1])[8:12])
			// fixpath := rootdir + matched[1][12:]
			f := openedFile[uintptr(findex)]
			readbuf := make([]byte, size)
			readed, err := f.ReadAt(readbuf, int64(offset))
			if err != nil && err != io.EOF {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				var ret int32 = -9
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			if readed == 0 {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				binary.BigEndian.PutUint32(buf[4:8], 0)
				conn.Write(buf[:8])
			} else if readed > 0 {
				binary.BigEndian.PutUint32(buf[0:4], 4+uint32(readed))
				binary.BigEndian.PutUint32(buf[4:8], uint32(readed))
				copy(buf[8:], readbuf)
				conn.Write(buf[:8+readed])
			}
		} else if matched := reWrite.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			findex := binary.BigEndian.Uint32([]byte(matched[1])[:4])
			offset := binary.BigEndian.Uint32([]byte(matched[1])[4:8])
			size := binary.BigEndian.Uint32([]byte(matched[1])[8:12])
			fmt.Println(size)
			fmt.Println(len(matched[1]))
			wbuf := []byte(matched[1])[12 : 12+size]
			f := openedFile[uintptr(findex)]
			writed, _ := f.WriteAt(wbuf, int64(offset))
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], uint32(writed))
			conn.Write(buf[:8])
		} else if matched := reTruncate.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			newSize := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			err := os.Truncate(fixpath, int64(newSize))
			if err != nil {
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13 // EACCES
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reRelease.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			findex := binary.BigEndian.Uint32([]byte(matched[1])[:4])
			f := openedFile[uintptr(findex)]
			err := f.Close()
			if err != nil {
				fmt.Println(err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -9
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reMkdir.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			mode := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			if err := os.MkdirAll(fixpath, os.FileMode(mode)); err != nil {
				log.Fatal("Can't create dir", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reRmdir.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			fixpath := rootdir + matched[1]
			if err := os.Remove(fixpath); err != nil {
				log.Fatal("Can't rmdir", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reUnlink.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			// FIXME
			fixpath := rootdir + matched[1]
			if err := os.Remove(fixpath); err != nil {
				log.Fatal("Can't rmdir", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reCreate.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			// mode := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			f, err := os.Create(fixpath)
			if err != nil {
				log.Fatal("Can't create", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			fd := f.Fd()
			openedFile[fd] = f
			binary.BigEndian.PutUint32(buf[0:4], 8)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			binary.BigEndian.PutUint32(buf[8:12], uint32(fd))
			conn.Write(buf[:12])
		} else if matched := reUtime.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			atime := binary.BigEndian.Uint64([]byte(matched[1])[0:8])
			mtime := binary.BigEndian.Uint64([]byte(matched[1])[8:16])
			fixpath := rootdir + matched[1][16:]
			err := syscall.Utime(fixpath, &syscall.Utimbuf{int64(atime), int64(mtime)})
			if err != nil {
				log.Fatal("Can't create", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else if matched := reChmod.FindStringSubmatch(string(buf[:msglen])); len(matched) > 1 {
			mode := binary.BigEndian.Uint32([]byte(matched[1])[0:4])
			fixpath := rootdir + matched[1][4:]
			err := os.Chmod(fixpath, os.FileMode(mode))
			if err != nil {
				log.Fatal("Can't chmod", err)
				binary.BigEndian.PutUint32(buf[0:4], 4)
				ret := -13
				binary.BigEndian.PutUint32(buf[4:8], uint32(ret))
				conn.Write(buf[:8])
				continue
			}
			binary.BigEndian.PutUint32(buf[0:4], 4)
			binary.BigEndian.PutUint32(buf[4:8], 0)
			conn.Write(buf[:8])
		} else {
			fmt.Println("error, badmsg")
		}
	}
	fmt.Println("xxxxxxxxxxx, close")
}

var (
	port = flag.String("port", ":9876", "port to listen to")
)

func main() {
	flag.Parse()
	l, e := net.Listen("tcp", *port)
	if e != nil {
		log.Fatal(e)
		return
	}
	for {
		conn, e := l.Accept()
		if e != nil {
			log.Fatal(e)
			continue
		}
		go handleConn(conn)
	}
}
<|endoftext|>


<commit_before>package model

import (
	"fmt"
	"log"
	"net/url"
	"strconv"
	"strings"

	"github.com/taskcluster/jsonschema2go"
	"github.com/taskcluster/taskcluster-client-java/codegenerator/utils"
)

type JsonSubSchema jsonschema2go.JsonSubSchema

func (jsonSubSchema *JsonSubSchema) TypeDefinition(level int, extraPackages map[string]bool) (classDefinition, comment, typ string) {
	if d := jsonSubSchema.Description; d != nil {
		if desc := *d; desc != "" {
			comment += desc
		}
	}
	if comment != "" && comment[len(comment)-1:] != "\n" {
		comment += "\n"
	}

	// Create comments for metadata in a single paragraph. Only start new
	// paragraph if we discover after inspecting all possible metadata, that
	// something has been specified. If there is no metadata, no need to create
	// a new paragraph.
	var metadata string
	if enum := jsonSubSchema.Enum; enum != nil {
		metadata += "Possible values:\n"
		for _, i := range enum {
			switch i.(type) {
			case float64:
				metadata += fmt.Sprintf("    * %v\n", i)
			default:
				metadata += fmt.Sprintf("    * %q\n", i)
			}
		}
	}
	if def := jsonSubSchema.Default; def != nil {
		var value string
		switch (*def).(type) {
		case bool:
			value = strconv.FormatBool((*def).(bool))
		case float64:
			value = strconv.FormatFloat((*def).(float64), 'g', -1, 64)
		default:
			value = fmt.Sprintf("%q", *def)
		}
		metadata += "Default:    " + value + "\n"
	}
	if regex := jsonSubSchema.Pattern; regex != nil {
		metadata += "Syntax:     " + *regex + "\n"
	}
	if minItems := jsonSubSchema.MinLength; minItems != nil {
		metadata += "Min length: " + strconv.Itoa(*minItems) + "\n"
	}
	if maxItems := jsonSubSchema.MaxLength; maxItems != nil {
		metadata += "Max length: " + strconv.Itoa(*maxItems) + "\n"
	}
	if minimum := jsonSubSchema.Minimum; minimum != nil {
		metadata += "Mininum:    " + strconv.Itoa(*minimum) + "\n"
	}
	if maximum := jsonSubSchema.Maximum; maximum != nil {
		metadata += "Maximum:    " + strconv.Itoa(*maximum) + "\n"
	}
	// Here we check if metadata was specified, and only create new
	// paragraph (`*\n`) if something was.
	if len(metadata) > 0 {
		comment += "\n" + metadata
	}

	if URL := jsonSubSchema.SourceURL; URL != "" {
		u, err := url.Parse(URL)
		if err == nil && u.Scheme != "file" {
			if len(comment) > 1 {
				comment += "\n"
			}
			comment += "See " + URL + "\n"
		}
	}
	comment = utils.Comment(comment, "")

	typ = "Object"
	if p := jsonSubSchema.Type; p != nil {
		typ = *p
	}
	if p := jsonSubSchema.RefSubSchema; p != nil {
		j := JsonSubSchema(*jsonSubSchema.RefSubSchema)
		_, _, possSimpleType := (&j).TypeDefinition(0, make(map[string]bool))
		switch possSimpleType {
		case "":
			typ = p.TypeName
		default:
			typ = possSimpleType
		}
	}
	switch typ {
	case "array":
		if jsonSubSchema.Items != nil {
			if jsonSubSchema.Items.Type != nil {
				j := JsonSubSchema(*jsonSubSchema.Items)
				subClassDefinition, _, subType := (&j).TypeDefinition(level, extraPackages)
				if subType == "" {
					log.Fatalf("%v returns an empty Type", jsonSubSchema.Items.SourceURL)
				}
				typ = subType + "[]"
				classDefinition = subClassDefinition

			} else {
				if refSubSchema := jsonSubSchema.Items.RefSubSchema; refSubSchema != nil {
					if refSubSchema.TypeName == "" {
						log.Fatalf("%v has not set TypeName", refSubSchema.SourceURL)
					}
					typ = refSubSchema.TypeName + "[]"
				}
			}
		} else {
			typ = "Object[]"
		}

	case "object":
		if s := jsonSubSchema.Properties; s != nil {
			typ = jsonSubSchema.TypeName
			classDefinition = "\n" + strings.Repeat("    ", level) + "public class " + typ + " {"
			for _, j := range s.SortedPropertyNames {
				// recursive call to build go types inside structs
				var subType string
				c := JsonSubSchema(*s.Properties[j])
				subMember := s.MemberNames[j]
				subClassDefinition, subComment, subType := (&c).TypeDefinition(level+1, extraPackages)
				classDefinition += "\n"
				classDefinition += subClassDefinition
				classDefinition += "\n"
				classDefinition += utils.Indent(subComment, strings.Repeat("    ", level+1), false)
				classDefinition += strings.Repeat("    ", level+1) + "public " + subType + " " + subMember + ";"
			}
			classDefinition += "\n"
			classDefinition += strings.Repeat("    ", level) + "}"
			classDefinition += "\n"
		} else {
			typ = "Object"
		}
	case "number":
		typ = "int"
	case "integer":
		typ = "int"
	case "boolean":
		typ = "boolean"
	// json type string maps to go type string, so only need to test case of when
	// string is a json date-time, so we can convert to go type time.Time...
	case "string":
		if f := jsonSubSchema.Format; f != nil && *f == "date-time" {
			typ = "Date"
		} else {
			typ = "String"
		}
	}
	switch typ {
	case "Date":
		extraPackages["java.util.Date"] = true
	}
	return classDefinition, comment, typ
}
<commit_msg>Show defaults in json form, no go form<commit_after>package model

import (
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"strconv"
	"strings"

	"github.com/taskcluster/jsonschema2go"
	"github.com/taskcluster/taskcluster-client-java/codegenerator/utils"
)

type JsonSubSchema jsonschema2go.JsonSubSchema

func (jsonSubSchema *JsonSubSchema) TypeDefinition(level int, extraPackages map[string]bool) (classDefinition, comment, typ string) {
	if d := jsonSubSchema.Description; d != nil {
		if desc := *d; desc != "" {
			comment += desc
		}
	}
	if comment != "" && comment[len(comment)-1:] != "\n" {
		comment += "\n"
	}

	// Create comments for metadata in a single paragraph. Only start new
	// paragraph if we discover after inspecting all possible metadata, that
	// something has been specified. If there is no metadata, no need to create
	// a new paragraph.
	var metadata string
	if enum := jsonSubSchema.Enum; enum != nil {
		metadata += "Possible values:\n"
		for _, i := range enum {
			switch i.(type) {
			case float64:
				metadata += fmt.Sprintf("    * %v\n", i)
			default:
				metadata += fmt.Sprintf("    * %q\n", i)
			}
		}
	}
	if def := jsonSubSchema.Default; def != nil {
		var value string
		switch (*def).(type) {
		case bool:
			value = strconv.FormatBool((*def).(bool))
		case float64:
			value = strconv.FormatFloat((*def).(float64), 'g', -1, 64)
		default:
			v, err := json.MarshalIndent(*def, "", "  ")
			if err != nil {
				panic(fmt.Sprintf("couldn't marshal %+v", *def))
			}
			value = string(v)
		}
		metadata += "Default:    " + value + "\n"
	}
	if regex := jsonSubSchema.Pattern; regex != nil {
		metadata += "Syntax:     " + *regex + "\n"
	}
	if minItems := jsonSubSchema.MinLength; minItems != nil {
		metadata += "Min length: " + strconv.Itoa(*minItems) + "\n"
	}
	if maxItems := jsonSubSchema.MaxLength; maxItems != nil {
		metadata += "Max length: " + strconv.Itoa(*maxItems) + "\n"
	}
	if minimum := jsonSubSchema.Minimum; minimum != nil {
		metadata += "Mininum:    " + strconv.Itoa(*minimum) + "\n"
	}
	if maximum := jsonSubSchema.Maximum; maximum != nil {
		metadata += "Maximum:    " + strconv.Itoa(*maximum) + "\n"
	}
	// Here we check if metadata was specified, and only create new
	// paragraph (`*\n`) if something was.
	if len(metadata) > 0 {
		comment += "\n" + metadata
	}

	if URL := jsonSubSchema.SourceURL; URL != "" {
		u, err := url.Parse(URL)
		if err == nil && u.Scheme != "file" {
			if len(comment) > 1 {
				comment += "\n"
			}
			comment += "See " + URL + "\n"
		}
	}
	comment = utils.Comment(comment, "")

	typ = "Object"
	if p := jsonSubSchema.Type; p != nil {
		typ = *p
	}
	if p := jsonSubSchema.RefSubSchema; p != nil {
		j := JsonSubSchema(*jsonSubSchema.RefSubSchema)
		_, _, possSimpleType := (&j).TypeDefinition(0, make(map[string]bool))
		switch possSimpleType {
		case "":
			typ = p.TypeName
		default:
			typ = possSimpleType
		}
	}
	switch typ {
	case "array":
		if jsonSubSchema.Items != nil {
			if jsonSubSchema.Items.Type != nil {
				j := JsonSubSchema(*jsonSubSchema.Items)
				subClassDefinition, _, subType := (&j).TypeDefinition(level, extraPackages)
				if subType == "" {
					log.Fatalf("%v returns an empty Type", jsonSubSchema.Items.SourceURL)
				}
				typ = subType + "[]"
				classDefinition = subClassDefinition

			} else {
				if refSubSchema := jsonSubSchema.Items.RefSubSchema; refSubSchema != nil {
					if refSubSchema.TypeName == "" {
						log.Fatalf("%v has not set TypeName", refSubSchema.SourceURL)
					}
					typ = refSubSchema.TypeName + "[]"
				}
			}
		} else {
			typ = "Object[]"
		}

	case "object":
		if s := jsonSubSchema.Properties; s != nil {
			typ = jsonSubSchema.TypeName
			classDefinition = "\n" + strings.Repeat("    ", level) + "public class " + typ + " {"
			for _, j := range s.SortedPropertyNames {
				// recursive call to build go types inside structs
				var subType string
				c := JsonSubSchema(*s.Properties[j])
				subMember := s.MemberNames[j]
				subClassDefinition, subComment, subType := (&c).TypeDefinition(level+1, extraPackages)
				classDefinition += "\n"
				classDefinition += subClassDefinition
				classDefinition += "\n"
				classDefinition += utils.Indent(subComment, strings.Repeat("    ", level+1), false)
				classDefinition += strings.Repeat("    ", level+1) + "public " + subType + " " + subMember + ";"
			}
			classDefinition += "\n"
			classDefinition += strings.Repeat("    ", level) + "}"
			classDefinition += "\n"
		} else {
			typ = "Object"
		}
	case "number":
		typ = "int"
	case "integer":
		typ = "int"
	case "boolean":
		typ = "boolean"
	// json type string maps to go type string, so only need to test case of when
	// string is a json date-time, so we can convert to go type time.Time...
	case "string":
		if f := jsonSubSchema.Format; f != nil && *f == "date-time" {
			typ = "Date"
		} else {
			typ = "String"
		}
	}
	switch typ {
	case "Date":
		extraPackages["java.util.Date"] = true
	}
	return classDefinition, comment, typ
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/gaeshi-gaeshi/thermo-smart/HeatersController"
	"github.com/gaeshi-gaeshi/thermo-smart/TemperatureSensorController"
)

func main() {
	if os.Args[1] == "--reset" {
		HeatersController.SetNumberOfWorkingHeaters(0)

		return
	}

	targetTemperatureAsFloat64, error := strconv.ParseFloat(os.Args[1], 32)
	if error != nil {
		fmt.Println(error)
		return
	}

	targetTemperature := float32(targetTemperatureAsFloat64)

	fmt.Printf("Target temperature - %.2f\n", targetTemperature)

	for {
		currentTemperature, error := TemperatureSensorController.ReadTemperature()
		if error != nil {
			fmt.Println(error)
			return
		}

		temperatureDifference := targetTemperature - currentTemperature
		if temperatureDifference > 1 {
			HeatersController.SetNumberOfWorkingHeaters(3)
		} else if temperatureDifference <= 1 && temperatureDifference > 0 {
			HeatersController.SetNumberOfWorkingHeaters(2)
		} else if temperatureDifference <= 0 && temperatureDifference > -1 {
			HeatersController.SetNumberOfWorkingHeaters(1)
		} else {
			HeatersController.SetNumberOfWorkingHeaters(0)
		}

		fmt.Printf("Current temperature - %.2f\n", currentTemperature)
		fmt.Printf("Currently working heaters - %d\n", HeatersController.GetNumberOfWorkingHeaters())

		time.Sleep(time.Minute)
	}
}
<commit_msg>Added --temp argument which only prints the current temperature and exits<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/gaeshi-gaeshi/thermo-smart/HeatersController"
	"github.com/gaeshi-gaeshi/thermo-smart/TemperatureSensorController"
)

func main() {
	if os.Args[1] == "--reset" {
		HeatersController.SetNumberOfWorkingHeaters(0)

		return
	}

	if os.Args[1] == "--temp" {
		currentTemperature := getCurrentTemperature()
		printCurrentTemperature(currentTemperature)

		return
	}

	targetTemperatureAsFloat64, error := strconv.ParseFloat(os.Args[1], 32)
	if error != nil {
		fmt.Println(error)
		return
	}

	targetTemperature := float32(targetTemperatureAsFloat64)

	fmt.Printf("Target temperature - %.2f\n", targetTemperature)

	for {
		currentTemperature := getCurrentTemperature()

		temperatureDifference := targetTemperature - currentTemperature
		if temperatureDifference > 1 {
			HeatersController.SetNumberOfWorkingHeaters(3)
		} else if temperatureDifference <= 1 && temperatureDifference > 0 {
			HeatersController.SetNumberOfWorkingHeaters(2)
		} else if temperatureDifference <= 0 && temperatureDifference > -1 {
			HeatersController.SetNumberOfWorkingHeaters(1)
		} else {
			HeatersController.SetNumberOfWorkingHeaters(0)
		}

		printCurrentTemperature(currentTemperature)
		fmt.Printf("Currently working heaters - %d\n", HeatersController.GetNumberOfWorkingHeaters())

		time.Sleep(time.Minute)
	}
}

func getCurrentTemperature() float32 {
	currentTemperature, error := TemperatureSensorController.ReadTemperature()
	if error != nil {
		log.Fatal(error)
	}

	return currentTemperature
}

func printCurrentTemperature(currentTemperature float32) {

	fmt.Printf("Current temperature - %.2f\n", currentTemperature)
}
<|endoftext|>


<commit_before>package main

import (
  "crypto/rsa"
  "crypto/x509"
  "encoding/pem"
  "errors"
  "flag"
  "fmt"
  "io/ioutil"
  "math/big"
  "strconv"
  "github.com/sourcekris/goRsaTool/attacks"
  "github.com/sourcekris/goRsaTool/utils"
)

// https://golang.org/pkg/crypto/x509/#ParsePKIXPublicKey
func ParsePublicRsaKey(keyBytes []byte) (*rsa.PublicKey, error) {
  key, err := x509.ParsePKIXPublicKey(keyBytes)//.Bytes)
  if err != nil {
    return nil, errors.New("Failed to parse the DER key after decoding.")
  }

  switch key := key.(type) {
  case *rsa.PublicKey:
    return key, nil
  default:
    return nil, errors.New("Given key is not an RSA Key")
  }
}

func ParsePrivateRsaKey(keyBytes []byte) (*rsa.PrivateKey, error) {
  key, err := x509.ParsePKCS1PrivateKey(keyBytes)
  if err != nil {
    return nil, errors.New("Failed to parse the DER key after decoding.")
  }
  return key, nil
}

// import a PEM key file and return a rsa.PrivateKey object
func importKey(keyFile string) (*rsa.PrivateKey, error) {
  // read the key from the disk
  keyStr, err := ioutil.ReadFile(keyFile)
  if err != nil {
    fmt.Printf("[-] Failed to open/read file %s\n", keyFile)
    return nil, err
  }

  // decode the PEM data to extract the DER format key
  block, _ := pem.Decode([]byte(keyStr))
  if block == nil {
    return nil, errors.New("Failed to decode PEM key.")
  }

  key, err := ParsePublicRsaKey(block.Bytes)
  if err == nil {
    priv := rsa.PrivateKey{PublicKey: *key}
    return &priv, err
  }

  priv, err := ParsePrivateRsaKey(block.Bytes)
  if err != nil {
    return nil, errors.New("Failed to parse the key as either a public or private key.")
  }
  return priv, err

}

func dumpKey(key *rsa.PrivateKey) {
  fmt.Printf("[*] n = %d\n", key.N)
  fmt.Printf("[*] e = %d\n", key.E)

  // XXX: Support RSA multiprime [where len(key.Primes) > 2]
  if key.D != nil {
    fmt.Printf("[*] d = %d\n", key.D)
    fmt.Printf("[*] p = %d\n", key.Primes[0])
    fmt.Printf("[*] q = %d\n", key.Primes[1])
  }
}

func main() {
  // Parse command line arguments
  keyFile        := flag.String("key", "", "The filename of the RSA key to attack or dump")
  pastPrimesFile := flag.String("pastprimes", "../pastctfprimes.txt", "The filename of a file containing past CTF prime numbers.")
  verboseMode    := flag.Bool("verbose", false, "Enable verbose output.")
  dumpKeyMode    := flag.Bool("dumpkey", false, "Just dump the RSA integers from a key - n,e,d,p,q.")
  createKeyMode  := flag.Bool("createkey", false, "Create a public key given an E and N.")
  exponentArg    := flag.String("e","", "The exponent value - for use with createkey flag.")
  modulusArg     := flag.String("n","", "The modulus value - for use with createkey flag.")
  cipherText     := flag.String("ciphertext", "", "An RSA encrypted binary file to decrypt, necessary for certain attacks.")
  flag.Parse()

  // Print verbose information
  if *verboseMode != false {
    fmt.Printf("[*] goRsaTool\n")
  }

  // Did we get a public key file to read
  if len(*keyFile) > 0 {
    key, _ := importKey(*keyFile)

    if *dumpKeyMode != false {
      dumpKey(key)
      return
    }

    // pack the RSAStuff struct
    targetRSA := &utils.RSAStuff{
      Key: *key,
    }

    if len(*cipherText) > 0 {
      cipherData, err := utils.ReadCipherText(*cipherText)

      if err != nil {
        fmt.Printf("[-] Failed reading ciphertext file.")
        return
      }

      targetRSA.CipherText = cipherData
    }

    if len(*pastPrimesFile) > 0 {
      targetRSA.PastPrimesFile = *pastPrimesFile
    }

    // attacks begin here
    attacks.FactorDB(targetRSA)
    attacks.SmallQ(targetRSA)
    attacks.NoveltyPrimes(targetRSA)
    attacks.PastCTFPrimes(targetRSA)
    attacks.FermatFactorization(targetRSA)
    attacks.Hastads(targetRSA)

    if targetRSA.Key.D != nil {
      privStr := utils.EncodePrivateKey(&targetRSA.Key)
      fmt.Print(privStr)
      return
    }

  } else {
    if *createKeyMode != false {
      if len(*exponentArg) > 0 && len(*modulusArg) > 0 {
        n := new(big.Int)
        n.SetString(*modulusArg, 10)
        e, err := strconv.Atoi(*exponentArg)
        if err != nil {
          fmt.Printf("[-] Failed converting exponent to integer.")
          return
        }

        pub := rsa.PublicKey{N: n, E: e}
        pubStr,_ := utils.EncodePublicKey(&pub)
        fmt.Print(pubStr)
        return
      } else {
        fmt.Printf("[-] No exponent or modulus specified. Nothing to do.\n")
        return
      }
    }
    fmt.Printf("[-] No key file specified. Nothing to do.\n")
    return
  }
}<commit_msg>refactor to use receiver methods<commit_after>package main

import (
  "crypto/rsa"
  "crypto/x509"
  "encoding/pem"
  "errors"
  "flag"
  "fmt"
  "io/ioutil"
  "math/big"
  "strconv"
  "github.com/sourcekris/goRsaTool/attacks"
  "github.com/sourcekris/goRsaTool/utils"
)

// https://golang.org/pkg/crypto/x509/#ParsePKIXPublicKey
func ParsePublicRsaKey(keyBytes []byte) (*rsa.PublicKey, error) {
  key, err := x509.ParsePKIXPublicKey(keyBytes)//.Bytes)
  if err != nil {
    return nil, errors.New("Failed to parse the DER key after decoding.")
  }

  switch key := key.(type) {
  case *rsa.PublicKey:
    return key, nil
  default:
    return nil, errors.New("Given key is not an RSA Key")
  }
}

func ParsePrivateRsaKey(keyBytes []byte) (*rsa.PrivateKey, error) {
  key, err := x509.ParsePKCS1PrivateKey(keyBytes)
  if err != nil {
    return nil, errors.New("Failed to parse the DER key after decoding.")
  }
  return key, nil
}

// import a PEM key file and return a rsa.PrivateKey object
func importKey(keyFile string) (*rsa.PrivateKey, error) {
  // read the key from the disk
  keyStr, err := ioutil.ReadFile(keyFile)
  if err != nil {
    fmt.Printf("[-] Failed to open/read file %s\n", keyFile)
    return nil, err
  }

  // decode the PEM data to extract the DER format key
  block, _ := pem.Decode([]byte(keyStr))
  if block == nil {
    return nil, errors.New("Failed to decode PEM key.")
  }

  key, err := ParsePublicRsaKey(block.Bytes)
  if err == nil {
    priv := rsa.PrivateKey{PublicKey: *key}
    return &priv, err
  }

  priv, err := ParsePrivateRsaKey(block.Bytes)
  if err != nil {
    return nil, errors.New("Failed to parse the key as either a public or private key.")
  }
  return priv, err

}

func dumpKey(key *rsa.PrivateKey) {
  fmt.Printf("[*] n = %d\n", key.N)
  fmt.Printf("[*] e = %d\n", key.E)

  // XXX: Support RSA multiprime [where len(key.Primes) > 2]
  if key.D != nil {
    fmt.Printf("[*] d = %d\n", key.D)
    fmt.Printf("[*] p = %d\n", key.Primes[0])
    fmt.Printf("[*] q = %d\n", key.Primes[1])
  }
}

func main() {
  // Parse command line arguments
  keyFile        := flag.String("key", "", "The filename of the RSA key to attack or dump")
  pastPrimesFile := flag.String("pastprimes", "../pastctfprimes.txt", "The filename of a file containing past CTF prime numbers.")
  verboseMode    := flag.Bool("verbose", false, "Enable verbose output.")
  dumpKeyMode    := flag.Bool("dumpkey", false, "Just dump the RSA integers from a key - n,e,d,p,q.")
  createKeyMode  := flag.Bool("createkey", false, "Create a public key given an E and N.")
  exponentArg    := flag.String("e","", "The exponent value - for use with createkey flag.")
  modulusArg     := flag.String("n","", "The modulus value - for use with createkey flag.")
  cipherText     := flag.String("ciphertext", "", "An RSA encrypted binary file to decrypt, necessary for certain attacks.")
  flag.Parse()

  // Print verbose information
  if *verboseMode != false {
    fmt.Printf("[*] goRsaTool\n")
  }

  // Did we get a public key file to read
  if len(*keyFile) > 0 {
    key, _ := importKey(*keyFile)

    if *dumpKeyMode != false {
      dumpKey(key)
      return
    }

    var c []byte
    var err error
    if len(*cipherText) > 0 {
      c, err = utils.ReadCipherText(*cipherText)

      if err != nil {
        fmt.Printf("[-] Failed reading ciphertext file.")
        return
      }
    }

    targetRSA, _ := attacks.NewRSAStuff(key, c, nil, *pastPrimesFile)

    // attacks begin here
    //attacks.FactorDB(targetRSA)
    //targetRSA.SmallQ()
    //attacks.NoveltyPrimes(targetRSA)
    //attacks.PastCTFPrimes(targetRSA)
    targetRSA.FermatFactorization()
    //attacks.Hastads(targetRSA)

    if targetRSA.Key.D != nil {
      privStr := utils.EncodePrivateKey(&targetRSA.Key)
      fmt.Print(privStr)
      return
    }

  } else {
    if *createKeyMode != false {
      if len(*exponentArg) > 0 && len(*modulusArg) > 0 {
        n := new(big.Int)
        n.SetString(*modulusArg, 10)
        e, err := strconv.Atoi(*exponentArg)
        if err != nil {
          fmt.Printf("[-] Failed converting exponent to integer.")
          return
        }

        pub := rsa.PublicKey{N: n, E: e}
        pubStr,_ := utils.EncodePublicKey(&pub)
        fmt.Print(pubStr)
        return
      } else {
        fmt.Printf("[-] No exponent or modulus specified. Nothing to do.\n")
        return
      }
    }
    fmt.Printf("[-] No key file specified. Nothing to do.\n")
    return
  }
}<|endoftext|>


<commit_before>package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/go-kit/kit/log/level"
	"github.com/goph/emperror"
	"github.com/goph/healthz"
	"github.com/goph/serverz"
	"github.com/goph/stdlib/ext"
	"github.com/kelseyhightower/envconfig"
)

func main() {
	config := &configuration{}

	// Load configuration from environment
	err := envconfig.Process("", config)
	if err != nil {
		panic(err)
	}

	// Load configuration from flags
	flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	config.flags(flags)
	flags.Parse(os.Args[1:])

	// Create a new logger
	logger := newLogger(config)
	defer ext.Close(logger)

	// Create a new error handler
	errorHandler := newErrorHandler(config, logger)
	defer ext.Close(errorHandler)

	// Register error handler to recover from panics
	defer emperror.HandleRecover(errorHandler)

	// Initiate metrics scope
	metrics := newMetrics(config)
	defer ext.Close(metrics)

	// Application context
	appCtx := &application{
		config:          config,
		logger:          logger,
		errorHandler:    errorHandler,
		healthCollector: healthz.Collector{},
		tracer:          newTracer(config),
		metrics:         metrics,
	}

	serverQueue := serverz.NewQueue(&serverz.Manager{Logger: logger})

	level.Info(logger).Log(
		"msg", fmt.Sprintf("Starting %s", FriendlyServiceName),
		"version", Version,
		"commitHash", CommitHash,
		"buildDate", BuildDate,
		"environment", config.Environment,
	)

	if config.Debug {
		debugServer := newDebugServer(logger)
		serverQueue.Append(debugServer, config.DebugAddr)
		defer debugServer.Close()
	}

	server := newServer(appCtx)
	serverQueue.Prepend(server, config.ServiceAddr)
	defer server.Close()

	healthServer, status := newHealthServer(appCtx)
	serverQueue.Prepend(healthServer, config.HealthAddr)
	defer healthServer.Close()

	errChan := serverQueue.Start()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

MainLoop:
	for {
		select {
		case err := <-errChan:
			status.SetStatus(healthz.Unhealthy)
			level.Debug(logger).Log("msg", "Error received from error channel")
			emperror.HandleIfErr(errorHandler, err)

			// Break the loop, proceed with regular shutdown
			break MainLoop
		case s := <-signalChan:
			level.Info(logger).Log("msg", fmt.Sprintf("Captured %v", s))
			status.SetStatus(healthz.Unhealthy)

			level.Debug(logger).Log(
				"msg", "Shutting down with timeout",
				"timeout", config.ShutdownTimeout,
			)

			ctx, cancel := context.WithTimeout(context.Background(), config.ShutdownTimeout)

			err := serverQueue.Stop(ctx)
			if err != nil {
				errorHandler.Handle(err)
			}

			// Cancel context if shutdown completed earlier
			cancel()

			// Break the loop, proceed with regular shutdown
			break MainLoop
		}
	}
}
<commit_msg>Remove unnecessary for loop<commit_after>package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/go-kit/kit/log/level"
	"github.com/goph/emperror"
	"github.com/goph/healthz"
	"github.com/goph/serverz"
	"github.com/goph/stdlib/ext"
	"github.com/kelseyhightower/envconfig"
)

func main() {
	config := &configuration{}

	// Load configuration from environment
	err := envconfig.Process("", config)
	if err != nil {
		panic(err)
	}

	// Load configuration from flags
	flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	config.flags(flags)
	flags.Parse(os.Args[1:])

	// Create a new logger
	logger := newLogger(config)
	defer ext.Close(logger)

	// Create a new error handler
	errorHandler := newErrorHandler(config, logger)
	defer ext.Close(errorHandler)

	// Register error handler to recover from panics
	defer emperror.HandleRecover(errorHandler)

	// Initiate metrics scope
	metrics := newMetrics(config)
	defer ext.Close(metrics)

	// Application context
	appCtx := &application{
		config:          config,
		logger:          logger,
		errorHandler:    errorHandler,
		healthCollector: healthz.Collector{},
		tracer:          newTracer(config),
		metrics:         metrics,
	}

	serverQueue := serverz.NewQueue(&serverz.Manager{Logger: logger})

	level.Info(logger).Log(
		"msg", fmt.Sprintf("Starting %s", FriendlyServiceName),
		"version", Version,
		"commitHash", CommitHash,
		"buildDate", BuildDate,
		"environment", config.Environment,
	)

	if config.Debug {
		debugServer := newDebugServer(logger)
		serverQueue.Append(debugServer, config.DebugAddr)
		defer debugServer.Close()
	}

	server := newServer(appCtx)
	serverQueue.Prepend(server, config.ServiceAddr)
	defer server.Close()

	healthServer, status := newHealthServer(appCtx)
	serverQueue.Prepend(healthServer, config.HealthAddr)
	defer healthServer.Close()

	errChan := serverQueue.Start()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	select {
	case err := <-errChan:
		status.SetStatus(healthz.Unhealthy)
		level.Debug(logger).Log("msg", "Error received from error channel")
		emperror.HandleIfErr(errorHandler, err)
	case s := <-signalChan:
		level.Info(logger).Log("msg", fmt.Sprintf("Captured %v", s))
		status.SetStatus(healthz.Unhealthy)

		level.Debug(logger).Log(
			"msg", "Shutting down with timeout",
			"timeout", config.ShutdownTimeout,
		)

		ctx, cancel := context.WithTimeout(context.Background(), config.ShutdownTimeout)

		err := serverQueue.Stop(ctx)
		if err != nil {
			errorHandler.Handle(err)
		}

		// Cancel context if shutdown completed earlier
		cancel()
	}
}
<|endoftext|>


<commit_before>package main

import "fmt"

func main(){

   forMethod();

   forMultipleMethod();

   breakStatement();

   continueStatement();

   gotoStatement();

}

func forMethod(){
	fmt.Println(" \n\n \t for 循环 \n ")
	var b int = 10
	var a int

	numbers := [6]int{1, 2, 3, 6}
	/* for loop execution */
	fmt.Println(" \n for case 1 ")
	for i := 0; i < 10; i++{
		fmt.Printf(" \n value of i is: %d ", i)
	}
	fmt.Println(" \n for case 2 -----")
	for a < b {
		a++
		fmt.Println(" for a value is ", a, " for a value is ", b)
	}
	fmt.Println(" \n for case3 ")
	for i, x :=range numbers{
		fmt.Printf(" \n value od x = %d and i =  %d ", x, i)
	}

	fmt.Println(" \n\n a value is ", a, " b value is ", b, " numbers value is ", numbers)
}

func forMultipleMethod(){
	fmt.Println(" \n\n \t 嵌套循环  \n")

	var i, j int
	for i = 2; i <= 100; i++ {
		for j = 2; j <= (i / j); j++{
			if( i % j == 0){
				fmt.Println(" i value is ", i , " and j value is ", j , " i % j == 0 ")
				break;
			}
		}
		if(j > ( i / j)){
			fmt.Printf(" \n  i = %d,  j = %d is prime \n ", i, j)
		}

	}
}

func breakStatement(){
	fmt.Println(" \n\n \t break语句 ")
	var a int = 10

	/* for loop execution */
	for a < 25 {
		fmt.Printf(" \n value of a: %d ", a)
		a++
		if a > 15{
			fmt.Println("\n\n break when a > 15, a =", a)
			break
		}
	}
}

func continueStatement(){
	fmt.Println(" \n\n \t  continue 语句 ")

}

func gotoStatement(){
	fmt.Println(" \n\n \t goto语句 ")

}<commit_msg>2015-06-08 lidongxu demo8 for-continue case<commit_after>package main

import "fmt"

func main(){

   forMethod();

   forMultipleMethod();

   breakStatement();

   continueStatement();

   gotoStatement();

}

func forMethod(){
	fmt.Println(" \n\n \t for 循环 \n ")
	var b int = 10
	var a int

	numbers := [6]int{1, 2, 3, 6}
	/* for loop execution */
	fmt.Println(" \n for case 1 ")
	for i := 0; i < 10; i++{
		fmt.Printf(" \n value of i is: %d ", i)
	}
	fmt.Println(" \n for case 2 -----")
	for a < b {
		a++
		fmt.Println(" for a value is ", a, " for a value is ", b)
	}
	fmt.Println(" \n for case3 ")
	for i, x :=range numbers{
		fmt.Printf(" \n value od x = %d and i =  %d ", x, i)
	}

	fmt.Println(" \n\n a value is ", a, " b value is ", b, " numbers value is ", numbers)
}

func forMultipleMethod(){
	fmt.Println(" \n\n \t 嵌套循环  \n")

	var i, j int
	for i = 2; i <= 100; i++ {
		for j = 2; j <= (i / j); j++{
			if( i % j == 0){
				fmt.Println(" i value is ", i , " and j value is ", j , " i % j == 0 ")
				break;
			}
		}
		if(j > ( i / j)){
			fmt.Printf(" \n  i = %d,  j = %d is prime \n ", i, j)
		}

	}
}

func breakStatement(){
	fmt.Println(" \n\n \t break语句 ")
	var a int = 10

	/* for loop execution */
	for a < 25 {
		fmt.Printf(" \n value of a: %d ", a)
		a++
		if a > 15{
			fmt.Println("\n\n break when a > 15, a =", a)
			break
		}
	}
}

func continueStatement(){
	fmt.Println(" \n\n \t  continue 语句 ")

	var a int = 10

	for a < 25 {
		if a == 15 || a == 17 || a == 18 {
			a = a + 1
			continue
		}
		fmt.Println(" value a is : ", a)
		a++
	}

}

func gotoStatement(){
	fmt.Println(" \n\n \t goto语句 ")

}<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"log"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/emr"
	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSEMRInstanceGroup_basic(t *testing.T) {
	var ig emr.InstanceGroup
	rInt := acctest.RandInt()
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEmrInstanceGroupDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEmrInstanceGroupConfig(rInt),
				Check:  testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
			},
		},
	})
}

// Confirm we can scale down the instance count. Regression test for https://github.com/terraform-providers/terraform-provider-aws/issues/1264
func TestAccAWSEMRInstanceGroup_zero_count(t *testing.T) {
	var ig emr.InstanceGroup
	rInt := acctest.RandInt()
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEmrInstanceGroupDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEmrInstanceGroupConfig(rInt),
				Check:  testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
			},
			{
				Config: testAccAWSEmrInstanceGroupConfig_zero_count(rInt),
				Check:  testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
			},
		},
	})
}

func TestAccAWSEMRInstanceGroup_ebsBasic(t *testing.T) {
	var ig emr.InstanceGroup
	rInt := acctest.RandInt()
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEmrInstanceGroupDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEmrInstanceGroupConfig_ebsBasic(rInt),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
					resource.TestCheckResourceAttr(
						"aws_emr_instance_group.task", "ebs_config.#", "1"),
					resource.TestCheckResourceAttr(
						"aws_emr_instance_group.task", "ebs_optimized", "true"),
				),
			},
		},
	})
}

func testAccCheckAWSEmrInstanceGroupDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).emrconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_emr_cluster" {
			continue
		}

		params := &emr.DescribeClusterInput{
			ClusterId: aws.String(rs.Primary.ID),
		}

		describe, err := conn.DescribeCluster(params)

		if err == nil {
			if describe.Cluster != nil &&
				*describe.Cluster.Status.State == "WAITING" {
				return fmt.Errorf("EMR Cluster still exists")
			}
		}

		providerErr, ok := err.(awserr.Error)
		if !ok {
			return err
		}

		log.Printf("[ERROR] %v", providerErr)
	}

	return nil
}

func testAccCheckAWSEmrInstanceGroupExists(n string, v *emr.InstanceGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}
		if rs.Primary.ID == "" {
			return fmt.Errorf("No task group id set")
		}
		meta := testAccProvider.Meta()
		conn := meta.(*AWSClient).emrconn
		g, err := fetchEMRInstanceGroup(conn, rs.Primary.Attributes["cluster_id"], rs.Primary.ID)
		if err != nil {
			return fmt.Errorf("EMR error: %v", err)
		}

		if g == nil {
			return fmt.Errorf("No match found for (%s)", n)
		}

		v = g
		return nil
	}
}

const testAccAWSEmrInstanceGroupBase = `
provider "aws" {
  region = "us-west-2"
}

resource "aws_emr_cluster" "tf-test-cluster" {
  name          = "tf-test-emr-%d"
  release_label = "emr-4.6.0"
  applications  = ["Spark"]

  ec2_attributes {
    subnet_id                         = "${aws_subnet.main.id}"
    emr_managed_master_security_group = "${aws_security_group.allow_all.id}"
    emr_managed_slave_security_group  = "${aws_security_group.allow_all.id}"
    instance_profile                  = "${aws_iam_instance_profile.emr_profile.arn}"
  }

  master_instance_type = "c4.large"
  core_instance_type   = "c4.large"
  core_instance_count  = 2

  tags = {
    role     = "rolename"
    dns_zone = "env_zone"
    env      = "env"
    name     = "name-env"
  }

  bootstrap_action {
    path = "s3://elasticmapreduce/bootstrap-actions/run-if"
    name = "runif"
    args = ["instance.isMaster=true", "echo running on master node"]
  }

  configurations = "test-fixtures/emr_configurations.json"
  service_role = "${aws_iam_role.iam_emr_default_role.arn}"

  depends_on = ["aws_internet_gateway.gw"]
}

resource "aws_security_group" "allow_all" {
  name        = "allow_all"
  description = "Allow all inbound traffic"
  vpc_id      = "${aws_vpc.main.id}"

  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    self        = true
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  depends_on = ["aws_subnet.main"]

  lifecycle {
    ignore_changes = ["ingress", "egress"]
  }
}

resource "aws_vpc" "main" {
  cidr_block           = "168.31.0.0/16"
  enable_dns_hostnames = true

	tags = {
		Name = "terraform-testacc-emr-instance-group"
	}
}

resource "aws_subnet" "main" {
  vpc_id     = "${aws_vpc.main.id}"
  cidr_block = "168.31.0.0/20"

  tags = {
    Name = "tf-acc-emr-instance-group"
  }
}

resource "aws_internet_gateway" "gw" {
  vpc_id = "${aws_vpc.main.id}"
}

resource "aws_route_table" "r" {
  vpc_id = "${aws_vpc.main.id}"

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = "${aws_internet_gateway.gw.id}"
  }
}

resource "aws_main_route_table_association" "a" {
  vpc_id         = "${aws_vpc.main.id}"
  route_table_id = "${aws_route_table.r.id}"
}

###

# IAM role for EMR Service
resource "aws_iam_role" "iam_emr_default_role" {
  name = "iam_emr_default_role_%d"

  assume_role_policy = <<EOT
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "elasticmapreduce.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOT
}

resource "aws_iam_role_policy_attachment" "service-attach" {
  role       = "${aws_iam_role.iam_emr_default_role.id}"
  policy_arn = "${aws_iam_policy.iam_emr_default_policy.arn}"
}

resource "aws_iam_policy" "iam_emr_default_policy" {
  name = "iam_emr_default_policy_%d"

  policy = <<EOT
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Resource": "*",
        "Action": [
            "ec2:AuthorizeSecurityGroupEgress",
            "ec2:AuthorizeSecurityGroupIngress",
            "ec2:CancelSpotInstanceRequests",
            "ec2:CreateNetworkInterface",
            "ec2:CreateSecurityGroup",
            "ec2:CreateTags",
            "ec2:DeleteNetworkInterface",
            "ec2:DeleteSecurityGroup",
            "ec2:DeleteTags",
            "ec2:DescribeAvailabilityZones",
            "ec2:DescribeAccountAttributes",
            "ec2:DescribeDhcpOptions",
            "ec2:DescribeInstanceStatus",
            "ec2:DescribeInstances",
            "ec2:DescribeKeyPairs",
            "ec2:DescribeNetworkAcls",
            "ec2:DescribeNetworkInterfaces",
            "ec2:DescribePrefixLists",
            "ec2:DescribeRouteTables",
            "ec2:DescribeSecurityGroups",
            "ec2:DescribeSpotInstanceRequests",
            "ec2:DescribeSpotPriceHistory",
            "ec2:DescribeSubnets",
            "ec2:DescribeVpcAttribute",
            "ec2:DescribeVpcEndpoints",
            "ec2:DescribeVpcEndpointServices",
            "ec2:DescribeVpcs",
            "ec2:DetachNetworkInterface",
            "ec2:ModifyImageAttribute",
            "ec2:ModifyInstanceAttribute",
            "ec2:RequestSpotInstances",
            "ec2:RevokeSecurityGroupEgress",
            "ec2:RunInstances",
            "ec2:TerminateInstances",
            "ec2:DeleteVolume",
            "ec2:DescribeVolumeStatus",
            "ec2:DescribeVolumes",
            "ec2:DetachVolume",
            "iam:GetRole",
            "iam:GetRolePolicy",
            "iam:ListInstanceProfiles",
            "iam:ListRolePolicies",
            "iam:PassRole",
            "s3:CreateBucket",
            "s3:Get*",
            "s3:List*",
            "sdb:BatchPutAttributes",
            "sdb:Select",
            "sqs:CreateQueue",
            "sqs:Delete*",
            "sqs:GetQueue*",
            "sqs:PurgeQueue",
            "sqs:ReceiveMessage"
        ]
    }]
}
EOT
}

# IAM Role for EC2 Instance Profile
resource "aws_iam_role" "iam_emr_profile_role" {
  name = "iam_emr_profile_role_%d"

  assume_role_policy = <<EOT
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOT
}

resource "aws_iam_instance_profile" "emr_profile" {
  name  = "emr_profile_%d"
  roles = ["${aws_iam_role.iam_emr_profile_role.name}"]
}

resource "aws_iam_role_policy_attachment" "profile-attach" {
  role       = "${aws_iam_role.iam_emr_profile_role.id}"
  policy_arn = "${aws_iam_policy.iam_emr_profile_policy.arn}"
}

resource "aws_iam_policy" "iam_emr_profile_policy" {
  name = "iam_emr_profile_policy_%d"

  policy = <<EOT
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Resource": "*",
        "Action": [
            "cloudwatch:*",
            "dynamodb:*",
            "ec2:Describe*",
            "elasticmapreduce:Describe*",
            "elasticmapreduce:ListBootstrapActions",
            "elasticmapreduce:ListClusters",
            "elasticmapreduce:ListInstanceGroups",
            "elasticmapreduce:ListInstances",
            "elasticmapreduce:ListSteps",
            "kinesis:CreateStream",
            "kinesis:DeleteStream",
            "kinesis:DescribeStream",
            "kinesis:GetRecords",
            "kinesis:GetShardIterator",
            "kinesis:MergeShards",
            "kinesis:PutRecord",
            "kinesis:SplitShard",
            "rds:Describe*",
            "s3:*",
            "sdb:*",
            "sns:*",
            "sqs:*"
        ]
    }]
}
EOT
}
`

func testAccAWSEmrInstanceGroupConfig(r int) string {
	return fmt.Sprintf(testAccAWSEmrInstanceGroupBase+`
	resource "aws_emr_instance_group" "task" {
    cluster_id     = "${aws_emr_cluster.tf-test-cluster.id}"
    instance_count = 1
    instance_type  = "c4.large"
  }
	`, r, r, r, r, r, r)
}

func testAccAWSEmrInstanceGroupConfig_zero_count(r int) string {
	return fmt.Sprintf(testAccAWSEmrInstanceGroupBase+`
	resource "aws_emr_instance_group" "task" {
    cluster_id     = "${aws_emr_cluster.tf-test-cluster.id}"
    instance_count = 0
    instance_type  = "c4.large"
  }
	`, r, r, r, r, r, r)
}

func testAccAWSEmrInstanceGroupConfig_ebsBasic(r int) string {
	return fmt.Sprintf(testAccAWSEmrInstanceGroupBase+`
		resource "aws_emr_instance_group" "task" {
    cluster_id     = "${aws_emr_cluster.tf-test-cluster.id}"
    instance_count = 1
    instance_type  = "c4.large"
    ebs_optimized = true
    ebs_config {
      "size" = 10,
      "type" = "gp2",
    }
  }
	`, r, r, r, r, r, r)
}
<commit_msg>tests/resource/aws_emr_instance_group: Fix Terraform 0.12 syntax<commit_after>package aws

import (
	"fmt"
	"log"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/emr"
	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSEMRInstanceGroup_basic(t *testing.T) {
	var ig emr.InstanceGroup
	rInt := acctest.RandInt()
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEmrInstanceGroupDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEmrInstanceGroupConfig(rInt),
				Check:  testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
			},
		},
	})
}

// Confirm we can scale down the instance count. Regression test for https://github.com/terraform-providers/terraform-provider-aws/issues/1264
func TestAccAWSEMRInstanceGroup_zero_count(t *testing.T) {
	var ig emr.InstanceGroup
	rInt := acctest.RandInt()
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEmrInstanceGroupDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEmrInstanceGroupConfig(rInt),
				Check:  testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
			},
			{
				Config: testAccAWSEmrInstanceGroupConfig_zero_count(rInt),
				Check:  testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
			},
		},
	})
}

func TestAccAWSEMRInstanceGroup_ebsBasic(t *testing.T) {
	var ig emr.InstanceGroup
	rInt := acctest.RandInt()
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEmrInstanceGroupDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEmrInstanceGroupConfig_ebsBasic(rInt),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSEmrInstanceGroupExists("aws_emr_instance_group.task", &ig),
					resource.TestCheckResourceAttr(
						"aws_emr_instance_group.task", "ebs_config.#", "1"),
					resource.TestCheckResourceAttr(
						"aws_emr_instance_group.task", "ebs_optimized", "true"),
				),
			},
		},
	})
}

func testAccCheckAWSEmrInstanceGroupDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).emrconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_emr_cluster" {
			continue
		}

		params := &emr.DescribeClusterInput{
			ClusterId: aws.String(rs.Primary.ID),
		}

		describe, err := conn.DescribeCluster(params)

		if err == nil {
			if describe.Cluster != nil &&
				*describe.Cluster.Status.State == "WAITING" {
				return fmt.Errorf("EMR Cluster still exists")
			}
		}

		providerErr, ok := err.(awserr.Error)
		if !ok {
			return err
		}

		log.Printf("[ERROR] %v", providerErr)
	}

	return nil
}

func testAccCheckAWSEmrInstanceGroupExists(n string, v *emr.InstanceGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}
		if rs.Primary.ID == "" {
			return fmt.Errorf("No task group id set")
		}
		meta := testAccProvider.Meta()
		conn := meta.(*AWSClient).emrconn
		g, err := fetchEMRInstanceGroup(conn, rs.Primary.Attributes["cluster_id"], rs.Primary.ID)
		if err != nil {
			return fmt.Errorf("EMR error: %v", err)
		}

		if g == nil {
			return fmt.Errorf("No match found for (%s)", n)
		}

		v = g
		return nil
	}
}

const testAccAWSEmrInstanceGroupBase = `
provider "aws" {
  region = "us-west-2"
}

resource "aws_emr_cluster" "tf-test-cluster" {
  name          = "tf-test-emr-%d"
  release_label = "emr-4.6.0"
  applications  = ["Spark"]

  ec2_attributes {
    subnet_id                         = "${aws_subnet.main.id}"
    emr_managed_master_security_group = "${aws_security_group.allow_all.id}"
    emr_managed_slave_security_group  = "${aws_security_group.allow_all.id}"
    instance_profile                  = "${aws_iam_instance_profile.emr_profile.arn}"
  }

  master_instance_type = "c4.large"
  core_instance_type   = "c4.large"
  core_instance_count  = 2

  tags = {
    role     = "rolename"
    dns_zone = "env_zone"
    env      = "env"
    name     = "name-env"
  }

  bootstrap_action {
    path = "s3://elasticmapreduce/bootstrap-actions/run-if"
    name = "runif"
    args = ["instance.isMaster=true", "echo running on master node"]
  }

  configurations = "test-fixtures/emr_configurations.json"
  service_role = "${aws_iam_role.iam_emr_default_role.arn}"

  depends_on = ["aws_internet_gateway.gw"]
}

resource "aws_security_group" "allow_all" {
  name        = "allow_all"
  description = "Allow all inbound traffic"
  vpc_id      = "${aws_vpc.main.id}"

  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    self        = true
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  depends_on = ["aws_subnet.main"]

  lifecycle {
    ignore_changes = ["ingress", "egress"]
  }
}

resource "aws_vpc" "main" {
  cidr_block           = "168.31.0.0/16"
  enable_dns_hostnames = true

	tags = {
		Name = "terraform-testacc-emr-instance-group"
	}
}

resource "aws_subnet" "main" {
  vpc_id     = "${aws_vpc.main.id}"
  cidr_block = "168.31.0.0/20"

  tags = {
    Name = "tf-acc-emr-instance-group"
  }
}

resource "aws_internet_gateway" "gw" {
  vpc_id = "${aws_vpc.main.id}"
}

resource "aws_route_table" "r" {
  vpc_id = "${aws_vpc.main.id}"

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = "${aws_internet_gateway.gw.id}"
  }
}

resource "aws_main_route_table_association" "a" {
  vpc_id         = "${aws_vpc.main.id}"
  route_table_id = "${aws_route_table.r.id}"
}

###

# IAM role for EMR Service
resource "aws_iam_role" "iam_emr_default_role" {
  name = "iam_emr_default_role_%d"

  assume_role_policy = <<EOT
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "elasticmapreduce.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOT
}

resource "aws_iam_role_policy_attachment" "service-attach" {
  role       = "${aws_iam_role.iam_emr_default_role.id}"
  policy_arn = "${aws_iam_policy.iam_emr_default_policy.arn}"
}

resource "aws_iam_policy" "iam_emr_default_policy" {
  name = "iam_emr_default_policy_%d"

  policy = <<EOT
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Resource": "*",
        "Action": [
            "ec2:AuthorizeSecurityGroupEgress",
            "ec2:AuthorizeSecurityGroupIngress",
            "ec2:CancelSpotInstanceRequests",
            "ec2:CreateNetworkInterface",
            "ec2:CreateSecurityGroup",
            "ec2:CreateTags",
            "ec2:DeleteNetworkInterface",
            "ec2:DeleteSecurityGroup",
            "ec2:DeleteTags",
            "ec2:DescribeAvailabilityZones",
            "ec2:DescribeAccountAttributes",
            "ec2:DescribeDhcpOptions",
            "ec2:DescribeInstanceStatus",
            "ec2:DescribeInstances",
            "ec2:DescribeKeyPairs",
            "ec2:DescribeNetworkAcls",
            "ec2:DescribeNetworkInterfaces",
            "ec2:DescribePrefixLists",
            "ec2:DescribeRouteTables",
            "ec2:DescribeSecurityGroups",
            "ec2:DescribeSpotInstanceRequests",
            "ec2:DescribeSpotPriceHistory",
            "ec2:DescribeSubnets",
            "ec2:DescribeVpcAttribute",
            "ec2:DescribeVpcEndpoints",
            "ec2:DescribeVpcEndpointServices",
            "ec2:DescribeVpcs",
            "ec2:DetachNetworkInterface",
            "ec2:ModifyImageAttribute",
            "ec2:ModifyInstanceAttribute",
            "ec2:RequestSpotInstances",
            "ec2:RevokeSecurityGroupEgress",
            "ec2:RunInstances",
            "ec2:TerminateInstances",
            "ec2:DeleteVolume",
            "ec2:DescribeVolumeStatus",
            "ec2:DescribeVolumes",
            "ec2:DetachVolume",
            "iam:GetRole",
            "iam:GetRolePolicy",
            "iam:ListInstanceProfiles",
            "iam:ListRolePolicies",
            "iam:PassRole",
            "s3:CreateBucket",
            "s3:Get*",
            "s3:List*",
            "sdb:BatchPutAttributes",
            "sdb:Select",
            "sqs:CreateQueue",
            "sqs:Delete*",
            "sqs:GetQueue*",
            "sqs:PurgeQueue",
            "sqs:ReceiveMessage"
        ]
    }]
}
EOT
}

# IAM Role for EC2 Instance Profile
resource "aws_iam_role" "iam_emr_profile_role" {
  name = "iam_emr_profile_role_%d"

  assume_role_policy = <<EOT
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOT
}

resource "aws_iam_instance_profile" "emr_profile" {
  name  = "emr_profile_%d"
  roles = ["${aws_iam_role.iam_emr_profile_role.name}"]
}

resource "aws_iam_role_policy_attachment" "profile-attach" {
  role       = "${aws_iam_role.iam_emr_profile_role.id}"
  policy_arn = "${aws_iam_policy.iam_emr_profile_policy.arn}"
}

resource "aws_iam_policy" "iam_emr_profile_policy" {
  name = "iam_emr_profile_policy_%d"

  policy = <<EOT
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Resource": "*",
        "Action": [
            "cloudwatch:*",
            "dynamodb:*",
            "ec2:Describe*",
            "elasticmapreduce:Describe*",
            "elasticmapreduce:ListBootstrapActions",
            "elasticmapreduce:ListClusters",
            "elasticmapreduce:ListInstanceGroups",
            "elasticmapreduce:ListInstances",
            "elasticmapreduce:ListSteps",
            "kinesis:CreateStream",
            "kinesis:DeleteStream",
            "kinesis:DescribeStream",
            "kinesis:GetRecords",
            "kinesis:GetShardIterator",
            "kinesis:MergeShards",
            "kinesis:PutRecord",
            "kinesis:SplitShard",
            "rds:Describe*",
            "s3:*",
            "sdb:*",
            "sns:*",
            "sqs:*"
        ]
    }]
}
EOT
}
`

func testAccAWSEmrInstanceGroupConfig(r int) string {
	return fmt.Sprintf(testAccAWSEmrInstanceGroupBase+`
	resource "aws_emr_instance_group" "task" {
    cluster_id     = "${aws_emr_cluster.tf-test-cluster.id}"
    instance_count = 1
    instance_type  = "c4.large"
  }
	`, r, r, r, r, r, r)
}

func testAccAWSEmrInstanceGroupConfig_zero_count(r int) string {
	return fmt.Sprintf(testAccAWSEmrInstanceGroupBase+`
	resource "aws_emr_instance_group" "task" {
    cluster_id     = "${aws_emr_cluster.tf-test-cluster.id}"
    instance_count = 0
    instance_type  = "c4.large"
  }
	`, r, r, r, r, r, r)
}

func testAccAWSEmrInstanceGroupConfig_ebsBasic(r int) string {
	return fmt.Sprintf(testAccAWSEmrInstanceGroupBase+`
		resource "aws_emr_instance_group" "task" {
    cluster_id     = "${aws_emr_cluster.tf-test-cluster.id}"
    instance_count = 1
    instance_type  = "c4.large"
    ebs_optimized = true
    ebs_config {
      size = 10
      type = "gp2"
    }
  }
	`, r, r, r, r, r, r)
}
<|endoftext|>


<commit_before>package xmpp

import (
	"crypto/tls"
	"encoding/xml"
	"errors"
	"fmt"
	"log"
)

// Config structure used to create a new XMPP client connection.
type ClientConfig struct {
	// Don't upgrade the connection to TLS, even if the server supports it. If
	// the server *requires* TLS then this option is ignored.
	NoTLS bool

	// Skip verification of the server's certificate chain. Probably only
	// useful during development.
	InsecureSkipVerify bool
}

// Create a client XMPP over the stream.
func NewClientXMPP(stream *Stream, jid JID, password string, config *ClientConfig) (*XMPP, error) {

	if config == nil {
		config = &ClientConfig{}
	}

	for {

		if err := startClient(stream, jid); err != nil {
			return nil, err
		}

		// Read features.
		f := new(features)
		if err := stream.Decode(f); err != nil {
			return nil, err
		}

		// TLS?
		if f.StartTLS != nil && (f.StartTLS.Required != nil || !config.NoTLS) {
			log.Println("Start TLS")
			if err := startTLS(stream, config); err != nil {
				return nil, err
			}
			continue // Restart
		}

		// Authentication
		if f.Mechanisms != nil {
			log.Println("Authenticating")
			if err := authenticate(stream, f.Mechanisms.Mechanisms, jid.Node, password); err != nil {
				return nil, err
			}
			continue // Restart
		}

		// Bind resource.
		if f.Bind != nil {
			log.Println("Binding resource.")
			boundJID, err := bindResource(stream, jid)
			if err != nil {
				return nil, err
			}
			jid = boundJID
		}

		break
	}

	return newXMPP(jid, stream), nil
}

func startClient(stream *Stream, jid JID) error {

	start := xml.StartElement{
		xml.Name{"stream", "stream"},
		[]xml.Attr{
			xml.Attr{xml.Name{"", "xmlns"}, "jabber:client"},
			xml.Attr{xml.Name{"xmlns", "stream"}, "http://etherx.jabber.org/streams"},
			xml.Attr{xml.Name{"", "from"}, jid.Full()},
			xml.Attr{xml.Name{"", "to"}, jid.Domain},
			xml.Attr{xml.Name{"", "version"}, "1.0"},
		},
	}

	if err := stream.SendStart(&start); err != nil {
		return err
	}

	if _, err := stream.Next(&xml.Name{nsStream, "stream"}); err != nil {
		return err
	}

	return nil
}

func startTLS(stream *Stream, config *ClientConfig) error {

	if err := stream.Send(&tlsStart{}); err != nil {
		return err
	}

	p := tlsProceed{}
	if err := stream.Decode(&p); err != nil {
		return err
	}

	tlsConfig := tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}
	return stream.UpgradeTLS(&tlsConfig)
}

type tlsStart struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls starttls"`
}

type tlsProceed struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls proceed"`
}

func authenticate(stream *Stream, mechanisms []string, user, password string) error {

	log.Println("authenticate, mechanisms=", mechanisms)

	if !stringSliceContains(mechanisms, "PLAIN") {
		return errors.New("Only PLAIN supported for now")
	}

	return authenticatePlain(stream, user, password)
}

func authenticatePlain(stream *Stream, user, password string) error {

	auth := saslAuth{Mechanism: "PLAIN", Message: saslEncodePlain(user, password)}
	if err := stream.Send(&auth); err != nil {
		return err
	}

	se, err := stream.Next(nil)
	if err != nil {
		return err
	}
	switch se.Name.Local {
	case "success":
		if err := stream.Skip(); err != nil {
			return err
		}
	case "failure":
		f := new(saslFailure)
		stream.DecodeElement(f, se)
		return errors.New(fmt.Sprintf("Authentication failed: %s", f.Reason.Local))
	}

	return nil
}

type saslAuth struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl auth"`
	Mechanism string `xml:"mechanism,attr"`
	Message string `xml:",chardata"`
}

func bindResource(stream *Stream, jid JID) (JID, error) {

	req := Iq{Id: "foo", Type: "set"}
	if jid.Resource == "" {
		req.PayloadEncode(bindIq{})
	} else {
		req.PayloadEncode(bindIq{Resource: jid.Resource})
	}
	if err := stream.Send(req); err != nil {
		return JID{}, err
	}

	resp := Iq{}
	err := stream.Decode(&resp)
	if err != nil {
		return JID{}, err
	}
	bindResp := bindIq{}
	resp.PayloadDecode(&bindResp)

	boundJID, err := ParseJID(bindResp.JID)
	return boundJID, nil
}

type bindIq struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"`
	Resource string `xml:"resource,omitempty"`
	JID string `xml:"jid,omitempty"`
}

func stringSliceContains(l []string, m string) bool {
	for _, i := range l {
		if i == m {
			return true
		}
	}
	return false
}

type features struct {
	XMLName xml.Name `xml:"http://etherx.jabber.org/streams features"`
	StartTLS *tlsStartTLS `xml:"starttls"`
	Mechanisms *mechanisms `xml:"mechanisms"`
	Bind *bind `xml:"bind"`
}

type bind struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"`
	Required *required `xml:"required"`
}

type mechanisms struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl mechanisms"`
	Mechanisms []string `xml:"mechanism"`
}

type tlsStartTLS struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls starttls"`
	Required *required `xml:"required"`
}

type required struct {}

type saslFailure struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl failure"`
	Reason xml.Name `xml:",any"`
}

// BUG(matt): Don't use "foo" as the <iq/> id during resource binding.
<commit_msg>Make authentication a little more pluggable.<commit_after>package xmpp

import (
	"crypto/tls"
	"encoding/xml"
	"errors"
	"fmt"
	"log"
)

// Config structure used to create a new XMPP client connection.
type ClientConfig struct {
	// Don't upgrade the connection to TLS, even if the server supports it. If
	// the server *requires* TLS then this option is ignored.
	NoTLS bool

	// Skip verification of the server's certificate chain. Probably only
	// useful during development.
	InsecureSkipVerify bool
}

// Create a client XMPP over the stream.
func NewClientXMPP(stream *Stream, jid JID, password string, config *ClientConfig) (*XMPP, error) {

	if config == nil {
		config = &ClientConfig{}
	}

	for {

		if err := startClient(stream, jid); err != nil {
			return nil, err
		}

		// Read features.
		f := new(features)
		if err := stream.Decode(f); err != nil {
			return nil, err
		}

		// TLS?
		if f.StartTLS != nil && (f.StartTLS.Required != nil || !config.NoTLS) {
			log.Println("Start TLS")
			if err := startTLS(stream, config); err != nil {
				return nil, err
			}
			continue // Restart
		}

		// Authentication
		if f.Mechanisms != nil {
			log.Println("Authenticating")
			if err := authenticate(stream, f.Mechanisms.Mechanisms, jid.Node, password); err != nil {
				return nil, err
			}
			continue // Restart
		}

		// Bind resource.
		if f.Bind != nil {
			log.Println("Binding resource.")
			boundJID, err := bindResource(stream, jid)
			if err != nil {
				return nil, err
			}
			jid = boundJID
		}

		break
	}

	return newXMPP(jid, stream), nil
}

func startClient(stream *Stream, jid JID) error {

	start := xml.StartElement{
		xml.Name{"stream", "stream"},
		[]xml.Attr{
			xml.Attr{xml.Name{"", "xmlns"}, "jabber:client"},
			xml.Attr{xml.Name{"xmlns", "stream"}, "http://etherx.jabber.org/streams"},
			xml.Attr{xml.Name{"", "from"}, jid.Full()},
			xml.Attr{xml.Name{"", "to"}, jid.Domain},
			xml.Attr{xml.Name{"", "version"}, "1.0"},
		},
	}

	if err := stream.SendStart(&start); err != nil {
		return err
	}

	if _, err := stream.Next(&xml.Name{nsStream, "stream"}); err != nil {
		return err
	}

	return nil
}

func startTLS(stream *Stream, config *ClientConfig) error {

	if err := stream.Send(&tlsStart{}); err != nil {
		return err
	}

	p := tlsProceed{}
	if err := stream.Decode(&p); err != nil {
		return err
	}

	tlsConfig := tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}
	return stream.UpgradeTLS(&tlsConfig)
}

type tlsStart struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls starttls"`
}

type tlsProceed struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls proceed"`
}

func authenticate(stream *Stream, mechanisms []string, user, password string) error {
	for _, handler := range authHandlers {
		if !stringSliceContains(mechanisms, handler.Mechanism) {
			continue
		}
		if err := handler.Fn(stream, user, password); err == nil {
			log.Printf("Authentication (%s) successful", handler.Mechanism)
			return nil
		}
	}
	return errors.New("No supported SASL mechanism found.")
}

type authHandler struct {
	Mechanism string
	Fn func(*Stream, string, string) error
}

var authHandlers = []authHandler{
		authHandler{"PLAIN", authenticatePlain},
	}

func authenticatePlain(stream *Stream, user, password string) error {

	auth := saslAuth{Mechanism: "PLAIN", Message: saslEncodePlain(user, password)}
	if err := stream.Send(&auth); err != nil {
		return err
	}

	se, err := stream.Next(nil)
	if err != nil {
		return err
	}
	switch se.Name.Local {
	case "success":
		if err := stream.Skip(); err != nil {
			return err
		}
	case "failure":
		f := new(saslFailure)
		stream.DecodeElement(f, se)
		return errors.New(fmt.Sprintf("Authentication failed: %s", f.Reason.Local))
	}

	return nil
}

type saslAuth struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl auth"`
	Mechanism string `xml:"mechanism,attr"`
	Message string `xml:",chardata"`
}

func bindResource(stream *Stream, jid JID) (JID, error) {

	req := Iq{Id: "foo", Type: "set"}
	if jid.Resource == "" {
		req.PayloadEncode(bindIq{})
	} else {
		req.PayloadEncode(bindIq{Resource: jid.Resource})
	}
	if err := stream.Send(req); err != nil {
		return JID{}, err
	}

	resp := Iq{}
	err := stream.Decode(&resp)
	if err != nil {
		return JID{}, err
	}
	bindResp := bindIq{}
	resp.PayloadDecode(&bindResp)

	boundJID, err := ParseJID(bindResp.JID)
	return boundJID, nil
}

type bindIq struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"`
	Resource string `xml:"resource,omitempty"`
	JID string `xml:"jid,omitempty"`
}

func stringSliceContains(l []string, m string) bool {
	for _, i := range l {
		if i == m {
			return true
		}
	}
	return false
}

type features struct {
	XMLName xml.Name `xml:"http://etherx.jabber.org/streams features"`
	StartTLS *tlsStartTLS `xml:"starttls"`
	Mechanisms *mechanisms `xml:"mechanisms"`
	Bind *bind `xml:"bind"`
}

type bind struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"`
	Required *required `xml:"required"`
}

type mechanisms struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl mechanisms"`
	Mechanisms []string `xml:"mechanism"`
}

type tlsStartTLS struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-tls starttls"`
	Required *required `xml:"required"`
}

type required struct {}

type saslFailure struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-sasl failure"`
	Reason xml.Name `xml:",any"`
}

// BUG(matt): Don't use "foo" as the <iq/> id during resource binding.
<|endoftext|>


<commit_before>// Copyright 2016 ego authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package storage

import (
	"fmt"
	"os"
)

const (
	// DefaultStorage default storage engine
	DefaultStorage = "ldb"

	// DefaultStorage = "bad"

	// DefaultStorage = "bolt"
)

var supportedStorage = map[string]func(path string) (Storage, error){
	"ldb":  OpenLeveldb,
	"bg":   OpenBadger, // bad to bg
	"bolt": OpenBolt,
	// "kv":   OpenKV,
	// "ledisdb"
}

// RegisterStorage register Storage engine
func RegisterStorage(name string, fn func(path string) (Storage, error)) {
	supportedStorage[name] = fn
}

// Storage is storage interface
type Storage interface {
	Set(k, v []byte) error
	Get(k []byte) ([]byte, error)
	Delete(k []byte) error
	Has(k []byte) (bool, error)
	ForEach(fn func(k, v []byte) error) error
	Close() error
	WALName() string
}

// OpenStorage open Storage engine
func OpenStorage(path string, args ...string) (Storage, error) {
	wse := DefaultStorage

	if len(args) > 0 {
		if args[0] != "" {
			wse = args[0]
		}
	} else {
		wseEnv := os.Getenv("RIOT_STORAGE_ENGINE")
		if wseEnv != "" {
			wse = wseEnv
		}
	}

	if fn, has := supportedStorage[wse]; has {
		return fn(path)
	}
	return nil, fmt.Errorf("unsupported storage engine %v", wse)
}
<commit_msg>update store code, OpenStorage and name<commit_after>// Copyright 2016 ego authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package storage

import (
	"fmt"
	"os"
)

const (
	// DefaultStorage default storage engine
	DefaultStorage = "ldb"
	// DefaultStorage = "bad"
	// DefaultStorage = "bolt"
)

var supportedStorage = map[string]func(path string) (Storage, error){
	"ldb":  OpenLeveldb,
	"bg":   OpenBadger, // bad to bg
	"bolt": OpenBolt,
	// "kv":   OpenKV,
	// "ledisdb": Open,
}

// RegisterStorage register Storage engine
func RegisterStorage(name string, fn func(path string) (Storage, error)) {
	supportedStorage[name] = fn
}

// Storage is storage interface
type Storage interface {
	Set(k, v []byte) error
	Get(k []byte) ([]byte, error)
	Delete(k []byte) error
	Has(k []byte) (bool, error)
	ForEach(fn func(k, v []byte) error) error
	Close() error
	WALName() string
}

// OpenStorage open Storage engine
func OpenStorage(path string, args ...string) (Storage, error) {
	storeName := DefaultStorage

	if len(args) > 0 && args[0] != "" {
		storeName = args[0]
	} else {
		storeEnv := os.Getenv("RIOT_STORAGE_ENGINE")
		if storeEnv != "" {
			storeName = storeEnv
		}
	}

	if fn, has := supportedStorage[storeName]; has {
		return fn(path)
	}

	return nil, fmt.Errorf("unsupported storage engine: %v", storeName)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"net/url"
	"strconv"
)

const (
	ASC  = 1
	DESC = -1
)

type Item interface {
	OrderValue(key string) string
}

type Interface interface {
	Equal(order string, i, j int) bool
	Value(order string, i int) string
	Len() int
}

type Page struct {
	items []Item
}

func (p *Page) Equal(order string, i, j int) bool {
	return p.Value(order, i) == p.Value(order, j)
}

func (p *Page) Value(order string, i int) string {
	return p.items[i].OrderValue(order)
}

func (p *Page) Len() int {
	return len(p.items)
}

type Config struct {
	count     int
	order     string
	direction int
}

type Cursor struct {
	Value     string
	Offset    int
	Count     int
	Order     string
	Direction int
}

func (c Cursor) DirectionString() string {
	if c.Direction == ASC {
		return "asc"
	} else {
		return "desc"
	}
}

func NewCursorFromQuery(query string) (Cursor, error) {
	c := Cursor{}
	m, err := url.ParseQuery(query)
	if err != nil {
		return c, err
	}

	if v, ok := m["value"]; ok {
		c.Value = v[0]
	}
	if v, ok := m["offset"]; ok {
		offset, err := strconv.Atoi(v[0])
		if err != nil {
			return c, err
		}
		c.Offset = offset
	}
	if v, ok := m["count"]; ok {
		count, err := strconv.Atoi(v[0])
		if err != nil {
			return c, err
		}
		c.Count = count
	}
	if v, ok := m["order"]; ok {
		c.Order = v[0]
	}
	if v, ok := m["direction"]; ok {
		switch {
		case v[0] == "desc":
			c.Direction = DESC
		case v[0] == "asc":
			c.Direction = ASC
		default:
			return c, fmt.Errorf("'%s' in not a supported direction, use asc or desc", v)
		}
	}
	return c, nil
}

type Pagination struct {
	Cursor
	config Config
}

func (p *Pagination) max(items Interface) int {
	if items.Len() <= p.Count {
		return items.Len() - 1
	} else {
		return p.Count
	}
}

func (p *Pagination) equalCount(items Interface, order string, max int) int {
	c := 0
	for i := 0; i < p.Count; i++ {
		if items.Equal(order, i, max) {
			c += 1
		}
	}
	return c
}

func NewPagination(cursor Cursor, config Config) *Pagination {
	if cursor.Count == 0 {
		cursor.Count = config.count
	}
	if cursor.Order == "" {
		cursor.Order = config.order
	}
	if cursor.Direction == 0 {
		cursor.Direction = config.direction
	}
	return &Pagination{cursor, config}
}

func (p *Pagination) after(items Interface, last, direction int) *Pagination {
	if items.Len() == 0 {
		return nil
	}
	value := items.Value(p.Order, last)
	offset := p.equalCount(items, p.Order, last)
	if offset == p.Count && value == p.Value {
		offset += p.Offset
	}
	cursor := Cursor{value, offset, p.Count, p.Order, direction}
	return &Pagination{cursor, p.config}
}

func (p *Pagination) prev(items Interface) *Pagination {
	min := 0
	return p.after(items, min, p.Direction*-1)
}

func (p *Pagination) next(items Interface, next_page_prefetched bool) *Pagination {
	if next_page_prefetched && items.Len() <= p.Count {
		return nil
	}
	max := p.max(items)
	return p.after(items, max, p.Direction)
}

func (p *Pagination) addToUrl(u *url.URL) (*url.URL, error) {
	query, err := url.ParseQuery(u.RawQuery)
	if err != nil {
		return nil, err
	}
	query.Set("value", p.Value)
	query.Set("offset", strconv.Itoa(p.Offset))
	query.Set("count", strconv.Itoa(p.Count))
	query.Set("order", p.Order)
	query.Set("direction", p.DirectionString())
	u.RawQuery = query.Encode()
	return u, nil
}

type Comment struct {
	text       string
	created_at int
	updated_at int
}

func (c *Comment) OrderValue(order string) string {
	switch {
	case order == "created_at":
		return strconv.Itoa(c.created_at)
	case order == "updated_at":
		return strconv.Itoa(c.updated_at)
	default:
		return ""
	}
}

func main() {
	items := &Page{[]Item{
		&Comment{"e", 3, 5},
		&Comment{"d", 3, 5},
		&Comment{"c", 2, 5},
		&Comment{"b", 1, 4},
		&Comment{"a", 0, 4},
	}}

	cursor := Cursor{Order: "created_at"}
	config := Config{count: 2, order: "updated_at", direction: DESC}
	pagination := NewPagination(cursor, config)
	next := pagination.next(items, true)
	prev := pagination.prev(items)

	fmt.Printf("next value: %i, offset: %i, direction: %i\n", next.Value, next.Offset, next.Direction)
	fmt.Printf("prev value: %i, offset: %i, direction: %i\n", prev.Value, prev.Offset, prev.Direction)

	u, _ := url.Parse("http://kajic.com?order=updated_at&direction=desc&value=5&offset=0&count=4")
	cursor, _ = NewCursorFromQuery(u.RawQuery)
	pagination = NewPagination(cursor, config)
	next = pagination.next(items, true)
	prev = pagination.prev(items)

	u, _ = next.addToUrl(u)
	fmt.Println(u)
	u, _ = prev.addToUrl(u)
	fmt.Println(u)
}
<commit_msg>Rename addToUrl to toUrl<commit_after>package main

import (
	"fmt"
	"net/url"
	"strconv"
)

const (
	ASC  = 1
	DESC = -1
)

type Item interface {
	OrderValue(key string) string
}

type Interface interface {
	Equal(order string, i, j int) bool
	Value(order string, i int) string
	Len() int
}

type Page struct {
	items []Item
}

func (p *Page) Equal(order string, i, j int) bool {
	return p.Value(order, i) == p.Value(order, j)
}

func (p *Page) Value(order string, i int) string {
	return p.items[i].OrderValue(order)
}

func (p *Page) Len() int {
	return len(p.items)
}

type Config struct {
	count     int
	order     string
	direction int
}

type Cursor struct {
	Value     string
	Offset    int
	Count     int
	Order     string
	Direction int
}

func (c Cursor) DirectionString() string {
	if c.Direction == ASC {
		return "asc"
	} else {
		return "desc"
	}
}

func NewCursorFromQuery(query string) (Cursor, error) {
	c := Cursor{}
	m, err := url.ParseQuery(query)
	if err != nil {
		return c, err
	}

	if v, ok := m["value"]; ok {
		c.Value = v[0]
	}
	if v, ok := m["offset"]; ok {
		offset, err := strconv.Atoi(v[0])
		if err != nil {
			return c, err
		}
		c.Offset = offset
	}
	if v, ok := m["count"]; ok {
		count, err := strconv.Atoi(v[0])
		if err != nil {
			return c, err
		}
		c.Count = count
	}
	if v, ok := m["order"]; ok {
		c.Order = v[0]
	}
	if v, ok := m["direction"]; ok {
		switch {
		case v[0] == "desc":
			c.Direction = DESC
		case v[0] == "asc":
			c.Direction = ASC
		default:
			return c, fmt.Errorf("'%s' in not a supported direction, use asc or desc", v)
		}
	}
	return c, nil
}

type Pagination struct {
	Cursor
	config Config
}

func (p *Pagination) max(items Interface) int {
	if items.Len() <= p.Count {
		return items.Len() - 1
	} else {
		return p.Count
	}
}

func (p *Pagination) equalCount(items Interface, order string, max int) int {
	c := 0
	for i := 0; i < p.Count; i++ {
		if items.Equal(order, i, max) {
			c += 1
		}
	}
	return c
}

func NewPagination(cursor Cursor, config Config) *Pagination {
	if cursor.Count == 0 {
		cursor.Count = config.count
	}
	if cursor.Order == "" {
		cursor.Order = config.order
	}
	if cursor.Direction == 0 {
		cursor.Direction = config.direction
	}
	return &Pagination{cursor, config}
}

func (p *Pagination) after(items Interface, last, direction int) *Pagination {
	if items.Len() == 0 {
		return nil
	}
	value := items.Value(p.Order, last)
	offset := p.equalCount(items, p.Order, last)
	if offset == p.Count && value == p.Value {
		offset += p.Offset
	}
	cursor := Cursor{value, offset, p.Count, p.Order, direction}
	return &Pagination{cursor, p.config}
}

func (p *Pagination) prev(items Interface) *Pagination {
	min := 0
	return p.after(items, min, p.Direction*-1)
}

func (p *Pagination) next(items Interface, next_page_prefetched bool) *Pagination {
	if next_page_prefetched && items.Len() <= p.Count {
		return nil
	}
	max := p.max(items)
	return p.after(items, max, p.Direction)
}

func (p *Pagination) toUrl(baseurl *url.URL) (*url.URL, error) {
	query, err := url.ParseQuery(baseurl.RawQuery)
	if err != nil {
		return nil, err
	}
	query.Set("value", p.Value)
	query.Set("offset", strconv.Itoa(p.Offset))
	query.Set("count", strconv.Itoa(p.Count))
	query.Set("order", p.Order)
	query.Set("direction", p.DirectionString())
	newurl, err := url.Parse(baseurl.String())
	if err != nil {
		return nil, err
	}
	newurl.RawQuery = query.Encode()
	return newurl, nil
}

type Comment struct {
	text       string
	created_at int
	updated_at int
}

func (c *Comment) OrderValue(order string) string {
	switch {
	case order == "created_at":
		return strconv.Itoa(c.created_at)
	case order == "updated_at":
		return strconv.Itoa(c.updated_at)
	default:
		return ""
	}
}

func main() {
	items := &Page{[]Item{
		&Comment{"e", 3, 5},
		&Comment{"d", 3, 5},
		&Comment{"c", 2, 5},
		&Comment{"b", 1, 4},
		&Comment{"a", 0, 4},
	}}

	cursor := Cursor{Order: "created_at"}
	config := Config{count: 2, order: "updated_at", direction: DESC}
	pagination := NewPagination(cursor, config)
	next := pagination.next(items, true)
	prev := pagination.prev(items)

	fmt.Printf("next value: %i, offset: %i, direction: %i\n", next.Value, next.Offset, next.Direction)
	fmt.Printf("prev value: %i, offset: %i, direction: %i\n", prev.Value, prev.Offset, prev.Direction)

	u, _ := url.Parse("http://kajic.com?order=updated_at&direction=desc&value=5&offset=0&count=4")
	cursor, _ = NewCursorFromQuery(u.RawQuery)
	pagination = NewPagination(cursor, config)
	next = pagination.next(items, true)
	prev = pagination.prev(items)

	nexturl, _ := next.toUrl(u)
	prevurl, _ := prev.toUrl(u)
	fmt.Println("nexturl", nexturl)
	fmt.Println("prevurl", prevurl)
	fmt.Println("origurl", u)
}
<|endoftext|>


<commit_before>package middlewares

import (
	"encoding/base64"
	"github.com/vivowares/eywa/Godeps/_workspace/src/github.com/elithrar/simple-scrypt"
	"github.com/vivowares/eywa/Godeps/_workspace/src/github.com/zenazn/goji/web"
	. "github.com/vivowares/eywa/configs"
	. "github.com/vivowares/eywa/models"
	. "github.com/vivowares/eywa/utils"
	"net/http"
)

var PublicPaths = []string{"/login", "/heartbeat", "/", ""}

func Authenticator(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if StringSliceContains(PublicPaths, r.URL.Path) {
			h.ServeHTTP(w, r)
		} else {
			if len(r.Header.Get("Authentication")) != 0 {
				tokenStr := r.Header.Get("Authentication")
				auth, err := DecryptAuthToken(tokenStr)
				if err != nil {
					Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": err.Error()})
				} else {
					if auth.Username == Config().Security.Dashboard.Username {
						if asBytes, err := base64.URLEncoding.DecodeString(auth.TokenString); err != nil {
							Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": err.Error()})
						} else {
							if scrypt.CompareHashAndPassword(asBytes, []byte(Config().Security.Dashboard.Password)) != nil {
								Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid username or password"})
							} else {
								c.Env["auth_token"] = auth
								h.ServeHTTP(w, r)
							}
						}
					} else {
						Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid username or password"})
					}
				}
			} else {
				Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": "empty Authentication header"})
			}
		}
	}

	return http.HandlerFunc(fn)
}
<commit_msg>by pass Auth for OPTIONS method<commit_after>package middlewares

import (
	"encoding/base64"
	"github.com/vivowares/eywa/Godeps/_workspace/src/github.com/elithrar/simple-scrypt"
	"github.com/vivowares/eywa/Godeps/_workspace/src/github.com/zenazn/goji/web"
	. "github.com/vivowares/eywa/configs"
	. "github.com/vivowares/eywa/models"
	. "github.com/vivowares/eywa/utils"
	"net/http"
)

var PublicPaths = []string{"/login", "/heartbeat", "/", ""}

func Authenticator(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if StringSliceContains(PublicPaths, r.URL.Path) || r.Method == "OPTIONS" {
			h.ServeHTTP(w, r)
		} else {
			if len(r.Header.Get("Authentication")) != 0 {
				tokenStr := r.Header.Get("Authentication")
				auth, err := DecryptAuthToken(tokenStr)
				if err != nil {
					Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": err.Error()})
				} else {
					if auth.Username == Config().Security.Dashboard.Username {
						if asBytes, err := base64.URLEncoding.DecodeString(auth.TokenString); err != nil {
							Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": err.Error()})
						} else {
							if scrypt.CompareHashAndPassword(asBytes, []byte(Config().Security.Dashboard.Password)) != nil {
								Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid username or password"})
							} else {
								c.Env["auth_token"] = auth
								h.ServeHTTP(w, r)
							}
						}
					} else {
						Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid username or password"})
					}
				}
			} else {
				Render.JSON(w, http.StatusUnauthorized, map[string]string{"error": "empty Authentication header"})
			}
		}
	}

	return http.HandlerFunc(fn)
}
<|endoftext|>