func (client *Conn) proxy(rwc io.ReadWriteCloser) (bool, error) { var closed bool for job := range client.jobs { if closed { job.results <- rillResult{err: ErrClosedConnection{}} continue } switch job.op { case _read: n, err := rwc.Read(job.data) job.results <- rillResult{n, err} if err != nil { rwc.Close() return false, err } case _write: n, err := rwc.Write(job.data) job.results <- rillResult{n, err} if err != nil { rwc.Close() return false, err } case _close: closed = true err := rwc.Close() job.results <- rillResult{err: err} return true, err } } return false, nil }
func fakeServer(t *testing.T, rw io.ReadWriteCloser, fakeReply fakeResponseMap) { b := bufio.NewReader(rw) _, err := rw.Write([]byte(fakeReply[""])) if err != nil { t.Errorf("fakeServer: Banner write causes %s", err) } for { line, err := b.ReadString('\n') if err != nil { if err != io.EOF { t.Errorf("fakeServer: Reading causes %s", err) } break } reply := fakeReply[strings.TrimSpace(line)] if reply == "" { break } _, err = rw.Write([]byte(reply)) if err != nil { t.Errorf("fakeServer: Writing causes %s", err) break } } rw.Close() }
// logs a player in from an incoming connection, creating a player // in the world if they successfully connect func Login(rwc io.ReadWriteCloser, ip net.Addr) { showTitle(rwc) for i := 0; i < retries; i++ { user, err := authenticate(rwc, ip) switch err { case nil: world.SpawnPlayer(rwc, user) return case ErrAuth: log.Printf("Failed login from %s", ip) _, err = rwc.Write([]byte("Incorrect username or password, please try again\n")) if err != nil { break } case ErrDupe: ok, err := handleDupe(user, rwc) if ok && err == nil { kick(user) world.SpawnPlayer(rwc, user) return } case ErrNotSetup: rwc.Close() return } if err != nil { log.Printf("Error during login of user from %s: %s", ip, err) return } } }
// secureConnection creates a secure connection from an insecure connection. It // does this by performing the handshake, then returning an io.ReadWriteCloser // that can be used to communicate securely. func secureConnection(conn io.ReadWriteCloser) (io.ReadWriteCloser, error) { var priv, pub *[32]byte var err error pub, priv, err = box.GenerateKey(rand.Reader) if err != nil { return nil, err } if _, err := conn.Write(pub[:]); err != nil { return nil, err } if _, err := io.ReadFull(conn, pub[:]); err != nil { return nil, err } return struct { io.Reader io.Writer io.Closer }{ NewSecureReader(conn, priv, pub), NewSecureWriter(conn, priv, pub), conn, }, nil }
func (m *CircularMPI) handleMessage(conn io.ReadWriteCloser) { defer conn.Close() buf, err := ioutil.ReadAll(conn) if err != nil { m.logger.Println(err) conn.Write([]byte{'N', 'O'}) return } conn.Write([]byte{'O', 'K'}) go func() { states := make(map[string]Versioner) data := bytes.NewBuffer(buf) st, err := decodeData(data) if err != nil { m.logger.Println(err) } states = st m.logger.Println(m.me, " Received ") m.cleanLocalStreams(states) m.prepareData(states) if len(states) == 0 { m.logger.Println("Nothing to send Going") return } // Ne need to clean local streams for key, v := range states { m.Dummy.Write(key, v) } m.sendData(states) }() }
// New wraps a ReadWriterCloser and uses the underlying reader and writer to // perform a key exchange and then returns a secured connection. func New(conn io.ReadWriteCloser) (*SecureConn, error) { // Generate key pair priv, pub, err := box.GenerateKey(rand.Reader) if err != nil { return nil, err } // Send our public key // This is done in a goroutine so that read/writes can happen concurrently // in the event that the reader and writer are directly connected (for // example via io.Pipe) done := make(chan error) go func() { _, err := conn.Write(pub[:]) done <- err }() // Read their public key key := &[32]byte{} if _, err := io.ReadFull(conn, key[:]); err != nil { return nil, err } if err := <-done; err != nil { return nil, err } // Return a secured connection return &SecureConn{ NewSecureReader(conn, priv, key), NewSecureWriter(conn, priv, key), conn, DefaultStreamingChunkSize, }, nil }
func doLoris(conn io.ReadWriteCloser, victimUri *url.URL, activeConnectionsCh chan<- int, requestHeader []byte) { defer conn.Close() if _, err := conn.Write(requestHeader); err != nil { log.Printf("Cannot write requestHeader=[%v]: [%s]\n", requestHeader, err) return } activeConnectionsCh <- 1 defer func() { activeConnectionsCh <- -1 }() readerStopCh := make(chan int, 1) go nullReader(conn, readerStopCh) for i := 0; i < *contentLength; i++ { select { case <-readerStopCh: return case <-time.After(*sleepInterval): } if _, err := conn.Write(sharedWriteBuf); err != nil { log.Printf("Error when writing %d byte out of %d bytes: [%s]\n", i, *contentLength, err) return } } }
func PipeThenClose(src, dst io.ReadWriteCloser) { defer dst.Close() buf := make([]byte, MaxPacketSize) for { n, err := src.Read(buf) // read may return EOF with n > 0 // should always process n > 0 bytes before handling error if n > 0 { // Note: avoid overwrite err returned by Read. if _, err := dst.Write(buf[0:n]); err != nil { log.Println("write:", err) break } } if err != nil { // Always "use of closed network connection", but no easy way to // identify this specific error. So just leave the error along for now. // More info here: https://code.google.com/p/go/issues/detail?id=4373 /* if bool(Debug) && err != io.EOF { Debug.Println("read:", err) } */ log.Println("read:", err) break } } }
func acceptAndWrite(rwc io.ReadWriteCloser, t *testing.T) { // write buf := []byte(msg) for len(buf) > 0 { n, err := rwc.Write(buf) if err != nil { t.Fatalf("write: %s", err) } buf = buf[n:] } // read buf2 := make([]byte, len(msg)) free := buf2 for len(free) > 0 { n, err := rwc.Read(free) if err != nil { t.Fatalf("write/read: %s", err) } free = free[n:] } if string(buf2) != msg { t.Fatalf("write/read crc fail") } // close if err := rwc.Close(); err != nil { t.Fatalf("write/close: %s", err) } }
func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { var err1, err2 error var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() _, err1 = conn.Write(locEphPub[:]) }() go func() { defer wg.Done() remEphPub = new([32]byte) _, err2 = io.ReadFull(conn, remEphPub[:]) }() wg.Wait() if err1 != nil { return nil, err1 } if err2 != nil { return nil, err2 } return remEphPub, nil }
func (g *GraphiteTcpServer) handleConnection(conn io.ReadWriteCloser) { scanner := bufio.NewScanner(conn) defer conn.Close() // Create a channel for the metrics addChan := make(chan metrics.Metric, 1000) g.backend.AddMetricChan(addChan) defer close(addChan) for scanner.Scan() { // PARSE METRIC LINES //err, m := err, m := parseGraphiteLine(scanner.Text()) if err == nil { // Send parsed metric to the back-end addChan <- m } else { conn.Write([]byte(err.Error())) } } if err := scanner.Err(); err != nil { fmt.Printf("Error while parsing text: %v", err) } }
func main() { var stdout bool var reopen bool var delay int flag.BoolVar(&stdout, "stdout", false, "Write the specified frame to stdout instead of to a tty.") flag.StringVar(&tty, "tty", "/dev/tty.zigbee", "The tty device to use.") flag.IntVar(&delay, "delay", 0, "The number of seconds to delay before re-opening the tty after a reset command.") flag.Parse() args := flag.Args() length := len(args) - 2 if length < 0 || length > 255 { fmt.Printf("usage: cc2530-frame {options} [subSysId] [cmdId] [hex...]\n") flag.PrintDefaults() os.Exit(1) } frame := buildFrame(args) if frame[2] == 0x41 && frame[3] == 0x00 && !stdout { reopen = true } var io io.ReadWriteCloser if stdout { io = os.Stdout } else { io = open(tty) } io.Write(frame) if reopen { io.Close() time.Sleep(time.Second * time.Duration(delay)) io = open(tty) io.Write([]byte{0xef}) io.Close() io = open(tty) } if !stdout { for { responseSubsysId := processResponse(io) if responseSubsysId == (frame[2]|0x20) || responseSubsysId == frame[2] { // we received a response that wasn't for the command we // sent break } } } }
func send(s io.ReadWriteCloser, msg []byte) int { n, err := s.Write(msg) if err != nil { log.Print(err) return 0 } return n }
func SerialWrite(serialObject io.ReadWriteCloser, openClose string) error { // openClose // "OC0": open command // "OC1": close command _, err := serialObject.Write([]byte(openClose)) if err != nil { return err } return nil }
// CallTestSequence to Davis Weather Station // it must return "TEST" func CallTestSequence(connection io.ReadWriteCloser) string { nb, err := connection.Write([]byte("TEST\n")) check(err) buf := make([]byte, 100) nb, err = connection.Read(buf) check(err) log.Infof("%d bytes: %s\n", nb, string(buf)) return string(buf) }
// clientRead sends input from Stdin to c. func clientRead(c io.ReadWriteCloser) { s := bufio.NewScanner(os.Stdin) prompt := "> " fmt.Print(prompt) for s.Scan() { if _, err := c.Write([]byte(s.Text())); err != nil { log.Fatal(err) } } }
func CopyFromTo(r, w io.ReadWriteCloser, buf []byte) { defer CloseConn(r) if buf != nil && len(buf) > 0 { _, err := w.Write(buf) if err != nil { return } } io.Copy(r, w) }
func TransportHandshake(keypair DHKeys, wire io.ReadWriteCloser, verify func([]byte) bool) (io.ReadWriteCloser, error) { eph_keypair := dh_gen_key(2048) done := make(chan bool) go func() { // Send longterm public key _, err := wire.Write(keypair.Public) if err != nil { return } // Send ephemeral public key _, err = wire.Write(eph_keypair.Public) if err != nil { return } done <- true }() // Read longterm public key their_pubkey := make([]byte, 2048/8) _, err := io.ReadFull(wire, their_pubkey) if err != nil { return nil, errors.New(fmt.Sprintf("Couldn't read their longterm key (%s)", err.Error())) } if !verify(their_pubkey) { return nil, ErrMacNoMatch } // Read ephemeral public key their_eph_pubkey := make([]byte, 2048/8) _, err = io.ReadFull(wire, their_eph_pubkey) if err != nil { return nil, errors.New("Couldn't read their shortterm key") } // Generate secret secret1 := dh_gen_secret(keypair.Private, their_pubkey) secret2 := dh_gen_secret(eph_keypair.Private, their_eph_pubkey) secret := append(secret1, secret2...) // Generate r and w secrets by appending THEIR eph pubkey for w, and OUR eph pubkey for r write_secret := append(secret, their_eph_pubkey...) read_secret := append(secret, eph_keypair.Public...) write_key := KeyedHash(write_secret, []byte("KiSS-1.0")) read_key := KeyedHash(read_secret, []byte("KiSS-1.0")) readk := make([]byte, 56) copy(readk[:], read_key) writek := make([]byte, 56) copy(writek[:], write_key) <-done return MessToStream(&kiss_mess_ctx{make_chugger(readk), make_chugger(writek), wire}), nil }
func echoMsg(s io.ReadWriteCloser) error { b2 := make([]byte, 1024) n, err := s.Read(b2) if err != nil { return err } n, err = s.Write(b2[:n]) if err != nil { return err } return nil }
func echo(rwc io.ReadWriteCloser, handler func(string) string) { for { buf := make([]byte, 256) n, err := rwc.Read(buf) if err != nil { log.Println(err) rwc.Close() return } s := strings.TrimRight(string(buf[:n]), "\n") s = handler(s) _, err = rwc.Write([]byte(s)) } }
func SendQueuedMessagesTo(p io.ReadWriteCloser) { for { message := <-messageQueue if buf, err := message.MarshalBinary(); err != nil { messageQueueErr.Printf("Failed marshal message %x %x", err.Error(), message) } else if _, err := p.Write(buf); err != nil { messageQueueErr.Printf("Failed to send message %x %x", err.Error(), message) } else { messageQueueOut.Printf("Completed message send %x", message) } } }
// LLObfsServerHandshake negotiates low-level obfuscation (content hiding but no // volume hiding) on a network connection, acting as the server. The master // secret must be provided. func LLObfsServerHandshake(secret []byte, transport io.ReadWriteCloser) (io.ReadWriteCloser, error) { // Client needs to send proof that they actually have our secret proof := make([]byte, 64) _, err := io.ReadFull(transport, proof) if err != nil { return nil, err } kilog.FineDebug("llobfs: server obtained proof") // We need to verify proof nonce := proof[:32] hash := proof[32:] if subtle.ConstantTimeCompare(natrium.SecureHash(secret, nonce), hash) != 1 { return nil, errors.New("Client did not give the right proof") } // Generate our ephemeral keys our_keys := UDHGenerateKeys() // Send our public key _, err = transport.Write(our_keys.Public) if err != nil { return nil, err } kilog.FineDebug("llobfs: server sent public key") // Read their public key their_public := make([]byte, 1536/8) _, err = io.ReadFull(transport, their_public) if err != nil { return nil, err } kilog.FineDebug("llobfs: server read public key") // Compute shared secret shared_secret := UDHSecret(our_keys.Private, their_public) // Read and write keys read_key := natrium.SecureHash(shared_secret, []byte("llobfs-upstream-key")) write_key := natrium.SecureHash(shared_secret, []byte("llobfs-downstream-key")) // Create struct toret := new(llobfsContext) toret.read_chug, _ = rc4.NewCipher(read_key) toret.write_chug, _ = rc4.NewCipher(write_key) dummy := make([]byte, 1536) toret.read_chug.XORKeyStream(dummy, dummy) toret.write_chug.XORKeyStream(dummy, dummy) toret.underlying = transport return toret, nil }
func (rpc *RPC) Accept(conn io.ReadWriteCloser) (*Peer, error) { peer := NewPeer(rpc, conn) buf := make([]byte, 32) _, err := conn.Read(buf) if err != nil { return nil, err } // TODO: check handshake _, err = conn.Write([]byte(HandshakeAccept)) if err != nil { return nil, err } go peer.route() return peer, nil }
func help(cmd []string, c io.ReadWriteCloser) bool { usage := ` Supported Commands: PS list current running process System <command> <args> WARN:Exec System Command! Rollback <File path> <Postfix> Rollback updated file Start <Process> Start process Restart <Process> WARN:restart process Stop <Process> WARN:stop process Shutdown WARN:Stop whole service Exit exit current connection ` c.Write([]byte(usage)) return true }
// WakeUp davis Station with sending bites sequence func WakeUp(connection io.ReadWriteCloser) bool { nb, err := connection.Write([]byte("\n")) check(err) buf := make([]byte, 10) nb, err = connection.Read(buf) check(err) log.Infof("%d bytes read from USB port on Wake Up connection: %s\n", nb, string(buf)) if nb == 2 { time.Sleep(time.Second * 2) return true } else { return WakeUp(connection) } }
// NewSecureSession creates a new SecureSession around an io.ReadWriteCloser. // NewSecureSession will generate a public & private key, and then send the // private key to the peer. The peer is required to send its key as well. func NewSecureSession(rwc io.ReadWriteCloser, kp *KeyPair) (*SecureSession, error) { ss := &SecureSession{ kp: kp, rwc: rwc, } // Need to perform a handshake. However we only write our key, and don't // wait for theirs. // This is so that we don't block, and give the peer's key time to come // across the wire. if _, err := rwc.Write(kp.PublicKey[:]); err != nil { return nil, err } return ss, nil }
func writeHeader(rwc io.ReadWriteCloser, seq uint64, method string, data []byte) error { var bh bytes.Buffer var rerr error setError(&rerr, binary.Write(&bh, binary.LittleEndian, seq)) setError(&rerr, binary.Write(&bh, binary.LittleEndian, int32(len(method)))) setError(&rerr, binary.Write(&bh, binary.LittleEndian, int32(len(data)))) _, err := bh.Write([]byte(method)) setError(&rerr, err) if rerr != nil { return rerr } _, err = rwc.Write(bh.Bytes()) return err }
func sendJSON(conn io.ReadWriteCloser, json_data []byte, verb_type uint8) string { // send the two header bytes header := []byte{verb_type, uint8(len(json_data))} // len(json_data) MUST < 128 _, err := conn.Write(header) checkErr("Unable to send header:", err) // send the actual json-encoded data _, err = conn.Write(json_data) checkErr("Unable to send data:", err) // wait for a response from the server response := make([]byte, 255) _, err = conn.Read(response) checkErr("Unable to read response:", err) return string(response) }
func writeLCDMatrix(p *packet, s io.ReadWriteCloser) { if debug { fmt.Println("writeLCDMatrix") } s.Write([]byte(p.header)) s.Write([]byte(p.coord)) s.Write([]byte(p.dataR)) s.Write([]byte(p.dataG)) s.Write([]byte(p.terminator)) }
func (ms *MsocksService) on_auth(stream io.ReadWriteCloser) bool { f, err := ReadFrame(stream) if err != nil { log.Error("%s", err) return false } ft, ok := f.(*FrameAuth) if !ok { log.Error("unexpected package type") return false } log.Notice("auth with username: %s, password: %s.", ft.Username, ft.Password) if ms.userpass != nil { password1, ok := ms.userpass[ft.Username] if !ok || (ft.Password != password1) { log.Error("auth failed.") fb := NewFrameResult(ft.Streamid, ERR_AUTH) buf, err := fb.Packed() _, err = stream.Write(buf.Bytes()) if err != nil { log.Error("%s", err) return false } return false } } fb := NewFrameResult(ft.Streamid, ERR_NONE) buf, err := fb.Packed() if err != nil { log.Error("%s", err) return false } _, err = stream.Write(buf.Bytes()) if err != nil { log.Error("%s", err) return false } log.Info("auth passed.") return true }