| 11 | type DecodeLineFunc func(text string) (*Hop, error) |
| 12 | |
| 13 | func decodeNetworkOutputToFile(command *exec.Cmd, decodeLine DecodeLineFunc) ([]*Hop, string, error) { |
| 14 | stdout, err := command.StdoutPipe() |
| 15 | if err != nil { |
| 16 | return nil, "", fmt.Errorf("error piping traceroute's output: %w", err) |
| 17 | } |
| 18 | |
| 19 | if err := command.Start(); err != nil { |
| 20 | return nil, "", fmt.Errorf("error starting traceroute: %w", err) |
| 21 | } |
| 22 | |
| 23 | // Tee the output to a string to have the raw information |
| 24 | // in case the decode call fails |
| 25 | // This error is handled only after the Wait call below returns |
| 26 | // otherwise the process can become a zombie |
| 27 | buf := bytes.NewBuffer([]byte{}) |
| 28 | tee := io.TeeReader(stdout, buf) |
| 29 | hops, err := Decode(tee, decodeLine) |
| 30 | // regardless of success of the decoding |
| 31 | // consume all output to have available in buf |
| 32 | _, _ = io.ReadAll(tee) |
| 33 | |
| 34 | if werr := command.Wait(); werr != nil { |
| 35 | return nil, "", fmt.Errorf("error finishing traceroute: %w", werr) |
| 36 | } |
| 37 | |
| 38 | if err != nil { |
| 39 | return nil, buf.String(), err |
| 40 | } |
| 41 | |
| 42 | return hops, buf.String(), nil |
| 43 | } |
| 44 | |
| 45 | func Decode(reader io.Reader, decodeLine DecodeLineFunc) ([]*Hop, error) { |
| 46 | scanner := bufio.NewScanner(reader) |