Skip to content

Commit

Permalink
Use bufio.Scanner in parseEnv()
Browse files Browse the repository at this point in the history
  • Loading branch information
zaf committed Jul 26, 2022
1 parent 89bef15 commit fcd51e5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
4 changes: 4 additions & 0 deletions agi.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ import (
"strings"
)

const (
envMin = 18 // Minimum number of AGI environment args
)

// Session is a struct holding AGI environment vars and the I/O handlers.
type Session struct {
Env map[string]string //AGI environment variables.
Expand Down
25 changes: 10 additions & 15 deletions parsers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,26 @@
package agi

import (
"bufio"
"bytes"
"errors"
"fmt"
"strconv"
"strings"
)

const (
envMin = 18 // Minimum number of AGI environment args
envMax = 150 // Maximum number of AGI environment args
)

// parseEnv reads and stores AGI environment.
func (a *Session) parseEnv() error {
var err error
var line []byte
for i := 0; i <= envMax; i++ {
line, err = a.buf.ReadBytes(10)
if err != nil || len(line) <= len("\r\n") {
break
s := bufio.NewScanner(a.buf)
for s.Scan() {
line = s.Bytes()
if len(line) <= len("\r\n") {
break // end of input
}
// Strip trailing newline
line = line[:len(line)-1]
ind := bytes.IndexByte(line, ':')
// "agi_type" is the shortest length key, "agi_network_script" the longest, anything outside these boundaries is invalid.
if ind < len("agi_type") || ind > len("agi_network_script") || ind == len(line)-1 {
if ind == -1 || ind == len(line)-1 {
err = fmt.Errorf("malformed environment input: %s", string(line))
a.Env = nil
return err
Expand All @@ -42,9 +36,10 @@ func (a *Session) parseEnv() error {
value := string(line[ind:])
a.Env[key] = value
}
if len(a.Env) < envMin {
err = fmt.Errorf("incomplete environment with only %d env vars", len(a.Env))
if err := s.Err(); err != nil {
err = fmt.Errorf("error reading environment input: %s", err)
a.Env = nil
return err
}
return err
}
Expand Down

0 comments on commit fcd51e5

Please sign in to comment.