Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix #165 for REST responses containing escape sequences #167

Merged
merged 2 commits into from
Mar 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions routeros/mikrotik_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"github.com/go-routeros/routeros"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"encoding/hex"
"net/http"
"net/url"
"os"
"strings"
"time"

"github.com/go-routeros/routeros"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

type Client interface {
Expand Down Expand Up @@ -160,3 +162,20 @@ func (u *URL) GetRestURL() string {
}
return u.Path + q
}

// EscapeChars peterGo https://groups.google.com/g/golang-nuts/c/NiQiAahnl5E/m/U60Sm1of-_YJ
func EscapeChars(data []byte) []byte {
var u = []byte(`\u0000`)
//var u = []byte(`U+0000`)
var res = make([]byte, 0, len(data))

for i, ch := range data {
if ch < 0x20 {
res = append(res, u...)
hex.Encode(res[len(res)-2:], data[i:i+1])
continue
}
res = append(res, ch)
}
return res
}
9 changes: 8 additions & 1 deletion routeros/mikrotik_client_rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,14 @@ func (c *RestClient) SendRequest(method crudMethod, url *URL, item MikrotikItem,

if len(body) != 0 && result != nil {
if err = json.Unmarshal(body, &result); err != nil {
return err

if e, ok := err.(*json.SyntaxError); ok {
ColorizedDebug(c.ctx, fmt.Sprintf("json.Unmarshal(response body): syntax error at byte offset %d", e.Offset))

if err = json.Unmarshal(EscapeChars(body), &result); err != nil {
return fmt.Errorf("json.Unmarshal(response body): %v", err)
}
}
}
}
return nil
Expand Down
1 change: 0 additions & 1 deletion routeros/resource_ip_dhcp_server_lease.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ func ResourceDhcpServerLease() *schema.Resource {
},
"host_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The hostname of the device",
},
Expand Down