func dump(args ...string) error { var w io.WriteCloser if len(args) == 0 { w = hex.Dumper(os.Stdout) } else { var err error w, err = os.Create(args[0]) if err != nil { return err } } defer w.Close() d, err := openDevice() if err != nil { return err } defer d.Close() if dumpCount == 0 { dumpCount = eeprom.MaxBytes - dumpStart } data := make([]byte, dumpCount) if err := d.Read(uint16(dumpStart), data); err != nil { d.Reset() return err } _, err = w.Write(data) return err }
func testEncodeChunked(t *testing.T, chunkSize int, testName string, enc *Encoding, decoded, encoded []byte, eol string) { var part []byte encBuf := bytes.NewBuffer(nil) var encoder io.WriteCloser if eol != "" { encoder = NewEncoderWithEOL(eol, enc, encBuf) } else { encoder = NewEncoder(enc, encBuf) } for decoded != nil { if len(decoded) > chunkSize { part = decoded[:chunkSize] decoded = decoded[chunkSize:] } else { part = decoded decoded = nil } _, err := encoder.Write(part) if err != nil { t.Errorf("Test %s: encoder error: %s", testName, err.Error()) return } } testEqual(t, testName, encoded, encBuf.Bytes()) }
func Writer(writer io.WriteCloser, errors chan<- error) chan<- []byte { reader := make(chan []byte) go func() { defer func() { err := writer.Close() if err != nil { errors <- err } }() for block := range reader { if DEBUG { log.Println("TCPWriter got a block", string(block)) } n, err := writer.Write(block) for n < len(block) || err != nil { if err != nil { errors <- err break } n, err = writer.Write(block[n:]) } if DEBUG { log.Println("TCPWriter sent the block", string(block)) } } }() return reader }
// Sends data on stdin for a user event. The stdin simply contains the // payload (if any) of the event. func userEventStdin(logger *log.Logger, stdin io.WriteCloser, e *serf.UserEvent) { defer stdin.Close() if _, err := stdin.Write(e.Payload); err != nil { logger.Printf("[ERR] Error writing user event payload: %s", err) return } }
func (cl *Client) readTransport(w io.WriteCloser) { defer w.Close() p := make([]byte, 1024) for { if cl.socket == nil { cl.waitForSocket() } cl.socket.SetReadDeadline(time.Now().Add(time.Second)) nr, err := cl.socket.Read(p) if nr == 0 { if errno, ok := err.(*net.OpError); ok { if errno.Timeout() { continue } } Warn.Logf("read: %s", err) break } nw, err := w.Write(p[:nr]) if nw < nr { Warn.Logf("read: %s", err) break } } }
// Encrypt the provided bytes for the provided encryption // keys recipients. Returns the encrypted content bytes. func Encrypt(d []byte, encryptionKeys *openpgp.EntityList) ([]byte, error) { var buffer *bytes.Buffer = &bytes.Buffer{} var armoredWriter io.WriteCloser var cipheredWriter io.WriteCloser var err error // Create an openpgp armored cipher writer pointing on our // buffer armoredWriter, err = armor.Encode(buffer, "PGP MESSAGE", nil) if err != nil { return nil, NewPgpError(ERR_ENCRYPTION_ENCODING, fmt.Sprintf("Can't make armor: %v", err)) } // Create an encrypted writer using the provided encryption keys cipheredWriter, err = openpgp.Encrypt(armoredWriter, *encryptionKeys, nil, nil, nil) if err != nil { return nil, NewPgpError(ERR_ENCRYPTION_ENCRYPT, fmt.Sprintf("Error encrypting: %v", err)) } // Write (encrypts on the fly) the provided bytes to // cipheredWriter _, err = cipheredWriter.Write(d) if err != nil { return nil, NewPgpError(ERR_ENCRYPTION_ENCRYPT, fmt.Sprintf("Error copying encrypted content: %v", err)) } cipheredWriter.Close() armoredWriter.Close() return buffer.Bytes(), nil }
func (sw *SMTPWriter) Write(d []byte) (n int, err error) { sw.mu.Lock() if sw.cli == nil { sw.mu.Unlock() return -1, errors.New("client not init") } for _, t := range sw.to { if err = sw.cli.Rcpt(t); err != nil { sw.mu.Unlock() return } } var wc io.WriteCloser if wc, err = sw.cli.Data(); err == nil { body := append(sw.buf[:], d...) n, err = wc.Write(body) wc.Close() sw.mu.Unlock() return } sw.mu.Unlock() return }
func decrypt(block cipher.Block, in io.Reader, size int, out io.WriteCloser) error { var err error var buf []byte var count int var decrypter cipher.BlockMode defer out.Close() buf = make([]byte, block.BlockSize()) if _, err = io.ReadFull(in, buf); err != nil { return err } decrypter = cipher.NewCBCDecrypter(block, buf) count = (size - block.BlockSize()) / block.BlockSize() for count > 0 && err == nil { if _, err = io.ReadFull(in, buf); err == nil { decrypter.CryptBlocks(buf, buf) if count == 1 { for count = block.BlockSize() - 1; buf[count] == 0x00; count-- { continue } if buf[count] == 0x80 { buf = buf[:count] } } _, err = out.Write(buf) } count-- } if err == io.EOF { return nil } return err }
func revc(conn net.Conn, w io.WriteCloser) { defer w.Write([]byte("exit\n\r")) defer conn.Close() var b [100]byte conn.Write([]byte("welcome\n")) var s string for { n, err := conn.Read(b[0:100]) if err != nil { break } //退格删除字符 if b[0] == 8 { s = s[0 : len(s)-1] continue } s += string(b[0:n]) //回车提交 if b[n-1] == 10 { //fmt.Print("接收:", n, s, b[1]) w.Write([]byte(s)) s = "" } } }
/** Attempts to encode the response according to the client's Accept-Encoding header. If there is an error, or if the encoding requests aren't supported then the original content is returned. Encoding type: * deflate (zlib stream) * gzip This should be the last module loaded */ func EncodeResponse(ctx *Context, content interface{}) (interface{}, error) { var compressed bytes.Buffer var output io.WriteCloser if len(ctx.Request.Header["Accept-Encoding"]) > 0 { for _, opt := range ctx.Request.Header["Accept-Encoding"] { if strings.Index(opt, "gzip") >= 0 { output = gzip.NewWriter(&compressed) ctx.SetHeader("Content-Encoding", "gzip", true) } else if strings.Index(opt, "deflate") >= 0 { output = zlib.NewWriter(&compressed) ctx.SetHeader("Content-Encoding", "deflate", true) } } } if output != nil { _, err := output.Write(content.([]byte)) if err != nil { ctx.Server.Logger.Printf("EncodeResponse write failed: %s", err) return content, &WebError{500, err.Error()} } err = output.Close() return compressed.Bytes(), nil } return content, nil }
func writeClose(w io.WriteCloser, buf []byte) error { _, err := w.Write(buf) if err != nil { return err } return w.Close() }
func NewClientLogger(client client.Client, id int64, rc io.ReadCloser, wc io.WriteCloser, limit int64) LoggerFunc { var once sync.Once var size int64 return func(line *build.Line) { // annoying hack to only start streaming once the first line is written once.Do(func() { go func() { err := client.Stream(id, rc) if err != nil && err != io.ErrClosedPipe { logrus.Errorf("Error streaming build logs. %s", err) } }() }) if size > limit { return } linejson, _ := json.Marshal(line) wc.Write(linejson) wc.Write([]byte{'\n'}) size += int64(len(line.Out)) } }
// Send will package and send the email. func (e *ToEmail) Send(msg interface{}) error { // extract the 'to' and 'from' and build the email body from, to, email, err := e.buildEmail(msg) if err != nil { return err } // set the 'from' if err = e.client.Mail(from); err != nil { return err } // set the 'to' if err = e.client.Rcpt(to); err != nil { return err } // get a handle of a writer for the message.. var w io.WriteCloser if w, err = e.client.Data(); err != nil { return err } // ...and send the message body if _, err = w.Write(email); err != nil { return err } if err = w.Close(); err != nil { return err } return nil }
func commandsInput(outPipe io.WriteCloser) { loop: for { cmd := readCommand() if debug { logger.Println("cmd", cmd) } switch cmd.cmd { case CMD_STOP: break loop case CMD_DATA: n, err := outPipe.Write(cmd.data) if err != nil { if debug { logger.Println(err) } fatal_if(err) } l := len(cmd.data) if n != l { fatal_if(fmt.Errorf("forward input: expected to write %d bytes length, got %d", l, n)) } } } if debug { logger.Println("Command input exited.") } }
func executeBuildDir(c *cli.Context, dir, app, manifest, description string, output io.WriteCloser) (string, string, error) { err := warnUnignoredEnv(dir) if err != nil { return "", "", err } dir, err = filepath.Abs(dir) if err != nil { return "", "", err } output.Write([]byte("Creating tarball... ")) tar, err := createTarball(dir) if err != nil { return "", "", err } output.Write([]byte("OK\n")) opts := client.CreateBuildSourceOptions{ Cache: !c.Bool("no-cache"), Config: manifest, Description: description, Progress: progress("Uploading: ", "Starting build... ", output), } build, err := rackClient(c).CreateBuildSource(app, bytes.NewReader(tar), opts) if err != nil { return "", "", err } return finishBuild(c, app, build, output) }
// Send will package and send the email. func (e *ToEmail) send(from, to string, email []byte) error { var err error // set the 'from' if err = e.client.Mail(from); err != nil { return err } // set the 'to' if err = e.client.Rcpt(to); err != nil { return err } // get a handle of a writer for the message.. var w io.WriteCloser if w, err = e.client.Data(); err != nil { return err } // ...and send the message body if _, err = w.Write(email); err != nil { return err } if err = w.Close(); err != nil { return err } return nil }
func PGPKeyRawToArmored(raw []byte, priv bool) (ret string, err error) { var writer io.WriteCloser var out bytes.Buffer var which string if priv { which = "PRIVATE" } else { which = "PUBLIC" } hdr := fmt.Sprintf("PGP %s KEY BLOCK", which) writer, err = armor.Encode(&out, hdr, PGPArmorHeaders) if err != nil { return } if _, err = writer.Write(raw); err != nil { return } writer.Close() ret = out.String() return }
func (s *ExportedStreams) Write(_ context.Context, a keybase1.WriteArg) (n int, err error) { var w io.WriteCloser if w, err = s.GetWriter(a.S); err != nil { return } n, err = w.Write(a.Buf) return }
func v1WriteStatusFunc(stream io.WriteCloser) func(status *apierrors.StatusError) error { return func(status *apierrors.StatusError) error { if status.Status().Status == metav1.StatusSuccess { return nil // send error messages } _, err := stream.Write([]byte(status.Error())) return err } }
func Intercept(out chan<- *Unit, w io.WriteCloser, in <-chan *Unit) { tree := <-in out <- tree close(out) //bs, _ := json.MarshalIndent(tree, "", "\t") w.Write([]byte(PrintUnit(tree))) //w.Write(bs) w.Close() }
// serializeStreamHeader writes an OpenPGP packet header to w where the // length of the packet is unknown. It returns a io.WriteCloser which can be // used to write the contents of the packet. See RFC 4880, section 4.2. func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) { var buf [1]byte buf[0] = 0x80 | 0x40 | byte(ptype) _, err = w.Write(buf[:]) if err != nil { return } out = &partialLengthWriter{w: w} return }
// v4WriteStatusFunc returns a WriteStatusFunc that marshals a given api Status // as json in the error channel. func v4WriteStatusFunc(stream io.WriteCloser) func(status *apierrors.StatusError) error { return func(status *apierrors.StatusError) error { bs, err := json.Marshal(status.Status()) if err != nil { return err } _, err = stream.Write(bs) return err } }
// Compress places the canary byte in a buffer and uses the same buffer to fill // in the compressed information of the given input. The configuration supports // two type of compression: LZW and Gzip. When using Gzip compression format, // if GzipCompressionLevel is not specified, the 'gzip.DefaultCompression' will // be assumed. func Compress(data []byte, config *CompressionConfig) ([]byte, error) { var buf bytes.Buffer var writer io.WriteCloser var err error if config == nil { return nil, fmt.Errorf("config is nil") } // Write the canary into the buffer and create writer to compress the // input data based on the configured type switch config.Type { case CompressionTypeLzw: buf.Write([]byte{CompressionCanaryLzw}) writer = lzw.NewWriter(&buf, lzw.LSB, 8) case CompressionTypeGzip: buf.Write([]byte{CompressionCanaryGzip}) switch { case config.GzipCompressionLevel == gzip.BestCompression, config.GzipCompressionLevel == gzip.BestSpeed, config.GzipCompressionLevel == gzip.DefaultCompression: // These are valid compression levels default: // If compression level is set to NoCompression or to // any invalid value, fallback to Defaultcompression config.GzipCompressionLevel = gzip.DefaultCompression } writer, err = gzip.NewWriterLevel(&buf, config.GzipCompressionLevel) default: return nil, fmt.Errorf("unsupported compression type") } if err != nil { return nil, fmt.Errorf("failed to create a compression writer; err: %v", err) } if writer == nil { return nil, fmt.Errorf("failed to create a compression writer") } // Compress the input and place it in the same buffer containing the // canary byte. if _, err = writer.Write(data); err != nil { return nil, fmt.Errorf("failed to compress input data; err: %v", err) } // Close the io.WriteCloser if err = writer.Close(); err != nil { return nil, err } // Return the compressed bytes with canary byte at the start return buf.Bytes(), nil }
func ExampleNewSignArmor62Stream() { var err error // Make a new Keyring, initialized to be empty keyring := basic.NewKeyring() // The test message msg := []byte("The Magic Words are Squeamish Ossifrage") // Make a secret key for the sender var signer saltpack.SigningSecretKey signer, err = keyring.GenerateSigningKey() if err != nil { return } // Make a new signature stream. We write the input data into // the input stream, and we read output out of the output stream. // In this case, the output stream is just a buffer. var input io.WriteCloser var output bytes.Buffer input, err = saltpack.NewSignArmor62Stream(&output, signer, "") if err != nil { return } // Write the message into the input stream, and then close input.Write(msg) input.Close() // The verified message. We pass the signed stream as the first argument // as a stream (here a bytes.Buffer which is output from above), and read the // verified data out of verified stream. var verifiedStream io.Reader var signingPublicKey saltpack.SigningPublicKey signingPublicKey, verifiedStream, _, err = saltpack.NewDearmor62VerifyStream(&output, keyring) if err != nil { return } // Assert we got the right key back. if saltpack.PublicKeyEqual(signingPublicKey, signer.GetPublicKey()) { fmt.Println("The right key") } // Copy all of the data out of the verified stream, and into standard // output, here for testing / comparison purposes. io.Copy(os.Stdout, verifiedStream) os.Stdout.Write([]byte{'\n'}) // Output: // The right key // The Magic Words are Squeamish Ossifrage }
func verify(cmd *cobra.Command, args []string, output io.WriteCloser) { if len(args) < 2 { cmd.Usage() fatalf("must specify a GUN and target") } // Reads all of the data on STDIN //TODO (diogo): Change this to do a streaming hash payload, err := ioutil.ReadAll(os.Stdin) if err != nil { fatalf("error reading content from STDIN: %v", err) } //TODO (diogo): This code is copy/pasted from lookup. gun := args[0] targetName := args[1] kdb := keys.NewDB() repo := tuf.NewTufRepo(kdb, nil) remote, err := store.NewHTTPStore( "https://notary:4443/v2/"+gun+"/_trust/tuf/", "", "json", "", ) c, err := bootstrapClient(remote, repo, kdb) if err != nil { logrus.Error("Unable to setup client.") return } err = c.Update() if err != nil { fmt.Println("Update failed") fatalf(err.Error()) } meta := c.TargetMeta(targetName) if meta == nil { logrus.Error("notary: data not present in the trusted collection.") os.Exit(1) } // Create hasher and hash data stdinHash := fmt.Sprintf("sha256:%x", sha256.Sum256(payload)) serverHash := fmt.Sprintf("sha256:%s", meta.Hashes["sha256"]) if stdinHash != serverHash { logrus.Error("notary: data not present in the trusted collection.") os.Exit(1) } else { _, _ = output.Write(payload) output.Close() } return }
func (h *handler) Read(filename string, w io.WriteCloser) error { h.mu.Lock() bytes, ok := h.files[filename] h.mu.Unlock() if !ok { return tftp.ErrFileNotFound } defer w.Close() _, err := w.Write(bytes) return err }
func Node1(output io.WriteCloser) { var data = []byte("Hello World") n, err := output.Write(data) if n != len(data) { fmt.Printf("Written %v of %v \n", n, len(data)) } if err != nil { fmt.Printf("Error %v\n", err.Error()) } output.Close() }
// WriteMessage sends the specified message to the GELF server // specified in the call to New(). It assumes all the fields are // filled out appropriately. In general, clients will want to use // Write, rather than WriteMessage. func (w *Writer) WriteMessage(m *Message) (err error) { mBuf := newBuffer() defer bufPool.Put(mBuf) if err = m.MarshalJSONBuf(mBuf); err != nil { return err } mBytes := mBuf.Bytes() var ( zBuf *bytes.Buffer zBytes []byte ) var zw io.WriteCloser switch w.CompressionType { case CompressGzip: zBuf = newBuffer() defer bufPool.Put(zBuf) zw, err = gzip.NewWriterLevel(zBuf, w.CompressionLevel) case CompressZlib: zBuf = newBuffer() defer bufPool.Put(zBuf) zw, err = zlib.NewWriterLevel(zBuf, w.CompressionLevel) case CompressNone: zBytes = mBytes default: panic(fmt.Sprintf("unknown compression type %d", w.CompressionType)) } if zw != nil { if err != nil { return } if _, err = zw.Write(mBytes); err != nil { zw.Close() return } zw.Close() zBytes = zBuf.Bytes() } if numChunks(zBytes) > 1 { return w.writeChunked(zBytes) } n, err := w.conn.Write(zBytes) if err != nil { return } if n != len(zBytes) { return fmt.Errorf("bad write (%d/%d)", n, len(zBytes)) } return nil }
// TODO: func (p *Propolis) DownloadRequest(path string, body io.WriteCloser) (info *os.FileInfo, err os.Error) { var resp *http.Response if resp, err = p.SendRequest("GET", false, "", nil, nil, "", nil); err != nil { return } info = new(os.FileInfo) info.Name = path p.GetResponseMetaData(resp, info) // download and compute MD5 hash as we go md5hash := md5.New() // adapted from io.Copy written := int64(0) buf := make([]byte, 32*1024) for { nr, er := resp.Body.Read(buf) if nr > 0 { md5hash.Write(buf[0:nr]) nw, ew := body.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = io.ErrShortWrite break } } if er == os.EOF { break } if er != nil { err = er break } } body.Close() if err == nil && written != info.Size { err = io.ErrUnexpectedEOF } // hex-encode the md5 hash md5hex := "\"" + hex.EncodeToString(md5hash.Sum()) + "\"" if md5hex != resp.Header.Get("Etag") { err = os.NewError("md5sum mismatch for " + path) } return }
/* Read from src and write to dest. */ func send_file(src *bufio.Reader, dest io.WriteCloser) { for { rec, rerr := src.ReadBytes('\n') if rerr == nil { if len(rec) > 0 && rec[0] != '#' { // skip empty lines and comment lines dest.Write(rec) } } else { return } } }