func WritePacket(logger *log.Logger, conn *tls.Conn, p *Packet) error { jsbuf, err := json.Marshal(&p) if err != nil { return err } plen := len(jsbuf) pilen := uint32(plen) outlen := new(bytes.Buffer) binary.Write(outlen, binary.BigEndian, &pilen) jsbuf = append(outlen.Bytes(), jsbuf...) bw := 0 for { if bw >= (plen + 4) { break } w, err := conn.Write(jsbuf) if err != nil { return err } bw = bw + w } return nil }
func clientFunc(conn *tls.Conn) error { defer conn.Close() if !conn.ConnectionState().HandshakeComplete { return errors.New("handshake didn't complete") } input := []byte("Hello World!") if _, err := conn.Write(input); err != nil { return err } output, err := ioutil.ReadAll(conn) if err != nil { return err } if bytes.Compare(input, output) != 0 { return errors.New("input and output do not match") } return nil }
func (c *IFMapClient) request(conn *tls.Conn, action, data string) error { var requestBuffer bytes.Buffer requestBuffer.WriteString("POST / HTTP/1.1 \r\n") requestBuffer.WriteString("Host: ") requestBuffer.WriteString(c.url) requestBuffer.WriteString("\r\n") base64Auth := base64.StdEncoding.EncodeToString([]byte(c.username + ":" + c.password)) requestBuffer.WriteString("Authorization: Basic ") requestBuffer.WriteString(base64Auth) requestBuffer.WriteString("\r\n") requestBuffer.WriteString("User-Agent: goifmap \r\n") requestBuffer.WriteString("Accept: */* \r\n") requestBuffer.WriteString("SOAPAction: ") requestBuffer.WriteString(action) requestBuffer.WriteString("\r\n") requestBuffer.WriteString(fmt.Sprintf("Content-Length: %d\r\n", len(data))) requestBuffer.WriteString("Content-type: text/xml;\r\n") requestBuffer.WriteString("\r\n") requestBuffer.WriteString(data) // fmt.Println("Sending request...") // fmt.Println(requestBuffer.String()) conn.Write(requestBuffer.Bytes()) return nil }
func Publishv1(input chan []*FileEvent, registrar chan []*FileEvent, config *NetworkConfig) { var buffer bytes.Buffer var socket *tls.Conn var sequence uint32 var err error socket = connect(config) defer socket.Close() for events := range input { buffer.Truncate(0) compressor, _ := zlib.NewWriterLevel(&buffer, 3) for _, event := range events { sequence += 1 writeDataFrame(event, sequence, compressor) } compressor.Flush() compressor.Close() compressed_payload := buffer.Bytes() // Send buffer until we're successful... oops := func(err error) { // TODO(sissel): Track how frequently we timeout and reconnect. If we're // timing out too frequently, there's really no point in timing out since // basically everything is slow or down. We'll want to ratchet up the // timeout value slowly until things improve, then ratchet it down once // things seem healthy. log.Printf("Socket error, will reconnect: %s\n", err) time.Sleep(1 * time.Second) socket.Close() socket = connect(config) } SendPayload: for { // Abort if our whole request takes longer than the configured // network timeout. socket.SetDeadline(time.Now().Add(config.timeout)) // Set the window size to the length of this payload in events. _, err = socket.Write([]byte("1W")) if err != nil { oops(err) continue } binary.Write(socket, binary.BigEndian, uint32(len(events))) if err != nil { oops(err) continue } // Write compressed frame socket.Write([]byte("1C")) if err != nil { oops(err) continue } binary.Write(socket, binary.BigEndian, uint32(len(compressed_payload))) if err != nil { oops(err) continue } _, err = socket.Write(compressed_payload) if err != nil { oops(err) continue } // read ack response := make([]byte, 0, 6) ackbytes := 0 for ackbytes != 6 { n, err := socket.Read(response[len(response):cap(response)]) if err != nil { log.Printf("Read error looking for ack: %s\n", err) socket.Close() socket = connect(config) continue SendPayload // retry sending on new connection } else { ackbytes += n } } // TODO(sissel): verify ack // Success, stop trying to send the payload. break } // Tell the registrar that we've successfully sent these events registrar <- events } /* for each event payload */ } // Publish
func (t *Transport) newClientConn(host, key string, tconn *tls.Conn) (*clientConn, error) { if err := tconn.Handshake(); err != nil { return nil, err } if !t.InsecureTLSDial { if err := tconn.VerifyHostname(host); err != nil { return nil, err } } state := tconn.ConnectionState() if p := state.NegotiatedProtocol; p != NextProtoTLS { return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS) } if !state.NegotiatedProtocolIsMutual { return nil, errors.New("http2: could not negotiate protocol mutually") } if _, err := tconn.Write(clientPreface); err != nil { return nil, err } cc := &clientConn{ t: t, tconn: tconn, connKey: []string{key}, // TODO: cert's validated hostnames too tlsState: &state, readerDone: make(chan struct{}), nextStreamID: 1, maxFrameSize: 16 << 10, // spec default initialWindowSize: 65535, // spec default maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough. streams: make(map[uint32]*clientStream), } cc.bw = bufio.NewWriter(stickyErrWriter{tconn, &cc.werr}) cc.br = bufio.NewReader(tconn) cc.fr = NewFramer(cc.bw, cc.br) cc.henc = hpack.NewEncoder(&cc.hbuf) cc.fr.WriteSettings() // TODO: re-send more conn-level flow control tokens when server uses all these. cc.fr.WriteWindowUpdate(0, 1<<30) // um, 0x7fffffff doesn't work to Google? it hangs? cc.bw.Flush() if cc.werr != nil { return nil, cc.werr } // Read the obligatory SETTINGS frame f, err := cc.fr.ReadFrame() if err != nil { return nil, err } sf, ok := f.(*SettingsFrame) if !ok { return nil, fmt.Errorf("expected settings frame, got: %T", f) } cc.fr.WriteSettingsAck() cc.bw.Flush() sf.ForeachSetting(func(s Setting) error { switch s.ID { case SettingMaxFrameSize: cc.maxFrameSize = s.Val case SettingMaxConcurrentStreams: cc.maxConcurrentStreams = s.Val case SettingInitialWindowSize: cc.initialWindowSize = s.Val default: // TODO(bradfitz): handle more t.vlogf("Unhandled Setting: %v", s) } return nil }) // TODO: figure out henc size cc.hdec = hpack.NewDecoder(initialHeaderTableSize, cc.onNewHeaderField) go cc.readLoop() return cc, nil }
func pushMessage(conn *tls.Conn, token string, identity int32, payload *Payload) error { if len(token) == 0 { return errors.New("missing token") } if payload == nil || payload.IsEmpty() { return errors.New("not a valid payload") } buf := new(bytes.Buffer) // command var command byte = 1 err := binary.Write(buf, binary.BigEndian, command) if err != nil { return err } // identifier err = binary.Write(buf, binary.BigEndian, identity) if err != nil { return err } // expires var expires int32 = int32(time.Now().AddDate(0, 0, 1).Unix()) err = binary.Write(buf, binary.BigEndian, expires) if err != nil { return err } // token length var tokenLength int16 = 32 err = binary.Write(buf, binary.BigEndian, tokenLength) if err != nil { return err } // token content tokenBytes, err := hex.DecodeString(token) if len(tokenBytes) != int(tokenLength) { return errors.New("invalid token!") } err = binary.Write(buf, binary.BigEndian, tokenBytes) if err != nil { return err } // payload length payloadBytes, err := payload.Json() if err != nil { return err } fmt.Printf("payload %s\n", string(payloadBytes)) var payloadLength int16 = int16(len(payloadBytes)) err = binary.Write(buf, binary.BigEndian, payloadLength) if err != nil { return err } // payload content err = binary.Write(buf, binary.BigEndian, payloadBytes) if err != nil { return err } // write to socket size, err := conn.Write(buf.Bytes()) fmt.Printf("body: %x\n", buf.Bytes()) log.Printf("write body size %d", size) if err != nil { log.Printf("error when write to socket %s, %d", err, size) return errors.New("socket write error") } return nil }