yangerd: Add wireguard support

This commit is contained in:
Mattias Walström
2026-06-19 11:38:09 +02:00
parent fc2517720b
commit 9d072b60de
122 changed files with 5399 additions and 27149 deletions
+4 -3
View File
@@ -8,16 +8,17 @@ require (
github.com/mdlayher/ethtool v0.4.1
github.com/mdlayher/genetlink v1.3.2
github.com/mdlayher/netlink v1.8.0
github.com/osrg/gobgp/v3 v3.37.0
github.com/vishvananda/netlink v1.3.1
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10
)
require (
github.com/google/go-cmp v0.7.0 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 // indirect
)
+10 -22
View File
@@ -1,10 +1,5 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-test/deep v1.1.0 h1:WOcxcdHcvdgThNXjw0t76K42FXTU7HpNQWHpA2HHNlg=
github.com/go-test/deep v1.1.0/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -17,30 +12,23 @@ github.com/mdlayher/netlink v1.8.0 h1:e7XNIYJKD7hUct3Px04RuIGJbBxy1/c4nX7D5Yyvvl
github.com/mdlayher/netlink v1.8.0/go.mod h1:UhgKXUlDQhzb09DrCl2GuRNEglHmhYoWAHid9HK3594=
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/osrg/gobgp/v3 v3.37.0 h1:+ObuOdvj7G7nxrT0fKFta+EAupdWf/q1WzbXydr8IOY=
github.com/osrg/gobgp/v3 v3.37.0/go.mod h1:kVHVFy1/fyZHJ8P32+ctvPeJogn9qKwa1YCeMRXXrP0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721 h1:RlZweED6sbSArvlE924+mUcZuXKLBHA35U7LN621Bws=
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721/go.mod h1:Ickgr2WtCLZ2MDGd4Gr0geeCH5HybhRJbonOgQpvSxc=
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 h1:/jFs0duh4rdb8uIfPMv78iAJGcPKDeqAFnaLBropIC4=
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA=
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10 h1:3GDAcqdIg1ozBNLgPy4SLT84nfcBjr6rhGtXYtrkWLU=
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10/go.mod h1:T97yPqesLiNrOYxkwmhMI0ZIlJDm+p0PMR8eRVeR5tQ=
+38 -10
View File
@@ -51,13 +51,14 @@ type NLMonitor struct {
// staging holds raw ip-json data used as input to iface.Transform().
// Protected by mu.
mu sync.Mutex
links json.RawMessage // ip -json -s -d link show (includes stats+details)
addrs json.RawMessage // ip -json -d addr show (details only, no stats)
fdb map[string]json.RawMessage
mdb map[string]json.RawMessage
ethernet map[string]json.RawMessage // ifname → ethtool JSON
wifi map[string]json.RawMessage // ifname → wifi JSON
mu sync.Mutex
links json.RawMessage // ip -json -s -d link show (includes stats+details)
addrs json.RawMessage // ip -json -d addr show (details only, no stats)
fdb map[string]json.RawMessage
mdb map[string]json.RawMessage
ethernet map[string]json.RawMessage // ifname → ethtool JSON
wifi map[string]json.RawMessage // ifname → wifi JSON
wireguard map[string]json.RawMessage // ifname → WireGuard peer-status JSON
lastOperStatus map[string]string
}
@@ -79,6 +80,7 @@ func New(linkBatch, addrBatch *ipbatch.IPBatch, brBatch *bridgebatch.BridgeBatch
mdb: make(map[string]json.RawMessage),
ethernet: make(map[string]json.RawMessage),
wifi: make(map[string]json.RawMessage),
wireguard: make(map[string]json.RawMessage),
lastOperStatus: make(map[string]string),
}
}
@@ -112,6 +114,23 @@ func (m *NLMonitor) SetWifiData(ifname string, data json.RawMessage) {
m.rebuild()
}
// SetWireguardData updates the staged WireGuard peer-status data for an
// interface and triggers a full rebuild of the YANG document.
func (m *NLMonitor) SetWireguardData(ifname string, data json.RawMessage) {
m.mu.Lock()
m.wireguard[ifname] = data
m.mu.Unlock()
m.rebuild()
}
// Links returns a copy of the current staged links data.
func (m *NLMonitor) Links() json.RawMessage {
m.mu.Lock()
cp := append(json.RawMessage{}, m.links...)
m.mu.Unlock()
return cp
}
// Run starts the netlink monitor loop and returns on context cancellation,
// channel closure, or subscription errors.
func (m *NLMonitor) Run(ctx context.Context) error {
@@ -339,6 +358,7 @@ func (m *NLMonitor) removeInterface(name string) {
delete(m.mdb, name)
delete(m.ethernet, name)
delete(m.wifi, name)
delete(m.wireguard, name)
delete(m.lastOperStatus, name)
m.mu.Unlock()
@@ -393,20 +413,21 @@ func (m *NLMonitor) rebuild() {
wfi := copyStringMap(m.wifi)
fdb := copyStringMap(m.fdb)
mdb := copyStringMap(m.mdb)
wg := copyStringMap(m.wireguard)
m.mu.Unlock()
var brSTP, ptSTP map[string]json.RawMessage
resolver := stpquery.NewLinksIfIndexResolver(linksCopy)
brSTP, ptSTP = stpquery.Query(linksCopy, resolver)
doc = mergeAugments(doc, eth, wfi, fdb, mdb, brSTP, ptSTP)
doc = mergeAugments(doc, eth, wfi, fdb, mdb, brSTP, ptSTP, wg)
m.tree.Set(treeKey, doc)
}
// mergeAugments adds ethernet, wifi, and bridge data into the
// complete ietf-interfaces document produced by iface.Transform().
func mergeAugments(doc json.RawMessage, ethernet, wifi, fdb, mdb, bridgeSTP, portSTP map[string]json.RawMessage) json.RawMessage {
if len(ethernet) == 0 && len(wifi) == 0 && len(fdb) == 0 && len(mdb) == 0 && len(bridgeSTP) == 0 && len(portSTP) == 0 {
func mergeAugments(doc json.RawMessage, ethernet, wifi, fdb, mdb, bridgeSTP, portSTP, wireguard map[string]json.RawMessage) json.RawMessage {
if len(ethernet) == 0 && len(wifi) == 0 && len(fdb) == 0 && len(mdb) == 0 && len(bridgeSTP) == 0 && len(portSTP) == 0 && len(wireguard) == 0 {
return doc
}
@@ -480,6 +501,13 @@ func mergeAugments(doc json.RawMessage, ethernet, wifi, fdb, mdb, bridgeSTP, por
}
}
if wgData, ok := wireguard[name]; ok {
var wgObj any
if err := json.Unmarshal(wgData, &wgObj); err == nil {
ifaceObj["infix-interfaces:wireguard"] = wgObj
}
}
ifaceArr[i] = ifaceObj
}
+3 -3
View File
@@ -344,7 +344,7 @@ func TestMergeAugments(t *testing.T) {
"br0": json.RawMessage(`[{"mac":"00:11:22:33:44:55"}]`),
}
got := mergeAugments(doc, eth, nil, fdb, nil, nil, nil)
got := mergeAugments(doc, eth, nil, fdb, nil, nil, nil, nil)
var root map[string]any
if err := json.Unmarshal(got, &root); err != nil {
@@ -370,7 +370,7 @@ func TestMergeAugments(t *testing.T) {
func TestMergeAugmentsNoOp(t *testing.T) {
doc := json.RawMessage(`{"interface":[{"name":"lo"}]}`)
got := mergeAugments(doc, nil, nil, nil, nil, nil, nil)
got := mergeAugments(doc, nil, nil, nil, nil, nil, nil, nil)
if string(got) != string(doc) {
t.Fatalf("expected no-op, got %s", string(got))
}
@@ -379,7 +379,7 @@ func TestMergeAugmentsNoOp(t *testing.T) {
func TestMergeAugmentsInvalidDoc(t *testing.T) {
doc := json.RawMessage(`{invalid`)
eth := map[string]json.RawMessage{"eth0": json.RawMessage(`{}`)}
got := mergeAugments(doc, eth, nil, nil, nil, nil, nil)
got := mergeAugments(doc, eth, nil, nil, nil, nil, nil, nil)
if string(got) != string(doc) {
t.Fatalf("expected passthrough on invalid doc, got %s", string(got))
}
+107
View File
@@ -0,0 +1,107 @@
package wgquery
import (
"encoding/json"
"strconv"
"time"
"golang.zx2c4.com/wireguard/wgctrl"
)
func Query(links json.RawMessage) map[string]json.RawMessage {
wgIfaces := findWireguardIfaces(links)
if len(wgIfaces) == 0 {
return nil
}
client, err := wgctrl.New()
if err != nil {
return nil
}
defer client.Close()
result := make(map[string]json.RawMessage)
now := time.Now().UTC()
for _, ifname := range wgIfaces {
dev, err := client.Device(ifname)
if err != nil {
continue
}
if len(dev.Peers) == 0 {
continue
}
var peers []map[string]any
for _, p := range dev.Peers {
peer := map[string]any{
"public-key": p.PublicKey.String(),
"connection-status": connectionStatus(p.LastHandshakeTime, now),
}
if !p.LastHandshakeTime.IsZero() {
peer["latest-handshake"] = p.LastHandshakeTime.UTC().Format("2006-01-02T15:04:05+00:00")
}
if p.Endpoint != nil {
peer["endpoint-address"] = p.Endpoint.IP.String()
peer["endpoint-port"] = p.Endpoint.Port
}
if p.TransmitBytes > 0 || p.ReceiveBytes > 0 {
peer["transfer"] = map[string]any{
"tx-bytes": strconv.FormatInt(p.TransmitBytes, 10),
"rx-bytes": strconv.FormatInt(p.ReceiveBytes, 10),
}
}
peers = append(peers, peer)
}
if len(peers) == 0 {
continue
}
out, err := json.Marshal(map[string]any{"peer-status": map[string]any{"peer": peers}})
if err != nil {
continue
}
result[ifname] = out
}
if len(result) == 0 {
return nil
}
return result
}
func findWireguardIfaces(links json.RawMessage) []string {
var ifaces []map[string]any
if json.Unmarshal(links, &ifaces) != nil {
return nil
}
var result []string
for _, iface := range ifaces {
linkinfo, _ := iface["linkinfo"].(map[string]any)
if linkinfo == nil {
continue
}
if kind, _ := linkinfo["info_kind"].(string); kind == "wireguard" {
if name, _ := iface["ifname"].(string); name != "" {
result = append(result, name)
}
}
}
return result
}
func connectionStatus(handshake time.Time, now time.Time) string {
if handshake.IsZero() {
return "down"
}
if now.Sub(handshake) < 180*time.Second {
return "up"
}
return "down"
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-103
View File
@@ -1,103 +0,0 @@
// Copyright (C) 2021 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"github.com/sirupsen/logrus"
)
type LogLevel uint32
const (
PanicLevel LogLevel = iota
FatalLevel
ErrorLevel
WarnLevel
InfoLevel
DebugLevel
TraceLevel
)
const (
FieldFacility = "_facility"
)
var (
FacilityUnspecified interface{} = "unspecified"
FacilityConfig interface{} = "config"
)
type Fields map[string]interface{}
func (fields Fields) HasFacility(facility interface{}) bool {
if fieldsFacility, hasFacility := fields[FieldFacility]; hasFacility && fieldsFacility == facility {
return true
}
return false
}
type Logger interface {
Panic(msg string, fields Fields)
Fatal(msg string, fields Fields)
Error(msg string, fields Fields)
Warn(msg string, fields Fields)
Info(msg string, fields Fields)
Debug(msg string, fields Fields)
SetLevel(level LogLevel)
GetLevel() LogLevel
}
type DefaultLogger struct {
logger *logrus.Logger
}
func (l *DefaultLogger) Panic(msg string, fields Fields) {
l.logger.WithFields(logrus.Fields(fields)).Panic(msg)
}
func (l *DefaultLogger) Fatal(msg string, fields Fields) {
l.logger.WithFields(logrus.Fields(fields)).Fatal(msg)
}
func (l *DefaultLogger) Error(msg string, fields Fields) {
l.logger.WithFields(logrus.Fields(fields)).Error(msg)
}
func (l *DefaultLogger) Warn(msg string, fields Fields) {
l.logger.WithFields(logrus.Fields(fields)).Warn(msg)
}
func (l *DefaultLogger) Info(msg string, fields Fields) {
l.logger.WithFields(logrus.Fields(fields)).Info(msg)
}
func (l *DefaultLogger) Debug(msg string, fields Fields) {
l.logger.WithFields(logrus.Fields(fields)).Debug(msg)
}
func (l *DefaultLogger) SetLevel(level LogLevel) {
l.logger.SetLevel(logrus.Level(level))
}
func (l *DefaultLogger) GetLevel() LogLevel {
return LogLevel(l.logger.GetLevel())
}
func NewDefaultLogger() *DefaultLogger {
return &DefaultLogger{
logger: logrus.New(),
}
}
File diff suppressed because it is too large Load Diff
@@ -1,75 +0,0 @@
// Code generated by "stringer -type=BGPAttrType"; DO NOT EDIT.
package bgp
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[BGP_ATTR_TYPE_ORIGIN-1]
_ = x[BGP_ATTR_TYPE_AS_PATH-2]
_ = x[BGP_ATTR_TYPE_NEXT_HOP-3]
_ = x[BGP_ATTR_TYPE_MULTI_EXIT_DISC-4]
_ = x[BGP_ATTR_TYPE_LOCAL_PREF-5]
_ = x[BGP_ATTR_TYPE_ATOMIC_AGGREGATE-6]
_ = x[BGP_ATTR_TYPE_AGGREGATOR-7]
_ = x[BGP_ATTR_TYPE_COMMUNITIES-8]
_ = x[BGP_ATTR_TYPE_ORIGINATOR_ID-9]
_ = x[BGP_ATTR_TYPE_CLUSTER_LIST-10]
_ = x[BGP_ATTR_TYPE_MP_REACH_NLRI-14]
_ = x[BGP_ATTR_TYPE_MP_UNREACH_NLRI-15]
_ = x[BGP_ATTR_TYPE_EXTENDED_COMMUNITIES-16]
_ = x[BGP_ATTR_TYPE_AS4_PATH-17]
_ = x[BGP_ATTR_TYPE_AS4_AGGREGATOR-18]
_ = x[BGP_ATTR_TYPE_PMSI_TUNNEL-22]
_ = x[BGP_ATTR_TYPE_TUNNEL_ENCAP-23]
_ = x[BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIES-25]
_ = x[BGP_ATTR_TYPE_AIGP-26]
_ = x[BGP_ATTR_TYPE_LS-29]
_ = x[BGP_ATTR_TYPE_LARGE_COMMUNITY-32]
_ = x[BGP_ATTR_TYPE_PREFIX_SID-40]
}
const (
_BGPAttrType_name_0 = "BGP_ATTR_TYPE_ORIGINBGP_ATTR_TYPE_AS_PATHBGP_ATTR_TYPE_NEXT_HOPBGP_ATTR_TYPE_MULTI_EXIT_DISCBGP_ATTR_TYPE_LOCAL_PREFBGP_ATTR_TYPE_ATOMIC_AGGREGATEBGP_ATTR_TYPE_AGGREGATORBGP_ATTR_TYPE_COMMUNITIESBGP_ATTR_TYPE_ORIGINATOR_IDBGP_ATTR_TYPE_CLUSTER_LIST"
_BGPAttrType_name_1 = "BGP_ATTR_TYPE_MP_REACH_NLRIBGP_ATTR_TYPE_MP_UNREACH_NLRIBGP_ATTR_TYPE_EXTENDED_COMMUNITIESBGP_ATTR_TYPE_AS4_PATHBGP_ATTR_TYPE_AS4_AGGREGATOR"
_BGPAttrType_name_2 = "BGP_ATTR_TYPE_PMSI_TUNNELBGP_ATTR_TYPE_TUNNEL_ENCAP"
_BGPAttrType_name_3 = "BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIESBGP_ATTR_TYPE_AIGP"
_BGPAttrType_name_4 = "BGP_ATTR_TYPE_LS"
_BGPAttrType_name_5 = "BGP_ATTR_TYPE_LARGE_COMMUNITY"
_BGPAttrType_name_6 = "BGP_ATTR_TYPE_PREFIX_SID"
)
var (
_BGPAttrType_index_0 = [...]uint8{0, 20, 41, 63, 92, 116, 146, 170, 195, 222, 248}
_BGPAttrType_index_1 = [...]uint8{0, 27, 56, 90, 112, 140}
_BGPAttrType_index_2 = [...]uint8{0, 25, 51}
_BGPAttrType_index_3 = [...]uint8{0, 38, 56}
)
func (i BGPAttrType) String() string {
switch {
case 1 <= i && i <= 10:
i -= 1
return _BGPAttrType_name_0[_BGPAttrType_index_0[i]:_BGPAttrType_index_0[i+1]]
case 14 <= i && i <= 18:
i -= 14
return _BGPAttrType_name_1[_BGPAttrType_index_1[i]:_BGPAttrType_index_1[i+1]]
case 22 <= i && i <= 23:
i -= 22
return _BGPAttrType_name_2[_BGPAttrType_index_2[i]:_BGPAttrType_index_2[i+1]]
case 25 <= i && i <= 26:
i -= 25
return _BGPAttrType_name_3[_BGPAttrType_index_3[i]:_BGPAttrType_index_3[i+1]]
case i == 29:
return _BGPAttrType_name_4
case i == 32:
return _BGPAttrType_name_5
case i == 40:
return _BGPAttrType_name_6
default:
return "BGPAttrType(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
-328
View File
@@ -1,328 +0,0 @@
// Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bgp
import (
"strconv"
"strings"
)
const AS_TRANS = 23456
const BGP_PORT = 179
//go:generate stringer -type=FSMState
type FSMState int
const (
BGP_FSM_IDLE FSMState = iota
BGP_FSM_CONNECT
BGP_FSM_ACTIVE
BGP_FSM_OPENSENT
BGP_FSM_OPENCONFIRM
BGP_FSM_ESTABLISHED
)
// partially taken from http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
type Protocol int
const (
Unknown Protocol = iota
ICMP = 0x01
IGMP = 0x02
TCP = 0x06
EGP = 0x08
IGP = 0x09
UDP = 0x11
RSVP = 0x2e
GRE = 0x2f
OSPF = 0x59
IPIP = 0x5e
PIM = 0x67
SCTP = 0x84
)
var ProtocolNameMap = map[Protocol]string{
Unknown: "unknown",
ICMP: "icmp",
IGMP: "igmp",
TCP: "tcp",
EGP: "egp",
IGP: "igp",
UDP: "udp",
RSVP: "rsvp",
GRE: "gre",
OSPF: "ospf",
IPIP: "ipip",
PIM: "pim",
SCTP: "sctp",
}
func (p Protocol) String() string {
name, ok := ProtocolNameMap[p]
if !ok {
return strconv.Itoa(int(p))
}
return name
}
type TCPFlag int
const (
_ TCPFlag = iota
TCP_FLAG_FIN = 0x01
TCP_FLAG_SYN = 0x02
TCP_FLAG_RST = 0x04
TCP_FLAG_PUSH = 0x08
TCP_FLAG_ACK = 0x10
TCP_FLAG_URGENT = 0x20
TCP_FLAG_ECE = 0x40
TCP_FLAG_CWR = 0x80
)
var TCPFlagNameMap = map[TCPFlag]string{
TCP_FLAG_FIN: "F",
TCP_FLAG_SYN: "S",
TCP_FLAG_RST: "R",
TCP_FLAG_PUSH: "P",
TCP_FLAG_ACK: "A",
TCP_FLAG_URGENT: "U",
TCP_FLAG_CWR: "C",
TCP_FLAG_ECE: "E",
}
// Prepares a sorted list of flags because map iterations does not happen
// in a consistent order in Golang.
var TCPSortedFlags = []TCPFlag{
TCP_FLAG_FIN,
TCP_FLAG_SYN,
TCP_FLAG_RST,
TCP_FLAG_PUSH,
TCP_FLAG_ACK,
TCP_FLAG_URGENT,
TCP_FLAG_ECE,
TCP_FLAG_CWR,
}
func (f TCPFlag) String() string {
flags := make([]string, 0, len(TCPSortedFlags))
for _, v := range TCPSortedFlags {
if f&v > 0 {
flags = append(flags, TCPFlagNameMap[v])
}
}
return strings.Join(flags, "")
}
type BitmaskFlagOp uint8
const (
BITMASK_FLAG_OP_OR BitmaskFlagOp = iota
BITMASK_FLAG_OP_MATCH = 0x01
BITMASK_FLAG_OP_NOT = 0x02
BITMASK_FLAG_OP_NOT_MATCH = 0x03
BITMASK_FLAG_OP_AND = 0x40
BITMASK_FLAG_OP_END = 0x80
)
var BitmaskFlagOpNameMap = map[BitmaskFlagOp]string{
BITMASK_FLAG_OP_OR: " ",
BITMASK_FLAG_OP_AND: "&",
BITMASK_FLAG_OP_END: "E",
BITMASK_FLAG_OP_NOT: "!",
BITMASK_FLAG_OP_MATCH: "=",
}
// Note: Meaning of "" is different from that of the numeric operator because
// RFC5575 says if the Match bit in the bitmask operand is set, it should be
// "strictly" matching against the given value.
var BitmaskFlagOpValueMap = map[string]BitmaskFlagOp{
" ": BITMASK_FLAG_OP_OR,
"": BITMASK_FLAG_OP_OR,
"==": BITMASK_FLAG_OP_MATCH,
"=": BITMASK_FLAG_OP_MATCH,
"!": BITMASK_FLAG_OP_NOT,
"!=": BITMASK_FLAG_OP_NOT_MATCH,
"=!": BITMASK_FLAG_OP_NOT_MATCH, // For the backward compatibility
"&": BITMASK_FLAG_OP_AND,
"E": BITMASK_FLAG_OP_END,
}
func (f BitmaskFlagOp) String() string {
ops := make([]string, 0, 3)
if f&BITMASK_FLAG_OP_AND > 0 {
ops = append(ops, BitmaskFlagOpNameMap[BITMASK_FLAG_OP_AND])
} else {
ops = append(ops, BitmaskFlagOpNameMap[BITMASK_FLAG_OP_OR])
}
if f&BITMASK_FLAG_OP_NOT > 0 {
ops = append(ops, BitmaskFlagOpNameMap[BITMASK_FLAG_OP_NOT])
}
if f&BITMASK_FLAG_OP_MATCH > 0 {
ops = append(ops, BitmaskFlagOpNameMap[BITMASK_FLAG_OP_MATCH])
}
return strings.Join(ops, "")
}
type FragmentFlag int
const (
FRAG_FLAG_NOT FragmentFlag = iota
FRAG_FLAG_DONT = 0x01
FRAG_FLAG_IS = 0x02
FRAG_FLAG_FIRST = 0x04
FRAG_FLAG_LAST = 0x08
)
var FragmentFlagNameMap = map[FragmentFlag]string{
FRAG_FLAG_NOT: "not-a-fragment",
FRAG_FLAG_DONT: "dont-fragment",
FRAG_FLAG_IS: "is-fragment",
FRAG_FLAG_FIRST: "first-fragment",
FRAG_FLAG_LAST: "last-fragment",
}
// Prepares a sorted list of flags because map iterations does not happen
// in a consistent order in Golang.
var FragmentSortedFlags = []FragmentFlag{
FRAG_FLAG_NOT,
FRAG_FLAG_DONT,
FRAG_FLAG_IS,
FRAG_FLAG_FIRST,
FRAG_FLAG_LAST,
}
func (f FragmentFlag) String() string {
flags := make([]string, 0, len(FragmentSortedFlags))
for _, v := range FragmentSortedFlags {
if f&v > 0 {
flags = append(flags, FragmentFlagNameMap[v])
}
}
// Note: If multiple bits are set, joins them with "+".
return strings.Join(flags, "+")
}
type DECNumOp uint8
const (
DEC_NUM_OP_TRUE DECNumOp = iota // true always with END bit set
DEC_NUM_OP_EQ = 0x01
DEC_NUM_OP_GT = 0x02
DEC_NUM_OP_GT_EQ = 0x03
DEC_NUM_OP_LT = 0x04
DEC_NUM_OP_LT_EQ = 0x05
DEC_NUM_OP_NOT_EQ = 0x06
DEC_NUM_OP_FALSE = 0x07 // false always with END bit set
DEC_NUM_OP_OR = 0x00
DEC_NUM_OP_AND = 0x40
DEC_NUM_OP_END = 0x80
)
var DECNumOpNameMap = map[DECNumOp]string{
DEC_NUM_OP_TRUE: "true",
DEC_NUM_OP_EQ: "==",
DEC_NUM_OP_GT: ">",
DEC_NUM_OP_GT_EQ: ">=",
DEC_NUM_OP_LT: "<",
DEC_NUM_OP_LT_EQ: "<=",
DEC_NUM_OP_NOT_EQ: "!=",
DEC_NUM_OP_FALSE: "false",
//DEC_NUM_OP_OR: " ", // duplicate with DEC_NUM_OP_TRUE
DEC_NUM_OP_AND: "&",
DEC_NUM_OP_END: "E",
}
var DECNumOpValueMap = map[string]DECNumOp{
"true": DEC_NUM_OP_TRUE,
"": DEC_NUM_OP_EQ,
"==": DEC_NUM_OP_EQ,
"=": DEC_NUM_OP_EQ,
">": DEC_NUM_OP_GT,
">=": DEC_NUM_OP_GT_EQ,
"<": DEC_NUM_OP_LT,
"<=": DEC_NUM_OP_LT_EQ,
"!=": DEC_NUM_OP_NOT_EQ,
"=!": DEC_NUM_OP_NOT_EQ,
"!": DEC_NUM_OP_NOT_EQ,
"false": DEC_NUM_OP_FALSE,
" ": DEC_NUM_OP_OR,
"&": DEC_NUM_OP_AND,
"E": DEC_NUM_OP_END,
}
func (f DECNumOp) String() string {
ops := make([]string, 0)
logicFlag := DECNumOp(f & 0xc0) // higher 2 bits
if logicFlag&DEC_NUM_OP_AND > 0 {
ops = append(ops, DECNumOpNameMap[DEC_NUM_OP_AND])
} else {
ops = append(ops, " ") // DEC_NUM_OP_OR
}
// Omits DEC_NUM_OP_END
cmpFlag := DECNumOp(f & 0x7) // lower 3 bits
for v, s := range DECNumOpNameMap {
if cmpFlag == v {
ops = append(ops, s)
break
}
}
return strings.Join(ops, "")
}
// Potentially taken from https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml
type EthernetType int
const (
IPv4 EthernetType = 0x0800
ARP EthernetType = 0x0806
RARP EthernetType = 0x8035
VMTP EthernetType = 0x805B
APPLE_TALK EthernetType = 0x809B
AARP EthernetType = 0x80F3
IPX EthernetType = 0x8137
SNMP EthernetType = 0x814C
NET_BIOS EthernetType = 0x8191
XTP EthernetType = 0x817D
IPv6 EthernetType = 0x86DD
PPPoE_DISCOVERY EthernetType = 0x8863
PPPoE_SESSION EthernetType = 0x8864
LOOPBACK EthernetType = 0x9000
)
var EthernetTypeNameMap = map[EthernetType]string{
IPv4: "ipv4",
ARP: "arp",
RARP: "rarp",
VMTP: "vmtp",
APPLE_TALK: "apple-talk",
AARP: "aarp",
IPX: "ipx",
SNMP: "snmp",
NET_BIOS: "net-bios",
XTP: "xtp",
IPv6: "ipv6",
PPPoE_DISCOVERY: "pppoe-discovery",
PPPoE_SESSION: "pppoe-session",
LOOPBACK: "loopback",
}
func (t EthernetType) String() string {
if name, ok := EthernetTypeNameMap[t]; ok {
return name
}
return strconv.Itoa(int(t))
}
@@ -1,28 +0,0 @@
// Code generated by "stringer -type=ESIType"; DO NOT EDIT.
package bgp
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[ESI_ARBITRARY-0]
_ = x[ESI_LACP-1]
_ = x[ESI_MSTP-2]
_ = x[ESI_MAC-3]
_ = x[ESI_ROUTERID-4]
_ = x[ESI_AS-5]
}
const _ESIType_name = "ESI_ARBITRARYESI_LACPESI_MSTPESI_MACESI_ROUTERIDESI_AS"
var _ESIType_index = [...]uint8{0, 13, 21, 29, 36, 48, 54}
func (i ESIType) String() string {
if i >= ESIType(len(_ESIType_index)-1) {
return "ESIType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _ESIType_name[_ESIType_index[i]:_ESIType_index[i+1]]
}
@@ -1,28 +0,0 @@
// Code generated by "stringer -type=FSMState"; DO NOT EDIT.
package bgp
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[BGP_FSM_IDLE-0]
_ = x[BGP_FSM_CONNECT-1]
_ = x[BGP_FSM_ACTIVE-2]
_ = x[BGP_FSM_OPENSENT-3]
_ = x[BGP_FSM_OPENCONFIRM-4]
_ = x[BGP_FSM_ESTABLISHED-5]
}
const _FSMState_name = "BGP_FSM_IDLEBGP_FSM_CONNECTBGP_FSM_ACTIVEBGP_FSM_OPENSENTBGP_FSM_OPENCONFIRMBGP_FSM_ESTABLISHED"
var _FSMState_index = [...]uint8{0, 12, 27, 41, 57, 76, 95}
func (i FSMState) String() string {
if i < 0 || i >= FSMState(len(_FSMState_index)-1) {
return "FSMState(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _FSMState_name[_FSMState_index[i]:_FSMState_index[i+1]]
}
-129
View File
@@ -1,129 +0,0 @@
// Copyright (C) 2016 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bgp
func NewTestBGPOpenMessage() *BGPMessage {
p1 := NewOptionParameterCapability(
[]ParameterCapabilityInterface{NewCapRouteRefresh()})
p2 := NewOptionParameterCapability(
[]ParameterCapabilityInterface{NewCapMultiProtocol(RF_IPv4_UC)})
g := &CapGracefulRestartTuple{4, 2, 3}
p3 := NewOptionParameterCapability(
[]ParameterCapabilityInterface{NewCapGracefulRestart(false, true, 100,
[]*CapGracefulRestartTuple{g})})
p4 := NewOptionParameterCapability(
[]ParameterCapabilityInterface{NewCapFourOctetASNumber(100000)})
p5 := NewOptionParameterCapability(
[]ParameterCapabilityInterface{NewCapAddPath([]*CapAddPathTuple{NewCapAddPathTuple(RF_IPv4_UC, BGP_ADD_PATH_BOTH)})})
return NewBGPOpenMessage(11033, 303, "100.4.10.3",
[]OptionParameterInterface{p1, p2, p3, p4, p5})
}
func NewTestBGPUpdateMessage() *BGPMessage {
w1 := NewIPAddrPrefix(23, "121.1.3.2")
w2 := NewIPAddrPrefix(17, "100.33.3.0")
w := []*IPAddrPrefix{w1, w2}
aspath1 := []AsPathParamInterface{
NewAsPathParam(2, []uint16{1000}),
NewAsPathParam(1, []uint16{1001, 1002}),
NewAsPathParam(2, []uint16{1003, 1004}),
}
aspath2 := []AsPathParamInterface{
NewAs4PathParam(2, []uint32{1000000}),
NewAs4PathParam(1, []uint32{1000001, 1002}),
NewAs4PathParam(2, []uint32{1003, 100004}),
}
aspath3 := []*As4PathParam{
NewAs4PathParam(2, []uint32{1000000}),
NewAs4PathParam(1, []uint32{1000001, 1002}),
NewAs4PathParam(2, []uint32{1003, 100004}),
}
isTransitive := true
ecommunities := []ExtendedCommunityInterface{
NewTwoOctetAsSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, 10003, 3<<20, isTransitive),
NewFourOctetAsSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, 1<<20, 300, isTransitive),
NewIPv4AddressSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, "192.2.1.2", 3000, isTransitive),
NewOpaqueExtended(false, []byte{1, 2, 3, 4, 5, 6, 7}),
NewValidationExtended(VALIDATION_STATE_INVALID),
NewUnknownExtended(99, []byte{0, 1, 2, 3, 4, 5, 6, 7}),
NewESILabelExtended(1000, true),
NewESImportRouteTarget("11:22:33:44:55:66"),
NewMacMobilityExtended(123, false),
}
prefixes1 := []AddrPrefixInterface{
NewLabeledVPNIPAddrPrefix(24, "192.0.9.0", *NewMPLSLabelStack(1, 2, 3),
NewRouteDistinguisherTwoOctetAS(256, 10000)),
NewLabeledVPNIPAddrPrefix(24, "192.10.8.0", *NewMPLSLabelStack(5, 6, 7, 8),
NewRouteDistinguisherIPAddressAS("10.0.1.1", 10001)),
}
prefixes2 := []AddrPrefixInterface{NewIPv6AddrPrefix(128,
"fe80:1234:1234:5667:8967:af12:8912:1023")}
prefixes3 := []AddrPrefixInterface{NewLabeledVPNIPv6AddrPrefix(128,
"fe80:1234:1234:5667:8967:af12:1203:33a1", *NewMPLSLabelStack(5, 6),
NewRouteDistinguisherFourOctetAS(5, 6))}
prefixes4 := []AddrPrefixInterface{NewLabeledIPAddrPrefix(25, "192.168.0.0",
*NewMPLSLabelStack(5, 6, 7))}
prefixes5 := []AddrPrefixInterface{
NewEVPNEthernetAutoDiscoveryRoute(NewRouteDistinguisherFourOctetAS(5, 6), EthernetSegmentIdentifier{ESI_ARBITRARY, make([]byte, 9)}, 2, 2),
NewEVPNMacIPAdvertisementRoute(NewRouteDistinguisherFourOctetAS(5, 6), EthernetSegmentIdentifier{ESI_ARBITRARY, make([]byte, 9)}, 3, "01:23:45:67:89:ab", "192.2.1.2", []uint32{3, 4}),
NewEVPNMulticastEthernetTagRoute(NewRouteDistinguisherFourOctetAS(5, 6), 3, "192.2.1.2"),
NewEVPNEthernetSegmentRoute(NewRouteDistinguisherFourOctetAS(5, 6), EthernetSegmentIdentifier{ESI_ARBITRARY, make([]byte, 9)}, "192.2.1.1"),
NewEVPNIPPrefixRoute(NewRouteDistinguisherFourOctetAS(5, 6), EthernetSegmentIdentifier{ESI_ARBITRARY, make([]byte, 9)}, 5, 24, "192.2.1.0", "192.3.1.1", 5),
}
prefixes6 := []AddrPrefixInterface{NewVPLSNLRI(NewRouteDistinguisherFourOctetAS(5, 6), 101, 100, 10, 1000)}
p := []PathAttributeInterface{
NewPathAttributeOrigin(3),
NewPathAttributeAsPath(aspath1),
NewPathAttributeAsPath(aspath2),
NewPathAttributeNextHop("129.1.1.2"),
NewPathAttributeMultiExitDisc(1 << 20),
NewPathAttributeLocalPref(1 << 22),
NewPathAttributeAtomicAggregate(),
NewPathAttributeAggregator(uint16(30002), "129.0.2.99"),
NewPathAttributeAggregator(uint32(30002), "129.0.2.99"),
NewPathAttributeAggregator(uint32(300020), "129.0.2.99"),
NewPathAttributeCommunities([]uint32{1, 3}),
NewPathAttributeOriginatorId("10.10.0.1"),
NewPathAttributeClusterList([]string{"10.10.0.2", "10.10.0.3"}),
NewPathAttributeExtendedCommunities(ecommunities),
NewPathAttributeAs4Path(aspath3),
NewPathAttributeAs4Aggregator(10000, "112.22.2.1"),
NewPathAttributeMpReachNLRI("112.22.2.0", prefixes1),
NewPathAttributeMpReachNLRI("1023::", prefixes2),
NewPathAttributeMpReachNLRI("fe80::", prefixes3),
NewPathAttributeMpReachNLRI("129.1.1.1", prefixes4),
NewPathAttributeMpReachNLRI("129.1.1.1", prefixes5),
NewPathAttributeMpReachNLRI("135.1.1.1", prefixes6),
NewPathAttributeMpUnreachNLRI(prefixes1),
//NewPathAttributeMpReachNLRI("112.22.2.0", []AddrPrefixInterface{}),
//NewPathAttributeMpUnreachNLRI([]AddrPrefixInterface{}),
NewPathAttributeUnknown(BGP_ATTR_FLAG_TRANSITIVE, 100, []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}),
}
n := []*IPAddrPrefix{NewIPAddrPrefix(24, "13.2.3.1")}
return NewBGPUpdateMessage(w, p, n)
}
-744
View File
@@ -1,744 +0,0 @@
package bgp
import (
"encoding/binary"
"encoding/json"
"fmt"
"net/netip"
)
// MUPExtended represents BGP MUP Extended Community as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-00#section-3.2
type MUPExtended struct {
SubType ExtendedCommunityAttrSubType
SegmentID2 uint16
SegmentID4 uint32
}
func (e *MUPExtended) Serialize() ([]byte, error) {
buf := make([]byte, 8)
buf[0] = byte(EC_TYPE_MUP)
buf[1] = byte(EC_SUBTYPE_MUP_DIRECT_SEG)
binary.BigEndian.PutUint16(buf[2:4], e.SegmentID2)
binary.BigEndian.PutUint32(buf[4:8], e.SegmentID4)
return buf, nil
}
func (e *MUPExtended) String() string {
return fmt.Sprintf("%d:%d", e.SegmentID2, e.SegmentID4)
}
func (e *MUPExtended) MarshalJSON() ([]byte, error) {
t, s := e.GetTypes()
return json.Marshal(struct {
Type ExtendedCommunityAttrType `json:"type"`
Subtype ExtendedCommunityAttrSubType `json:"subtype"`
SegmentID string `json:"segmend_id"`
}{
Type: t,
Subtype: s,
SegmentID: fmt.Sprintf("%d:%d", e.SegmentID2, e.SegmentID4),
})
}
func (e *MUPExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
return EC_TYPE_MUP, EC_SUBTYPE_MUP_DIRECT_SEG
}
func (e *MUPExtended) Flat() map[string]string {
return map[string]string{}
}
func NewMUPExtended(sid2 uint16, sid4 uint32) *MUPExtended {
return &MUPExtended{
SubType: EC_SUBTYPE_MUP_DIRECT_SEG,
SegmentID2: sid2,
SegmentID4: sid4,
}
}
func parseMUPExtended(data []byte) (ExtendedCommunityInterface, error) {
typ := ExtendedCommunityAttrType(data[0])
if typ != EC_TYPE_MUP {
return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("ext comm type is not EC_TYPE_MUP: %d", data[0]))
}
subType := ExtendedCommunityAttrSubType(data[1])
if subType == EC_SUBTYPE_MUP_DIRECT_SEG {
sid2 := binary.BigEndian.Uint16(data[2:4])
sid4 := binary.BigEndian.Uint32(data[4:8])
return NewMUPExtended(sid2, sid4), nil
}
return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("unknown mup subtype: %d", subType))
}
// BGP MUP SAFI Architecture Type as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-00#section-3.1
const (
MUP_ARCH_TYPE_UNDEFINED = iota
MUP_ARCH_TYPE_3GPP_5G
)
// BGP MUP SAFI Route Type as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-00#section-3.1
const (
_ = iota
MUP_ROUTE_TYPE_INTERWORK_SEGMENT_DISCOVERY
MUP_ROUTE_TYPE_DIRECT_SEGMENT_DISCOVERY
MUP_ROUTE_TYPE_TYPE_1_SESSION_TRANSFORMED
MUP_ROUTE_TYPE_TYPE_2_SESSION_TRANSFORMED
)
type MUPRouteTypeInterface interface {
DecodeFromBytes([]byte, uint16) error
Serialize() ([]byte, error)
AFI() uint16
Len() int
String() string
MarshalJSON() ([]byte, error)
rd() RouteDistinguisherInterface
}
func getMUPRouteType(at uint8, rt uint16) (MUPRouteTypeInterface, error) {
switch rt {
case MUP_ROUTE_TYPE_INTERWORK_SEGMENT_DISCOVERY:
if at == MUP_ARCH_TYPE_3GPP_5G {
return &MUPInterworkSegmentDiscoveryRoute{}, nil
}
case MUP_ROUTE_TYPE_DIRECT_SEGMENT_DISCOVERY:
if at == MUP_ARCH_TYPE_3GPP_5G {
return &MUPDirectSegmentDiscoveryRoute{}, nil
}
case MUP_ROUTE_TYPE_TYPE_1_SESSION_TRANSFORMED:
if at == MUP_ARCH_TYPE_3GPP_5G {
return &MUPType1SessionTransformedRoute{}, nil
}
case MUP_ROUTE_TYPE_TYPE_2_SESSION_TRANSFORMED:
if at == MUP_ARCH_TYPE_3GPP_5G {
return &MUPType2SessionTransformedRoute{}, nil
}
}
return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Unknown MUP Architecture and Route type: %d, %d", at, rt))
}
type MUPNLRI struct {
PrefixDefault
Afi uint16
ArchitectureType uint8
RouteType uint16
Length uint8
RouteTypeData MUPRouteTypeInterface
}
func (n *MUPNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
if len(data) < 4 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all MUPNLRI bytes available")
}
n.ArchitectureType = data[0]
n.RouteType = binary.BigEndian.Uint16(data[1:3])
n.Length = data[3]
data = data[4:]
if len(data) < int(n.Length) {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all MUPNLRI Route type bytes available")
}
r, err := getMUPRouteType(n.ArchitectureType, n.RouteType)
if err != nil {
return err
}
n.RouteTypeData = r
return n.RouteTypeData.DecodeFromBytes(data[:n.Length], n.Afi)
}
func (n *MUPNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
buf := make([]byte, 4)
buf[0] = n.ArchitectureType
binary.BigEndian.PutUint16(buf[1:3], n.RouteType)
buf[3] = n.Length
tbuf, err := n.RouteTypeData.Serialize()
if err != nil {
return nil, err
}
return append(buf, tbuf...), nil
}
func (n *MUPNLRI) AFI() uint16 {
return n.Afi
}
func (n *MUPNLRI) SAFI() uint8 {
return SAFI_MUP
}
func (n *MUPNLRI) Len(options ...*MarshallingOption) int {
return int(n.Length) + 4
}
func (n *MUPNLRI) String() string {
if n.RouteTypeData != nil {
return n.RouteTypeData.String()
}
return fmt.Sprintf("%d:%d:%d", n.ArchitectureType, n.RouteType, n.Length)
}
func (n *MUPNLRI) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
ArchitectureType uint8 `json:"arch_type"`
RouteType uint16 `json:"route_type"`
Value MUPRouteTypeInterface `json:"value"`
}{
ArchitectureType: n.ArchitectureType,
RouteType: n.RouteType,
Value: n.RouteTypeData,
})
}
func (n *MUPNLRI) RD() RouteDistinguisherInterface {
return n.RouteTypeData.rd()
}
func (l *MUPNLRI) Flat() map[string]string {
return map[string]string{}
}
func NewMUPNLRI(afi uint16, at uint8, rt uint16, data MUPRouteTypeInterface) *MUPNLRI {
var l uint8
if data != nil {
l = uint8(data.Len())
}
return &MUPNLRI{
Afi: afi,
ArchitectureType: at,
RouteType: rt,
Length: l,
RouteTypeData: data,
}
}
func TEIDString(nlri AddrPrefixInterface) string {
s := ""
switch n := nlri.(type) {
case *MUPNLRI:
switch route := n.RouteTypeData.(type) {
case *MUPType1SessionTransformedRoute:
s = route.TEID.String()
default:
s = ""
}
}
return s
}
func QFIString(nlri AddrPrefixInterface) string {
s := ""
switch n := nlri.(type) {
case *MUPNLRI:
switch route := n.RouteTypeData.(type) {
case *MUPType1SessionTransformedRoute:
s = fmt.Sprintf("%d", route.QFI)
default:
s = ""
}
}
return s
}
func EndpointString(nlri AddrPrefixInterface) string {
s := ""
switch n := nlri.(type) {
case *MUPNLRI:
switch route := n.RouteTypeData.(type) {
case *MUPType1SessionTransformedRoute:
s = route.EndpointAddress.String()
default:
s = ""
}
}
return s
}
// MUPInterworkSegmentDiscoveryRoute represents BGP Interwork Segment Discovery route as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-00#section-3.1.1
type MUPInterworkSegmentDiscoveryRoute struct {
RD RouteDistinguisherInterface
Prefix netip.Prefix
}
func NewMUPInterworkSegmentDiscoveryRoute(rd RouteDistinguisherInterface, prefix netip.Prefix) *MUPNLRI {
afi := uint16(AFI_IP)
if prefix.Addr().Is6() {
afi = AFI_IP6
}
return NewMUPNLRI(afi, MUP_ARCH_TYPE_3GPP_5G, MUP_ROUTE_TYPE_INTERWORK_SEGMENT_DISCOVERY, &MUPInterworkSegmentDiscoveryRoute{
RD: rd,
Prefix: prefix,
})
}
func (r *MUPInterworkSegmentDiscoveryRoute) DecodeFromBytes(data []byte, afi uint16) error {
r.RD = GetRouteDistinguisher(data)
p := r.RD.Len()
if len(data) < p {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid Interwork Segment Discovery Route length")
}
bits := int(data[p])
p += 1
byteLen := (bits + 7) / 8
if len(data[p:]) < byteLen {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "prefix bytes is short")
}
addrLen := 4
if afi == AFI_IP6 {
addrLen = 16
}
if bits > addrLen*8 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "prefix length is too long")
}
b := make([]byte, addrLen)
copy(b[0:byteLen], data[p:p+byteLen])
addr, ok := netip.AddrFromSlice(b)
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Prefix: %x", data[p:]))
}
r.Prefix = netip.PrefixFrom(addr, bits)
if r.Prefix.Bits() == -1 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Prefix: %s", r.Prefix))
}
return nil
}
func (r *MUPInterworkSegmentDiscoveryRoute) Serialize() ([]byte, error) {
var buf []byte
var err error
if r.RD != nil {
buf, err = r.RD.Serialize()
if err != nil {
return nil, err
}
} else {
buf = make([]byte, 8)
}
buf = append(buf, uint8(r.Prefix.Bits()))
byteLen := (r.Prefix.Bits() + 7) / 8
buf = append(buf, r.Prefix.Addr().AsSlice()[:byteLen]...)
return buf, nil
}
func (r *MUPInterworkSegmentDiscoveryRoute) AFI() uint16 {
if r.Prefix.Addr().Is6() {
return AFI_IP6
}
return AFI_IP
}
func (r *MUPInterworkSegmentDiscoveryRoute) Len() int {
// RD(8) + PrefixLength(1) + Prefix(variable)
return 9 + (r.Prefix.Bits()+7)/8
}
func (r *MUPInterworkSegmentDiscoveryRoute) String() string {
// I-D.draft-mpmz-bess-mup-safi-01
// 3.1.1. BGP Interwork Segment Discovery route
// For the purpose of BGP route key processing, only the RD, Prefix Length and Prefix are considered to be part of the prefix in the NLRI.
return fmt.Sprintf("[type:isd][rd:%s][prefix:%s]", r.RD, r.Prefix)
}
func (r *MUPInterworkSegmentDiscoveryRoute) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
RD RouteDistinguisherInterface `json:"rd"`
Prefix string `json:"prefix"`
}{
RD: r.RD,
Prefix: r.Prefix.String(),
})
}
func (r *MUPInterworkSegmentDiscoveryRoute) rd() RouteDistinguisherInterface {
return r.RD
}
// MUPDirectSegmentDiscoveryRoute represents BGP Direct Segment Discovery route as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-00#section-3.1.2
type MUPDirectSegmentDiscoveryRoute struct {
RD RouteDistinguisherInterface
Address netip.Addr
}
func NewMUPDirectSegmentDiscoveryRoute(rd RouteDistinguisherInterface, address netip.Addr) *MUPNLRI {
afi := uint16(AFI_IP)
if address.Is6() {
afi = AFI_IP6
}
return NewMUPNLRI(afi, MUP_ARCH_TYPE_3GPP_5G, MUP_ROUTE_TYPE_DIRECT_SEGMENT_DISCOVERY, &MUPDirectSegmentDiscoveryRoute{
RD: rd,
Address: address,
})
}
func (r *MUPDirectSegmentDiscoveryRoute) DecodeFromBytes(data []byte, afi uint16) error {
r.RD = GetRouteDistinguisher(data)
rdLen := r.RD.Len()
if len(data) != 12 && len(data) != 24 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid Direct Segment Discovery Route length")
}
if len(data) == 12 {
address, ok := netip.AddrFromSlice(data[rdLen : rdLen+4])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Address: %s", data[rdLen:rdLen+4]))
}
r.Address = address
} else if len(data) == 24 {
address, ok := netip.AddrFromSlice(data[rdLen : rdLen+16])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Address: %d", data[rdLen:rdLen+16]))
}
r.Address = address
}
return nil
}
func (r *MUPDirectSegmentDiscoveryRoute) Serialize() ([]byte, error) {
var buf []byte
var err error
if r.RD != nil {
buf, err = r.RD.Serialize()
if err != nil {
return nil, err
}
} else {
buf = make([]byte, 8)
}
buf = append(buf, r.Address.AsSlice()...)
return buf, nil
}
func (r *MUPDirectSegmentDiscoveryRoute) AFI() uint16 {
if r.Address.Is6() {
return AFI_IP6
}
return AFI_IP
}
func (r *MUPDirectSegmentDiscoveryRoute) Len() int {
// RD(8) + Address(4 or 16)
return 8 + r.Address.BitLen()/8
}
func (r *MUPDirectSegmentDiscoveryRoute) String() string {
// I-D.draft-mpmz-bess-mup-safi-01
// 3.1.2. BGP Direct Segment Discovery route
// For the purpose of BGP route key processing, only the RD and Address are considered to be part of the prefix in the NLRI.
return fmt.Sprintf("[type:dsd][rd:%s][prefix:%s]", r.RD, r.Address)
}
func (r *MUPDirectSegmentDiscoveryRoute) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
RD RouteDistinguisherInterface `json:"rd"`
Address string `json:"address"`
}{
RD: r.RD,
Address: r.Address.String(),
})
}
func (r *MUPDirectSegmentDiscoveryRoute) rd() RouteDistinguisherInterface {
return r.RD
}
// MUPType1SessionTransformedRoute3GPP5G represents 3GPP 5G specific Type 1 Session Transformed (ST) Route as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-03#section-3.1.3
type MUPType1SessionTransformedRoute struct {
RD RouteDistinguisherInterface
Prefix netip.Prefix
TEID netip.Addr
QFI uint8
EndpointAddressLength uint8
EndpointAddress netip.Addr
SourceAddressLength uint8
SourceAddress *netip.Addr
}
func NewMUPType1SessionTransformedRoute(rd RouteDistinguisherInterface, prefix netip.Prefix, teid netip.Addr, qfi uint8, ea netip.Addr, sa *netip.Addr) *MUPNLRI {
afi := uint16(AFI_IP)
if prefix.Addr().Is6() {
afi = uint16(AFI_IP6)
}
r := &MUPType1SessionTransformedRoute{
RD: rd,
Prefix: prefix,
TEID: teid,
QFI: qfi,
EndpointAddressLength: uint8(ea.BitLen()),
EndpointAddress: ea,
}
if sa != nil {
r.SourceAddressLength = uint8(sa.BitLen())
r.SourceAddress = sa
}
return NewMUPNLRI(afi, MUP_ARCH_TYPE_3GPP_5G, MUP_ROUTE_TYPE_TYPE_1_SESSION_TRANSFORMED, r)
}
func (r *MUPType1SessionTransformedRoute) DecodeFromBytes(data []byte, afi uint16) error {
r.RD = GetRouteDistinguisher(data)
p := r.RD.Len()
if len(data) < p {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid 3GPP 5G specific Type 1 Session Transformed Route length")
}
prefixLength := int(data[p])
p += 1
addrLen := 0
switch afi {
case AFI_IP:
if prefixLength > 32 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Prefix length: %d", prefixLength))
}
addrLen = 4
case AFI_IP6:
if prefixLength > 128 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Prefix length: %d", prefixLength))
}
addrLen = 16
default:
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid AFI: %d", afi))
}
byteLen := (prefixLength + 7) / 8
b := make([]byte, addrLen)
copy(b[0:byteLen], data[p:p+byteLen])
addr, ok := netip.AddrFromSlice(b)
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Prefix: %x", b))
}
r.Prefix = netip.PrefixFrom(addr, prefixLength)
p += byteLen
r.TEID, ok = netip.AddrFromSlice(data[p : p+4])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid TEID: %x", r.TEID))
}
p += 4
r.QFI = data[p]
p += 1
r.EndpointAddressLength = data[p]
p += 1
if r.EndpointAddressLength == 32 || r.EndpointAddressLength == 128 {
ea, ok := netip.AddrFromSlice(data[p : p+int(r.EndpointAddressLength/8)])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Endpoint Address: %x", data[p:p+int(r.EndpointAddressLength/8)]))
}
r.EndpointAddress = ea
} else {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Endpoint Address length: %d", r.EndpointAddressLength))
}
p += int(r.EndpointAddressLength / 8)
r.SourceAddressLength = data[p]
p += 1
if r.SourceAddressLength == 32 || r.SourceAddressLength == 128 {
sa, ok := netip.AddrFromSlice(data[p : p+int(r.SourceAddressLength/8)])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Source Address: %x", data[p:p+int(r.SourceAddressLength/8)]))
}
r.SourceAddress = &sa
}
return nil
}
func (r *MUPType1SessionTransformedRoute) Serialize() ([]byte, error) {
var buf []byte
var err error
if r.RD != nil {
buf, err = r.RD.Serialize()
if err != nil {
return nil, err
}
} else {
buf = make([]byte, 8)
}
buf = append(buf, byte(r.Prefix.Bits()))
byteLen := (r.Prefix.Bits() + 7) / 8
buf = append(buf, r.Prefix.Addr().AsSlice()[:byteLen]...)
buf = append(buf, r.TEID.AsSlice()...)
buf = append(buf, r.QFI)
buf = append(buf, r.EndpointAddressLength)
buf = append(buf, r.EndpointAddress.AsSlice()...)
buf = append(buf, r.SourceAddressLength)
if r.SourceAddressLength > 0 {
buf = append(buf, r.SourceAddress.AsSlice()...)
}
return buf, nil
}
func (r *MUPType1SessionTransformedRoute) AFI() uint16 {
if r.Prefix.Addr().Is6() {
return AFI_IP6
}
return AFI_IP
}
func (r *MUPType1SessionTransformedRoute) Len() int {
// RD(8) + PrefixLength(1) + Prefix(variable)
// + TEID(4) + QFI(1) + EndpointAddressLength(1) + EndpointAddress(4 or 16) + SourceAddressLength(1) + SourceAddress(4 or 16)
l := 16 + (r.Prefix.Bits()+7)/8 + int(r.EndpointAddressLength/8)
if r.SourceAddressLength > 0 {
l += int(r.SourceAddressLength / 8)
}
return l
}
func (r *MUPType1SessionTransformedRoute) String() string {
// I-D.draft-mpmz-bess-mup-safi-01
// 3.1.3. BGP Type 1 Session Transformed (ST) Route
// For the purpose of BGP route key processing, only the RD, Prefix Length and Prefix are considered to be part of the prefix in the NLRI.
return fmt.Sprintf("[type:t1st][rd:%s][prefix:%s]", r.RD, r.Prefix)
}
func (r *MUPType1SessionTransformedRoute) MarshalJSON() ([]byte, error) {
d := struct {
RD RouteDistinguisherInterface `json:"rd"`
Prefix string `json:"prefix"`
TEID string `json:"teid"`
QFI uint8 `json:"qfi"`
EndpointAddress string `json:"endpoint_address"`
SourceAddress string `json:"source_address"`
}{
RD: r.RD,
Prefix: r.Prefix.String(),
TEID: r.TEID.String(),
QFI: r.QFI,
EndpointAddress: r.EndpointAddress.String(),
}
if r.SourceAddress != nil {
d.SourceAddress = r.SourceAddress.String()
}
return json.Marshal(d)
}
func (r *MUPType1SessionTransformedRoute) rd() RouteDistinguisherInterface {
return r.RD
}
// MUPType2SessionTransformedRoute represents 3GPP 5G specific Type 2 Session Transformed (ST) Route as described in
// https://datatracker.ietf.org/doc/html/draft-mpmz-bess-mup-safi-00#section-3.1.4
type MUPType2SessionTransformedRoute struct {
RD RouteDistinguisherInterface
EndpointAddressLength uint8
EndpointAddress netip.Addr
TEID netip.Addr
}
func NewMUPType2SessionTransformedRoute(rd RouteDistinguisherInterface, eaLen uint8, ea netip.Addr, teid netip.Addr) *MUPNLRI {
afi := uint16(AFI_IP)
if ea.Is6() {
afi = AFI_IP6
}
return NewMUPNLRI(afi, MUP_ARCH_TYPE_3GPP_5G, MUP_ROUTE_TYPE_TYPE_2_SESSION_TRANSFORMED, &MUPType2SessionTransformedRoute{
RD: rd,
EndpointAddressLength: eaLen,
EndpointAddress: ea,
TEID: teid,
})
}
func (r *MUPType2SessionTransformedRoute) DecodeFromBytes(data []byte, afi uint16) error {
r.RD = GetRouteDistinguisher(data)
p := r.RD.Len()
if len(data) < p {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid 3GPP 5G specific Type 2 Session Transformed Route length")
}
r.EndpointAddressLength = data[p]
if (afi == AFI_IP && r.EndpointAddressLength > 64) || (afi == AFI_IP6 && r.EndpointAddressLength > 160) {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Endpoint Address Length: %d", r.EndpointAddressLength))
}
p += 1
var ea netip.Addr
var ok bool
teidLen := 0
switch afi {
case AFI_IP:
ea, ok = netip.AddrFromSlice(data[p : p+4])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Endpoint Address: %x", data[p:p+int(r.EndpointAddressLength/8)]))
}
p += 4
teidLen = int(r.EndpointAddressLength) - 32
case AFI_IP6:
ea, ok = netip.AddrFromSlice(data[p : p+16])
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid Endpoint Address: %x", data[p:p+int(r.EndpointAddressLength/8)]))
}
p += 16
teidLen = int(r.EndpointAddressLength) - 128
default:
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid AFI: %d", afi))
}
r.EndpointAddress = ea
if teidLen > 0 {
l := (teidLen + 7) / 8
b := make([]byte, 4)
copy(b[:l], data[p:p+l])
a, ok := netip.AddrFromSlice(b)
if !ok {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid TEID: %x", data[p:p+l]))
}
r.TEID = a
} else {
r.TEID = netip.AddrFrom4([4]byte{0, 0, 0, 0})
}
return nil
}
func (r *MUPType2SessionTransformedRoute) Serialize() ([]byte, error) {
var buf []byte
var err error
if r.RD != nil {
buf, err = r.RD.Serialize()
if err != nil {
return nil, err
}
} else {
buf = make([]byte, 8)
}
buf = append(buf, r.EndpointAddressLength)
buf = append(buf, r.EndpointAddress.AsSlice()...)
teidLen := int(r.EndpointAddressLength) - r.EndpointAddress.BitLen()
if teidLen > 0 {
byteLen := (teidLen + 7) / 8
buf = append(buf, r.TEID.AsSlice()[:byteLen]...)
}
return buf, nil
}
func (r *MUPType2SessionTransformedRoute) AFI() uint16 {
if r.EndpointAddress.Is6() {
return AFI_IP6
}
return AFI_IP
}
func (r *MUPType2SessionTransformedRoute) Len() int {
// RD(8) + EndpointAddressLength(1) + EndpointAddress(4 or 16)
// + TEID(4)
// Endpoint Address Length includes TEID Length
return 9 + int(r.EndpointAddressLength+7)/8
}
func (r *MUPType2SessionTransformedRoute) String() string {
// I-D.draft-mpmz-bess-mup-safi-01
// 3.1.4. BGP Type 2 Session Transformed (ST) Route
// For the purpose of BGP route key processing, only the RD, Endpoint Address and Architecture specific Endpoint Identifier are considered to be part of the prefix in the NLRI.
return fmt.Sprintf("[type:t2st][rd:%s][endpoint-address-length:%d][endpoint:%s][teid:%s]", r.RD, r.EndpointAddressLength, r.EndpointAddress, r.TEID)
}
func (r *MUPType2SessionTransformedRoute) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
RD RouteDistinguisherInterface `json:"rd"`
EndpointAddressLength uint8 `json:"endpoint_address_length"`
EndpointAddress string `json:"endpoint_address"`
TEID string `json:"teid"`
}{
RD: r.RD,
EndpointAddressLength: r.EndpointAddressLength,
EndpointAddress: r.EndpointAddress.String(),
TEID: r.TEID.String(),
})
}
func (r *MUPType2SessionTransformedRoute) rd() RouteDistinguisherInterface {
return r.RD
}
@@ -1,694 +0,0 @@
package bgp
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"net"
"net/netip"
)
const (
prefixSIDtlvHdrLen = 4
)
// BGP Prefix-SID TLV Types
// https://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml#bgp-prefix-sid-tlv-types
type TLVType uint8
const (
_ TLVType = iota // Reserved
TLVTypeLavelIndex
_ // Deprecated
TLVTypeOriginatorSRGB
_ // Deprecated
TLVTypeSRv6L3Service
TLVTypeSRv6L2Service
)
type TLV struct {
Type TLVType
Length uint16
}
func (t *TLV) Len() int {
return int(t.Length) + 3 // Type(1) + Length(2)
}
func (t *TLV) Serialize(value []byte) ([]byte, error) {
if len(value) != int(t.Len()) {
return nil, malformedAttrListErr("serialization failed: Prefix SID TLV malformed")
}
p := 0
value[p] = byte(t.Type)
p++
binary.BigEndian.PutUint16(value[p:p+2], uint16(t.Length))
return value, nil
}
func (t *TLV) DecodeFromBytes(data []byte) ([]byte, error) {
if len(data) < 3 {
return nil, malformedAttrListErr("decoding failed: Prefix SID TLV malformed")
}
p := 0
t.Type = TLVType(data[p])
p++
t.Length = binary.BigEndian.Uint16(data[p : p+2])
p += 2
if len(data[p:]) < int(t.Length) {
return nil, malformedAttrListErr("decoding failed: Prefix SID TLV malformed")
}
return data[p : p+int(t.Length)], nil
}
// PrefixSIDTLVInterface defines standard set of methods to handle Prefix SID attribute's TLVs
type PrefixSIDTLVInterface interface {
Len() int
DecodeFromBytes([]byte) error
Serialize() ([]byte, error)
String() string
MarshalJSON() ([]byte, error)
}
type PrefixSIDAttribute struct {
TLVs []PrefixSIDTLVInterface
}
type PathAttributePrefixSID struct {
PathAttribute
TLVs []PrefixSIDTLVInterface
}
func NewPathAttributePrefixSID(values ...PrefixSIDTLVInterface) *PathAttributePrefixSID {
var l int
for _, v := range values {
l += v.Len()
}
return &PathAttributePrefixSID{
PathAttribute: PathAttribute{
Flags: getPathAttrFlags(BGP_ATTR_TYPE_PREFIX_SID, l),
Type: BGP_ATTR_TYPE_PREFIX_SID,
Length: uint16(l),
},
TLVs: values,
}
}
func (p *PathAttributePrefixSID) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
tlvs, err := p.PathAttribute.DecodeFromBytes(data)
if err != nil {
return err
}
for len(tlvs) >= prefixSIDtlvHdrLen {
t := &TLV{}
_, err := t.DecodeFromBytes(tlvs)
if err != nil {
return err
}
var tlv PrefixSIDTLVInterface
switch t.Type {
case TLVTypeSRv6L3Service, TLVTypeSRv6L2Service:
tlv = &SRv6ServiceTLV{
SubTLVs: make([]PrefixSIDTLVInterface, 0),
}
default:
tlvs = tlvs[t.Len():]
continue
}
if err := tlv.DecodeFromBytes(tlvs); err != nil {
return err
}
tlvs = tlvs[t.Len():]
p.TLVs = append(p.TLVs, tlv)
}
return nil
}
func (p *PathAttributePrefixSID) Serialize(options ...*MarshallingOption) ([]byte, error) {
buf := make([]byte, 0)
for _, tlv := range p.TLVs {
s, err := tlv.Serialize()
if err != nil {
return nil, err
}
buf = append(buf, s...)
}
return p.PathAttribute.Serialize(buf)
}
func (p *PathAttributePrefixSID) String() string {
var buf bytes.Buffer
for _, tlv := range p.TLVs {
buf.WriteString(fmt.Sprintf("%s ", tlv.String()))
}
return fmt.Sprintf("{Prefix SID attributes: %s}", buf.String())
}
func (p *PathAttributePrefixSID) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type BGPAttrType `json:"type"`
Flags BGPAttrFlag `json:"flags"`
PrefixSIDAttribute
}{
p.GetType(),
p.GetFlags(),
*p.Extract(),
})
}
func (p *PathAttributePrefixSID) Extract() *PrefixSIDAttribute {
psid := &PrefixSIDAttribute{
TLVs: make([]PrefixSIDTLVInterface, 0),
}
psid.TLVs = append(psid.TLVs, p.TLVs...)
return psid
}
// SRv6L3Service defines the structure of SRv6 L3 Service object
type SRv6L3Service struct {
SubTLVs []PrefixSIDTLVInterface
}
// SRv6L3ServiceAttribute defines the structure of SRv6 L3 Service attribute
// Deprecated: Use SRv6ServiceTLV instead.
type SRv6L3ServiceAttribute struct {
TLV
SubTLVs []PrefixSIDTLVInterface
}
func (s *SRv6L3ServiceAttribute) Len() int {
return int(s.Length) + prefixSIDtlvHdrLen
}
func (s *SRv6L3ServiceAttribute) Serialize() ([]byte, error) {
buf := make([]byte, s.Length+3)
p := 4
for _, tlv := range s.SubTLVs {
s, err := tlv.Serialize()
if err != nil {
return nil, err
}
copy(buf[p:p+len(s)], s)
p += len(s)
}
return s.TLV.Serialize(buf)
}
func (s *SRv6L3ServiceAttribute) DecodeFromBytes(data []byte) error {
stlvs, err := s.TLV.DecodeFromBytes(data)
if err != nil {
return err
}
stlvs = stlvs[1:] // RESERVED(1)
for len(stlvs) >= subTLVHdrLen {
t := &SubTLV{}
_, err := t.DecodeFromBytes(stlvs)
if err != nil {
return err
}
var stlv PrefixSIDTLVInterface
switch t.Type {
case 1:
stlv = &SRv6InformationSubTLV{
SubSubTLVs: make([]PrefixSIDTLVInterface, 0),
}
default:
data = data[t.Len():]
continue
}
if err := stlv.DecodeFromBytes(stlvs); err != nil {
return err
}
stlvs = stlvs[t.Len():]
s.SubTLVs = append(s.SubTLVs, stlv)
}
return nil
}
func (s *SRv6L3ServiceAttribute) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type TLVType `json:"type"`
SRv6L3Service
}{
s.Type,
*s.Extract(),
})
}
func (s *SRv6L3ServiceAttribute) String() string {
var buf bytes.Buffer
for _, tlv := range s.SubTLVs {
buf.WriteString(fmt.Sprintf("%s ", tlv.String()))
}
return fmt.Sprintf("{SRv6 L3 Service Attribute: %s}", buf.String())
}
func (s *SRv6L3ServiceAttribute) Extract() *SRv6L3Service {
l3 := &SRv6L3Service{
SubTLVs: make([]PrefixSIDTLVInterface, 0),
}
l3.SubTLVs = append(l3.SubTLVs, s.SubTLVs...)
return l3
}
const (
subTLVHdrLen = 3
)
type SubTLVType uint8
type SubTLV struct {
Type SubTLVType
Length uint16
}
func (s *SubTLV) Len() int {
return int(s.Length) + subTLVHdrLen
}
func (s *SubTLV) Serialize(value []byte) ([]byte, error) {
if len(value) != int(s.Length) {
return nil, malformedAttrListErr("serialization failed: Prefix SID TLV malformed")
}
// Extra byte is reserved
buf := make([]byte, subTLVHdrLen+len(value))
buf[0] = byte(s.Type)
binary.BigEndian.PutUint16(buf[1:4], uint16(s.Length))
// 4th reserved byte
copy(buf[4:], value)
return buf, nil
}
func (s *SubTLV) DecodeFromBytes(data []byte) ([]byte, error) {
if len(data) < subTLVHdrLen {
return nil, malformedAttrListErr("decoding failed: Prefix SID Sub TLV malformed")
}
s.Type = SubTLVType(data[0])
s.Length = binary.BigEndian.Uint16(data[1:3])
if len(data) < s.Len() {
return nil, malformedAttrListErr("decoding failed: Prefix SID Sub TLV malformed")
}
return data[subTLVHdrLen:s.Len()], nil
}
type SRv6InformationSTLV struct {
SID []byte `json:"sid"`
Flags uint8 `json:"flags"`
EndpointBehavior uint16 `json:"endpoint_behavior"`
SubSubTLVs []PrefixSIDTLVInterface `json:"sub_sub_tlvs,omitempty"`
}
// SRv6InformationSubTLV defines a structure of SRv6 Information Sub TLV (type 1) object
// https://tools.ietf.org/html/draft-dawra-bess-srv6-services-02#section-2.1.1
type SRv6InformationSubTLV struct {
SubTLV
SID []byte
Flags uint8
EndpointBehavior uint16
SubSubTLVs []PrefixSIDTLVInterface
}
func NewSRv6InformationSubTLV(sid netip.Addr, behavior SRBehavior, values ...PrefixSIDTLVInterface) *SRv6InformationSubTLV {
l := 21 // RESERVED1(1) + SID(16) + Flags(1) + Endpoint Behavior(2) + RESERVED2(1)
for _, v := range values {
l += v.Len()
}
return &SRv6InformationSubTLV{
SubTLV: SubTLV{
Type: 1,
Length: uint16(l),
},
SID: sid.AsSlice(),
Flags: 0,
EndpointBehavior: uint16(behavior),
SubSubTLVs: values,
}
}
func (s *SRv6InformationSubTLV) Len() int {
return int(s.Length) + subTLVHdrLen
}
func (s *SRv6InformationSubTLV) Serialize() ([]byte, error) {
buf := make([]byte, s.Length)
p := 0
copy(buf[p:], s.SID)
p += len(s.SID)
buf[p] = byte(s.Flags)
p++
binary.BigEndian.PutUint16(buf[p:p+2], uint16(s.EndpointBehavior))
p += 2
// Reserved byte
buf[p] = 0x0
p++
for _, sstlv := range s.SubSubTLVs {
sbuf, err := sstlv.Serialize()
if err != nil {
return nil, err
}
copy(buf[p:], sbuf)
p += len(sbuf)
}
return s.SubTLV.Serialize(buf)
}
func (s *SRv6InformationSubTLV) DecodeFromBytes(data []byte) error {
if len(data) < subTLVHdrLen {
return malformedAttrListErr("decoding failed: Prefix SID TLV malformed")
}
s.Type = SubTLVType(data[0])
s.Length = binary.BigEndian.Uint16(data[1:3])
// 4th reserved byte
p := 4
s.SID = make([]byte, 16)
copy(s.SID, data[p:p+16])
p += 16
s.Flags = uint8(data[p])
p++
s.EndpointBehavior = binary.BigEndian.Uint16(data[p : p+2])
p += 2
// reserved byte
p++
if p+3 > len(data) {
// There is no Sub Sub TLVs detected, returning
return nil
}
stlvs := data[p:]
for len(stlvs) >= prefixSIDtlvHdrLen {
t := &SubSubTLV{}
_, err := t.DecodeFromBytes(stlvs)
if err != nil {
return err
}
var sstlv PrefixSIDTLVInterface
switch t.Type {
case 1:
sstlv = &SRv6SIDStructureSubSubTLV{}
default:
stlvs = stlvs[t.Len():]
continue
}
if err := sstlv.DecodeFromBytes(stlvs); err != nil {
return err
}
stlvs = stlvs[t.Len():]
s.SubSubTLVs = append(s.SubSubTLVs, sstlv)
}
return nil
}
func (s *SRv6InformationSubTLV) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type SubTLVType `json:"type"`
SRv6InformationSTLV
}{
s.Type,
*s.Extract(),
})
}
func (s *SRv6InformationSubTLV) String() string {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("SID: %s ", net.IP(s.SID).To16().String()))
buf.WriteString(fmt.Sprintf("Flag: %d ", s.Flags))
buf.WriteString(fmt.Sprintf("Endpoint Behavior: %d ", s.EndpointBehavior))
for _, tlv := range s.SubSubTLVs {
buf.WriteString(fmt.Sprintf("%s ", tlv.String()))
}
return fmt.Sprintf("{SRv6 Information Sub TLV: %s}", buf.String())
}
func (s *SRv6InformationSubTLV) Extract() *SRv6InformationSTLV {
info := &SRv6InformationSTLV{
SID: s.SID,
Flags: s.Flags,
EndpointBehavior: s.EndpointBehavior,
SubSubTLVs: make([]PrefixSIDTLVInterface, 0),
}
info.SubSubTLVs = append(info.SubSubTLVs, s.SubSubTLVs...)
return info
}
const (
subSubTLVHdrLen = 3
)
type SubSubTLVType uint8
type SubSubTLV struct {
Type SubSubTLVType
Length uint16
}
func (s *SubSubTLV) Len() int {
return int(s.Length) + subSubTLVHdrLen
}
func (s *SubSubTLV) Serialize(value []byte) ([]byte, error) {
if len(value) != int(s.Length) {
return nil, malformedAttrListErr("serialization failed: Prefix SID TLV malformed")
}
// Extra byte is reserved
buf := make([]byte, subSubTLVHdrLen+len(value))
p := 0
buf[p] = byte(s.Type)
p++
binary.BigEndian.PutUint16(buf[p:p+2], uint16(s.Length))
p += 2
copy(buf[p:], value)
return buf, nil
}
func (s *SubSubTLV) DecodeFromBytes(data []byte) ([]byte, error) {
if len(data) < prefixSIDtlvHdrLen {
return nil, malformedAttrListErr("decoding failed: Prefix SID Sub Sub TLV malformed")
}
s.Type = SubSubTLVType(data[0])
s.Length = binary.BigEndian.Uint16(data[1:3])
if len(data) < s.Len() {
return nil, malformedAttrListErr("decoding failed: Prefix SID Sub Sub TLV malformed")
}
return data[prefixSIDtlvHdrLen:s.Len()], nil
}
// SRv6SIDStructureSubSubTLV defines a structure of SRv6 SID Structure Sub Sub TLV (type 1) object
// https://www.rfc-editor.org/rfc/rfc9252.html#section-3.2.1
type SRv6SIDStructureSubSubTLV struct {
SubSubTLV
LocatorBlockLength uint8
LocatorNodeLength uint8
FunctionLength uint8
ArgumentLength uint8
TranspositionLength uint8
TranspositionOffset uint8
}
func NewSRv6SIDStructureSubSubTLV(lbl, lnl, fl, al, tl, to uint8) *SRv6SIDStructureSubSubTLV {
return &SRv6SIDStructureSubSubTLV{
SubSubTLV: SubSubTLV{
Type: 1,
Length: 6,
},
LocatorBlockLength: lbl,
LocatorNodeLength: lnl,
FunctionLength: fl,
ArgumentLength: al,
TranspositionLength: tl,
TranspositionOffset: to,
}
}
func (s *SRv6SIDStructureSubSubTLV) Len() int {
return int(s.Length) + subSubTLVHdrLen
}
func (s *SRv6SIDStructureSubSubTLV) Serialize() ([]byte, error) {
buf := make([]byte, s.Length)
p := 0
buf[p] = s.LocatorBlockLength
p++
buf[p] = s.LocatorNodeLength
p++
buf[p] = s.FunctionLength
p++
buf[p] = s.ArgumentLength
p++
buf[p] = s.TranspositionLength
p++
buf[p] = s.TranspositionOffset
return s.SubSubTLV.Serialize(buf)
}
func (s *SRv6SIDStructureSubSubTLV) DecodeFromBytes(data []byte) error {
if len(data) < subSubTLVHdrLen {
return malformedAttrListErr("decoding failed: Prefix SID Sub Sub TLV malformed")
}
s.Type = SubSubTLVType(data[0])
s.Length = binary.BigEndian.Uint16(data[1:3])
s.LocatorBlockLength = data[3]
s.LocatorNodeLength = data[4]
s.FunctionLength = data[5]
s.ArgumentLength = data[6]
s.TranspositionLength = data[7]
s.TranspositionOffset = data[8]
return nil
}
func (s *SRv6SIDStructureSubSubTLV) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type SubSubTLVType `json:"type"`
LocatorBlockLength uint8 `json:"locator_block_length"`
LocatorNodeLength uint8 `json:"locator_node_length"`
FunctionLength uint8 `json:"function_length"`
ArgumentLength uint8 `json:"argument_length"`
TranspositionLength uint8 `json:"transposition_length"`
TranspositionOffset uint8 `json:"transposition_offset"`
}{
Type: s.Type,
LocatorBlockLength: s.LocatorBlockLength,
LocatorNodeLength: s.LocatorNodeLength,
FunctionLength: s.FunctionLength,
ArgumentLength: s.ArgumentLength,
TranspositionLength: s.TranspositionLength,
TranspositionOffset: s.TranspositionOffset,
})
}
func (s *SRv6SIDStructureSubSubTLV) String() string {
return fmt.Sprintf("{SRv6 Structure Sub Sub TLV: [ Locator Block Length: %d, Locator Node Length: %d, Function Length: %d, Argument Length: %d, Transposition Length: %d, Transposition Offset: %d] }",
s.LocatorBlockLength,
s.LocatorNodeLength,
s.FunctionLength,
s.ArgumentLength,
s.TranspositionLength,
s.TranspositionOffset,
)
}
// SRv6ServiceTLV represents SRv6 Service TLV.
// https://www.rfc-editor.org/rfc/rfc9252.html#section-2
type SRv6ServiceTLV struct {
TLV
SubTLVs []PrefixSIDTLVInterface
}
func NewSRv6ServiceTLV(t TLVType, values ...PrefixSIDTLVInterface) *SRv6ServiceTLV {
l := 1 // RESERVED(1)
for _, v := range values {
l += v.Len()
}
return &SRv6ServiceTLV{
TLV: TLV{
Type: t,
Length: uint16(l),
},
SubTLVs: values,
}
}
func (s *SRv6ServiceTLV) Len() int {
return int(s.Length) + 3 // Type(1) + Length(2)
}
func (t *SRv6ServiceTLV) Serialize() ([]byte, error) {
buf := make([]byte, t.Len())
p := 4
for _, tlv := range t.SubTLVs {
b, err := tlv.Serialize()
if err != nil {
return nil, err
}
copy(buf[p:p+len(b)], b)
p += len(b)
}
return t.TLV.Serialize(buf)
}
func (s *SRv6ServiceTLV) DecodeFromBytes(data []byte) error {
stlvs, err := s.TLV.DecodeFromBytes(data)
if err != nil {
return err
}
stlvs = stlvs[1:] // RESERVED(1)
for len(stlvs) >= subTLVHdrLen {
t := &SubTLV{}
_, err := t.DecodeFromBytes(stlvs)
if err != nil {
return err
}
var stlv PrefixSIDTLVInterface
switch t.Type {
case 1:
stlv = &SRv6InformationSubTLV{
SubSubTLVs: make([]PrefixSIDTLVInterface, 0),
}
default:
data = data[t.Len():]
continue
}
if err := stlv.DecodeFromBytes(stlvs); err != nil {
return err
}
stlvs = stlvs[t.Len():]
s.SubTLVs = append(s.SubTLVs, stlv)
}
return nil
}
func (t *SRv6ServiceTLV) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type TLVType `json:"type"`
SubTLVs []PrefixSIDTLVInterface
}{
t.Type,
t.SubTLVs,
})
}
func (t *SRv6ServiceTLV) String() string {
var buf bytes.Buffer
for _, tlv := range t.SubTLVs {
buf.WriteString(fmt.Sprintf("%s ", tlv.String()))
}
return fmt.Sprintf("{SRv6 Service TLV: %s}", buf.String())
}
-927
View File
@@ -1,927 +0,0 @@
package bgp
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
"strconv"
)
type SRPolicyNLRI struct {
PrefixDefault
rf RouteFamily
Length uint8
Distinguisher uint32
Color uint32
Endpoint []byte
}
const (
// SRPolicyIPv4NLRILen defines IPv4 SR Policy NLRI portion length in bits
SRPolicyIPv4NLRILen = 96
// SRPolicyIPv6NLRILen defines IPv6 SR Policy NLRI portion length in bits
SRPolicyIPv6NLRILen = 192
)
func (s *SRPolicyNLRI) Flat() map[string]string {
return map[string]string{}
}
func (s *SRPolicyNLRI) decodeFromBytes(rf RouteFamily, data []byte, options ...*MarshallingOption) error {
if IsAddPathEnabled(true, rf, options) {
var err error
data, err = s.decodePathIdentifier(data)
if err != nil {
return err
}
}
switch data[0] {
case SRPolicyIPv4NLRILen:
s.rf = RF_SR_POLICY_IPv4
case SRPolicyIPv6NLRILen:
s.rf = RF_SR_POLICY_IPv6
default:
msg := fmt.Sprintf("Invalid length %d for SR Policy NLRI", len(data))
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
p := 0
s.Length = data[p] / 8
p++
s.Distinguisher = binary.BigEndian.Uint32(data[p : p+4])
p += 4
s.Color = binary.BigEndian.Uint32(data[p : p+4])
p += 4
s.Endpoint = data[p:]
return nil
}
func (s *SRPolicyNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
buf := make([]byte, 1+s.Length)
p := 0
buf[0] = s.Length * 8
p++
binary.BigEndian.PutUint32(buf[p:p+4], s.Distinguisher)
p += 4
binary.BigEndian.PutUint32(buf[p:p+4], s.Color)
p += 4
copy(buf[p:], s.Endpoint)
if IsAddPathEnabled(false, s.rf, options) {
id, err := s.serializeIdentifier()
if err != nil {
return nil, err
}
return append(id, buf...), nil
}
return buf, nil
}
func (s *SRPolicyNLRI) AFI() uint16 {
afi, _ := RouteFamilyToAfiSafi(s.rf)
return afi
}
func (s *SRPolicyNLRI) SAFI() uint8 {
_, safi := RouteFamilyToAfiSafi(s.rf)
return safi
}
func (s *SRPolicyNLRI) Len(options ...*MarshallingOption) int {
buf, _ := s.Serialize(options...)
return len(buf)
}
func (s *SRPolicyNLRI) String() string {
afi, _ := RouteFamilyToAfiSafi(s.rf)
var endp string
switch afi {
case AFI_IP:
endp = net.IP(s.Endpoint).To4().String()
case AFI_IP6:
endp = net.IP(s.Endpoint).To16().String()
default:
endp = "[" + string(s.Endpoint) + "]"
}
return fmt.Sprintf("{ Length: %d (bytes), Distinguisher: %d, Color %d, Endpoint: %s }", s.Length, s.Distinguisher, s.Color, endp)
}
func (s *SRPolicyNLRI) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Length uint8 `json:"length"`
Distinguisher uint32 `json:"distinguisher"`
Color uint32 `json:"color"`
Endpoint string `json:"endpoint"`
}{
Length: s.Length,
Distinguisher: s.Distinguisher,
Color: s.Color,
Endpoint: string(s.Endpoint),
})
}
type SRPolicyIPv4 struct {
SRPolicyNLRI
}
func (s *SRPolicyIPv4) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
return s.decodeFromBytes(s.rf, data)
}
func NewSRPolicyIPv4(l uint32, d uint32, c uint32, ep []byte) *SRPolicyIPv4 {
return &SRPolicyIPv4{
SRPolicyNLRI: SRPolicyNLRI{
rf: RF_SR_POLICY_IPv4,
Length: uint8(l / 8),
Distinguisher: d,
Color: c,
Endpoint: ep,
},
}
}
type SRPolicyIPv6 struct {
SRPolicyNLRI
}
func (s *SRPolicyIPv6) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
return s.decodeFromBytes(s.rf, data)
}
func NewSRPolicyIPv6(l uint32, d uint32, c uint32, ep []byte) *SRPolicyIPv6 {
return &SRPolicyIPv6{
SRPolicyNLRI: SRPolicyNLRI{
rf: RF_SR_POLICY_IPv6,
Length: uint8(l / 8),
Distinguisher: d,
Color: c,
Endpoint: ep,
},
}
}
type TunnelEncapSubTLVSRPreference struct {
TunnelEncapSubTLV
Flags uint8
Preference uint32
}
func (t *TunnelEncapSubTLVSRPreference) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Second byte carries the length of SR Preference SubTLV
if t.Length != 6 {
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRPreference length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Flags = value[0]
t.Preference = binary.BigEndian.Uint32(value[2:6])
return nil
}
func (t *TunnelEncapSubTLVSRPreference) Serialize() ([]byte, error) {
buf := make([]byte, 6)
buf[0] = t.Flags
binary.BigEndian.PutUint32(buf[2:6], t.Preference)
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRPreference) String() string {
return fmt.Sprintf("{Flags: 0x%02x, Preference: %d}", t.Flags, t.Preference)
}
func (t *TunnelEncapSubTLVSRPreference) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
Preference uint32 `json:"preference"`
}{
Type: t.Type,
Flags: t.Flags,
Preference: t.Preference,
})
}
func NewTunnelEncapSubTLVSRPreference(flags uint32, preference uint32) *TunnelEncapSubTLVSRPreference {
return &TunnelEncapSubTLVSRPreference{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRPREFERENCE,
Length: 6,
},
Flags: uint8(flags),
Preference: preference,
}
}
type TunnelEncapSubTLVSRPriority struct {
TunnelEncapSubTLV
Priority uint8
}
func (t *TunnelEncapSubTLVSRPriority) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Second byte carries the length of SR Preference SubTLV
if t.Length != 2 {
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRPriority length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Priority = value[0]
return nil
}
func (t *TunnelEncapSubTLVSRPriority) Serialize() ([]byte, error) {
buf := make([]byte, 1+1)
buf[0] = t.Priority
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRPriority) String() string {
return fmt.Sprintf("{Priority: %d}", t.Priority)
}
func (t *TunnelEncapSubTLVSRPriority) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Priority uint8 `json:"priority"`
}{
Type: t.Type,
Priority: t.Priority,
})
}
func NewTunnelEncapSubTLVSRPriority(priority uint8) *TunnelEncapSubTLVSRPriority {
return &TunnelEncapSubTLVSRPriority{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRPRIORITY,
Length: 2,
},
Priority: priority,
}
}
type TunnelEncapSubTLVSRCandidatePathName struct {
TunnelEncapSubTLV
CandidatePathName string
}
func (t *TunnelEncapSubTLVSRCandidatePathName) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Skip Reserved byte
t.CandidatePathName = string(value[1:t.TunnelEncapSubTLV.Len()])
return nil
}
func (t *TunnelEncapSubTLVSRCandidatePathName) Serialize() ([]byte, error) {
buf := make([]byte, 1+len(t.CandidatePathName))
copy(buf[1:], t.CandidatePathName)
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRCandidatePathName) String() string {
return fmt.Sprintf("{Candidate Path Name: %s}", t.CandidatePathName)
}
func (t *TunnelEncapSubTLVSRCandidatePathName) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
CandidatePathName string `json:"candidate_path_name"`
}{
Type: t.Type,
CandidatePathName: t.CandidatePathName,
})
}
func NewTunnelEncapSubTLVSRCandidatePathName(cpn string) *TunnelEncapSubTLVSRCandidatePathName {
return &TunnelEncapSubTLVSRCandidatePathName{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME,
Length: uint16(len(cpn) + 1), // length of Candidate Path name string + 1 Reserved byte
},
CandidatePathName: cpn,
}
}
type SRENLPValue uint8
const (
// ENLPType1 Indicates to push an IPv4 Explicit NULL label on an unlabeled IPv4
// packet, but do not push an IPv6 Explicit NULL label on an
// unlabeled IPv6 packet.
ENLPType1 SRENLPValue = 1
// ENLPType2 Indicates to push an IPv6 Explicit NULL label on an unlabeled IPv6
// packet, but do not push an IPv4 Explicit NULL label on an
// unlabeled IPv4 packet.
ENLPType2 SRENLPValue = 2
// ENLPType3 Indicates to push an IPv4 Explicit NULL label on an unlabeled IPv4
// packet, and push an IPv6 Explicit NULL label on an unlabeled
// IPv6 packet.
ENLPType3 SRENLPValue = 3
// ENLPType4 Indicates to not push an Explicit NULL label.
ENLPType4 SRENLPValue = 4
)
type TunnelEncapSubTLVSRENLP struct {
TunnelEncapSubTLV
Flags uint8
ENLP SRENLPValue
}
func (t *TunnelEncapSubTLVSRENLP) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Second byte carries the length of SR Preference SubTLV
if t.Length != 3 {
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRENLP length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Flags = value[0]
switch SRENLPValue(value[2]) {
case ENLPType1:
case ENLPType2:
case ENLPType3:
case ENLPType4:
default:
msg := fmt.Sprintf("Invalid ENLP Type: %d", value[2])
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.ENLP = SRENLPValue(value[2])
return nil
}
func (t *TunnelEncapSubTLVSRENLP) Serialize() ([]byte, error) {
buf := make([]byte, t.Length)
buf[0] = t.Flags
buf[2] = byte(t.ENLP)
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRENLP) String() string {
return fmt.Sprintf("{Flags: 0x%02x, ENLP Type: %d}", t.Flags, t.ENLP)
}
func (t *TunnelEncapSubTLVSRENLP) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
ENLP uint8 `json:"enlp"`
}{
Type: t.Type,
Flags: t.Flags,
ENLP: uint8(t.ENLP),
})
}
func NewTunnelEncapSubTLVSRENLP(flags uint32, enlp SRENLPValue) *TunnelEncapSubTLVSRENLP {
return &TunnelEncapSubTLVSRENLP{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRENLP,
Length: 3,
},
Flags: uint8(flags),
ENLP: enlp,
}
}
type BSID struct {
Value []byte
}
func (b *BSID) String() string {
switch len(b.Value) {
case 0:
return "n/a"
case 4:
bsid := binary.BigEndian.Uint32(b.Value)
bsid >>= 12
return strconv.Itoa(int(bsid))
case 16:
return net.IP(b.Value).To16().String()
default:
return "invalid"
}
}
func (b *BSID) Serialize() []byte {
return b.Value
}
func (b *BSID) Len() int {
return len(b.Value)
}
func NewBSID(v []byte) (*BSID, error) {
var bsid *BSID
switch len(v) {
case 0:
case 4:
t := binary.BigEndian.Uint32(v)
t <<= 12
bsid = &BSID{
Value: make([]byte, len(v)),
}
binary.BigEndian.PutUint32(bsid.Value, t)
case 16:
bsid = &BSID{
Value: make([]byte, len(v)),
}
copy(bsid.Value, v)
default:
return nil, fmt.Errorf("invalid length %d", len(v))
}
return bsid, nil
}
type TunnelEncapSubTLVSRBSID struct {
TunnelEncapSubTLV
Flags uint8
BSID *BSID
}
func (t *TunnelEncapSubTLVSRBSID) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
// Check Sub TLV length, only 3 possible length are allowed
switch t.Length {
case 2: // No BSID, do not initializing BSID struct
case 6:
fallthrough
case 18:
t.BSID = &BSID{
Value: make([]byte, t.Length-2),
}
copy(t.BSID.Value, value[2:t.Length])
default:
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRBSID length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Flags = value[0]
return nil
}
func (t *TunnelEncapSubTLVSRBSID) Serialize() ([]byte, error) {
l := 2
if t.BSID != nil {
l += t.BSID.Len()
}
buf := make([]byte, l) // 1st byte Flags, 2nd byte Reserved, 3rd+ BSID
buf[0] = t.Flags
if t.BSID != nil {
bsid := t.BSID.Serialize()
copy(buf[2:], bsid)
}
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRBSID) String() string {
return fmt.Sprintf("{S-Flag: %t, I-Flag: %t, BSID: %s}", t.Flags&0x80 == 0x80, t.Flags&0x40 == 0x40, t.BSID.String())
}
func (t *TunnelEncapSubTLVSRBSID) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
BSID string `json:"binding_sid,omitempty"`
}{
Type: t.Type,
Flags: t.Flags,
BSID: t.BSID.String(),
})
}
type TunnelEncapSubTLVSRv6BSID struct {
TunnelEncapSubTLV
Flags uint8
BSID *BSID
EPBAS *SRv6EndpointBehaviorStructure
}
func (t *TunnelEncapSubTLVSRv6BSID) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
t.Flags = value[0]
t.BSID, err = NewBSID(value[2:t.Length])
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
return nil
}
func (t *TunnelEncapSubTLVSRv6BSID) Serialize() ([]byte, error) {
buf := make([]byte, t.Length)
buf[0] = t.Flags
copy(buf[2:t.BSID.Len()], t.BSID.Serialize())
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRv6BSID) String() string {
return fmt.Sprintf("{S-Flag: %t, I-Flag: %t, B-Flag: %t, BSID: %s}", t.Flags&0x80 == 0x80, t.Flags&0x40 == 0x40, t.Flags&0x20 == 0x20, t.BSID.String())
}
func (t *TunnelEncapSubTLVSRv6BSID) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
BSID string `json:"binding_sid,omitempty"`
}{
Type: t.Type,
Flags: t.Flags,
BSID: t.BSID.String(),
})
}
// SegmentType defines a type of Segment in Segment List
type SegmentType int
const (
// TypeA Segment Sub-TLV encodes a single SR-MPLS SID
TypeA SegmentType = 1
// TypeB Segment Sub-TLV encodes a single SRv6 SID.
TypeB SegmentType = 13
// TypeC Segment Sub-TLV encodes an IPv4 node address, SR Algorithm
// and an optional SR-MPLS SID
TypeC SegmentType = 3
// TypeD Segment Sub-TLV encodes an IPv6 node address, SR Algorithm
// and an optional SR-MPLS SID.
TypeD SegmentType = 4
// TypeE Segment Sub-TLV encodes an IPv4 node address, a local
// interface Identifier (Local Interface ID) and an optional SR-MPLS
// SID.
TypeE SegmentType = 5
// TypeF Segment Sub-TLV encodes an adjacency local address, an
// adjacency remote address and an optional SR-MPLS SID.
TypeF SegmentType = 6
// TypeG Segment Sub-TLV encodes an IPv6 Link Local adjacency with
// IPv6 local node address, a local interface identifier (Local
// Interface ID), IPv6 remote node address , a remote interface
// identifier (Remote Interface ID) and an optional SR-MPLS SID.
TypeG SegmentType = 7
// TypeH Segment Sub-TLV encodes an adjacency local address, an
// adjacency remote address and an optional SR-MPLS SID.
TypeH SegmentType = 8
// TypeI Segment Sub-TLV encodes an IPv6 node address, SR Algorithm
// and an optional SRv6 SID.
TypeI SegmentType = 14
// TypeJ Segment Sub-TLV encodes an IPv6 Link Local adjacency with
// local node address, a local interface identifier (Local Interface
// ID), remote IPv6 node address, a remote interface identifier (Remote
// Interface ID) and an optional SRv6 SID.
TypeJ SegmentType = 15
// TypeK Segment Sub-TLV encodes an adjacency local address, an
// adjacency remote address and an optional SRv6 SID.
TypeK SegmentType = 16
)
// Weight sub-TLV specifies the weight associated to a given segment list.
type SegmentListWeight struct {
TunnelEncapSubTLV
Flags uint8
Weight uint32
}
func (s *SegmentListWeight) DecodeFromBytes(data []byte) error {
value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
s.Flags = value[0]
s.Weight = binary.BigEndian.Uint32(value[2:6])
return nil
}
func (s *SegmentListWeight) Serialize() ([]byte, error) {
buf := make([]byte, 6)
buf[0] = s.Flags
binary.BigEndian.PutUint32(buf[2:6], s.Weight)
return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentListWeight) String() string {
return fmt.Sprintf("{Flags: 0x%02x, Weight: %d}", s.Flags, s.Weight)
}
func (s *SegmentListWeight) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
Weight uint32 `json:"weight,omitempty"`
}{
Type: s.Type,
Flags: s.Flags,
Weight: s.Weight,
})
}
type SegmentTypeA struct {
TunnelEncapSubTLV
Flags uint8
Label uint32
}
func (s *SegmentTypeA) DecodeFromBytes(data []byte) error {
value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
s.Flags = value[0]
s.Label = binary.BigEndian.Uint32(value[2:6])
return nil
}
func (s *SegmentTypeA) Serialize() ([]byte, error) {
buf := make([]byte, 6)
buf[0] = s.Flags
binary.BigEndian.PutUint32(buf[2:6], s.Label)
return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentTypeA) String() string {
return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Label: %d TC: %d S: %t TTL: %d}",
s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10,
s.Label>>12, s.Label&0x00000e00>>9, s.Label&0x00000100 == 0x00000100, s.Label&0x000000ff)
}
func (s *SegmentTypeA) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
VFlag bool `json:"v_flag"`
AFlag bool `json:"a_flag"`
SFlag bool `json:"s_flag"`
BFlag bool `json:"b_flag"`
Label uint32 `json:"label"`
TC uint8 `json:"tc"`
S bool `json:"s"`
TTL uint8 `json:"ttl"`
}{
Type: s.Type,
VFlag: s.Flags&0x80 == 0x80,
AFlag: s.Flags&0x40 == 0x40,
SFlag: s.Flags&0x20 == 0x20,
BFlag: s.Flags&0x10 == 0x10,
Label: s.Label >> 12,
TC: uint8(s.Label & 0x00000e00 >> 9),
S: s.Label&0x00000100 == 0x00000100,
TTL: uint8(s.Label & 0x000000ff),
})
}
//go:generate go run internal/generate.go SRBehavior
//go:generate stringer -type=SRBehavior
type SRBehavior int32
type SRv6EndpointBehaviorStructure struct {
Behavior SRBehavior
BlockLen uint8
NodeLen uint8
FuncLen uint8
ArgLen uint8
}
func (s *SRv6EndpointBehaviorStructure) DecodeFromBytes(data []byte) error {
if len(data) < 8 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Malformed BGP message")
}
behavior := binary.BigEndian.Uint16(data[0:2])
s.Behavior = SRBehavior(behavior)
s.BlockLen = data[4]
s.NodeLen = data[5]
s.FuncLen = data[6]
s.ArgLen = data[7]
return nil
}
func (s *SRv6EndpointBehaviorStructure) Serialize() ([]byte, error) {
buf := make([]byte, 8)
binary.BigEndian.PutUint16(buf[0:2], uint16(s.Behavior))
buf[4] = s.BlockLen
buf[5] = s.NodeLen
buf[6] = s.FuncLen
buf[7] = s.ArgLen
return buf, nil
}
func (s *SRv6EndpointBehaviorStructure) String() string {
return fmt.Sprintf("{Behavior: %s, BlockLen: %d, NodeLen: %d, FuncLen: %d, ArgLen: %d}",
s.Behavior.String(), s.BlockLen, s.NodeLen, s.FuncLen, s.ArgLen)
}
func (s *SRv6EndpointBehaviorStructure) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Behavior SRBehavior `json:"behavior"`
BlockLen uint8 `json:"block_Len"`
NodeLen uint8 `json:"node_len"`
FuncLen uint8 `json:"func_len"`
ArgLen uint8 `json:"arg_len"`
}{
Behavior: s.Behavior,
BlockLen: s.BlockLen,
NodeLen: s.NodeLen,
FuncLen: s.FuncLen,
ArgLen: s.ArgLen,
})
}
type SegmentTypeB struct {
TunnelEncapSubTLV
Flags uint8
SID []byte
SRv6EBS *SRv6EndpointBehaviorStructure
}
func (s *SegmentTypeB) DecodeFromBytes(data []byte) error {
value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
if len(value) < 18 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Malformed BGP message")
}
s.Flags = value[0]
s.SID = value[2:18]
if len(value) == 26 {
s.SRv6EBS = &SRv6EndpointBehaviorStructure{}
err = s.SRv6EBS.DecodeFromBytes(value[18:])
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
}
return nil
}
func (s *SegmentTypeB) Serialize() ([]byte, error) {
buf := make([]byte, 18)
buf[0] = s.Flags
copy(buf[2:], s.SID)
if s.SRv6EBS != nil {
if ebs, _ := s.SRv6EBS.Serialize(); ebs != nil {
buf = append(buf, ebs...)
}
}
return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentTypeB) String() string {
if s.SRv6EBS == nil {
return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Sid: %s}",
s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10, net.IP(s.SID).To16().String())
} else {
return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Sid: %s, Ebs: %s}",
s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10, net.IP(s.SID).To16().String(),
s.SRv6EBS.String())
}
}
func (s *SegmentTypeB) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
VFlag bool `json:"v_flag"`
AFlag bool `json:"a_flag"`
SFlag bool `json:"s_flag"`
BFlag bool `json:"b_flag"`
Sid string `json:"sid"`
SRv6EBS *SRv6EndpointBehaviorStructure `json:"endpointBehaviorStructure"`
}{
Type: s.Type,
VFlag: s.Flags&0x80 == 0x80,
AFlag: s.Flags&0x40 == 0x40,
SFlag: s.Flags&0x20 == 0x20,
BFlag: s.Flags&0x10 == 0x10,
Sid: net.IP(s.SID).To16().String(),
SRv6EBS: s.SRv6EBS,
})
}
const (
// SegmentListSubTLVWeight defines code for Segment List's Weight sub-TLV
SegmentListSubTLVWeight = 9
)
type TunnelEncapSubTLVSRSegmentList struct {
TunnelEncapSubTLV
Weight *SegmentListWeight
Segments []TunnelEncapSubTLVInterface
}
func (t *TunnelEncapSubTLVSRSegmentList) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
if len(value) < 1 {
return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP message")
}
// Skip reserved byte to access inner SubTLV type
value = value[1:]
var segments []TunnelEncapSubTLVInterface
p := 0
for p < t.TunnelEncapSubTLV.Len()-4 {
var segment TunnelEncapSubTLVInterface
switch SegmentType(value[0]) {
case SegmentListSubTLVWeight:
t.Weight = &SegmentListWeight{}
if err := t.Weight.DecodeFromBytes(value); err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
p += t.Weight.TunnelEncapSubTLV.Len()
value = value[t.Weight.TunnelEncapSubTLV.Len():]
continue
case TypeA:
segment = &SegmentTypeA{}
if err := segment.DecodeFromBytes(value); err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
case TypeB:
segment = &SegmentTypeB{}
if err := segment.DecodeFromBytes(value); err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
case TypeC:
fallthrough
case TypeD:
fallthrough
case TypeE:
fallthrough
case TypeF:
fallthrough
case TypeG:
fallthrough
case TypeH:
fallthrough
case TypeI:
fallthrough
case TypeJ:
fallthrough
case TypeK:
msg := fmt.Sprintf("Invalid SR Policy Segment SubTLV %d is not yet supported", value[0])
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
default:
msg := fmt.Sprintf("Invalid SR Policy Segment List SubTLV %d", value[0])
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
segments = append(segments, segment)
p += segment.Len()
value = value[segment.Len():]
}
if len(segments) == 0 {
t.Segments = nil
} else {
t.Segments = segments
}
return nil
}
func (t *TunnelEncapSubTLVSRSegmentList) Serialize() ([]byte, error) {
buf := make([]byte, 0)
// Add reserved byte
buf = append(buf, 0x0)
if t.Weight != nil {
wbuf, err := t.Weight.Serialize()
if err != nil {
return nil, err
}
buf = append(buf, wbuf...)
}
for _, s := range t.Segments {
sbuf, err := s.Serialize()
if err != nil {
return nil, err
}
buf = append(buf, sbuf...)
}
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRSegmentList) String() string {
msg := "{"
if t.Weight != nil {
msg += "Weight: " + t.Weight.String() + ","
}
msg += "Segment List: [ "
for _, s := range t.Segments {
msg += s.String() + ","
}
msg += " ] }"
return msg
}
func (t *TunnelEncapSubTLVSRSegmentList) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Weight *SegmentListWeight
Segments []TunnelEncapSubTLVInterface
}{
Type: t.Type,
Weight: t.Weight,
Segments: t.Segments,
})
}
@@ -1,47 +0,0 @@
// Generated code; DO NOT EDIT.
package bgp
const (
RESERVED SRBehavior = 0
END SRBehavior = 1
END_WITH_PSP SRBehavior = 2
END_WITH_USP SRBehavior = 3
END_WITH_PSP_USP SRBehavior = 4
ENDX SRBehavior = 5
ENDX_WITH_PSP SRBehavior = 6
ENDX_WITH_USP SRBehavior = 7
ENDX_WITH_PSP_USP SRBehavior = 8
ENDT SRBehavior = 9
ENDT_WITH_PSP SRBehavior = 10
ENDT_WITH_USP SRBehavior = 11
ENDT_WITH_PSP_USP SRBehavior = 12
END_B6_ENCAPS SRBehavior = 14
END_BM SRBehavior = 15
END_DX6 SRBehavior = 16
END_DX4 SRBehavior = 17
END_DT6 SRBehavior = 18
END_DT4 SRBehavior = 19
END_DT46 SRBehavior = 20
END_DX2 SRBehavior = 21
END_DX2V SRBehavior = 22
END_DT2U SRBehavior = 23
END_DT2M SRBehavior = 24
END_B6_ENCAPS_Red SRBehavior = 27
END_WITH_USD SRBehavior = 28
END_WITH_PSP_USD SRBehavior = 29
END_WITH_USP_USD SRBehavior = 30
END_WITH_PSP_USP_USD SRBehavior = 31
ENDX_WITH_USD SRBehavior = 32
ENDX_WITH_PSP_USD SRBehavior = 33
ENDX_WITH_USP_USD SRBehavior = 34
ENDX_WITH_PSP_USP_USD SRBehavior = 35
ENDT_WITH_USD SRBehavior = 36
ENDT_WITH_PSP_USD SRBehavior = 37
ENDT_WITH_USP_USD SRBehavior = 38
ENDT_WITH_PSP_USP_USD SRBehavior = 39
ENDM_GTP6D SRBehavior = 69 // 0x0045
ENDM_GTP6DI SRBehavior = 70 // 0x0046
ENDM_GTP6E SRBehavior = 71 // 0x0047
ENDM_GTP4E SRBehavior = 72 // 0x0048
)
@@ -1,84 +0,0 @@
// Code generated by "stringer -type=SRBehavior"; DO NOT EDIT.
package bgp
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[RESERVED-0]
_ = x[END-1]
_ = x[END_WITH_PSP-2]
_ = x[END_WITH_USP-3]
_ = x[END_WITH_PSP_USP-4]
_ = x[ENDX-5]
_ = x[ENDX_WITH_PSP-6]
_ = x[ENDX_WITH_USP-7]
_ = x[ENDX_WITH_PSP_USP-8]
_ = x[ENDT-9]
_ = x[ENDT_WITH_PSP-10]
_ = x[ENDT_WITH_USP-11]
_ = x[ENDT_WITH_PSP_USP-12]
_ = x[END_B6_ENCAPS-14]
_ = x[END_BM-15]
_ = x[END_DX6-16]
_ = x[END_DX4-17]
_ = x[END_DT6-18]
_ = x[END_DT4-19]
_ = x[END_DT46-20]
_ = x[END_DX2-21]
_ = x[END_DX2V-22]
_ = x[END_DT2U-23]
_ = x[END_DT2M-24]
_ = x[END_B6_ENCAPS_Red-27]
_ = x[END_WITH_USD-28]
_ = x[END_WITH_PSP_USD-29]
_ = x[END_WITH_USP_USD-30]
_ = x[END_WITH_PSP_USP_USD-31]
_ = x[ENDX_WITH_USD-32]
_ = x[ENDX_WITH_PSP_USD-33]
_ = x[ENDX_WITH_USP_USD-34]
_ = x[ENDX_WITH_PSP_USP_USD-35]
_ = x[ENDT_WITH_USD-36]
_ = x[ENDT_WITH_PSP_USD-37]
_ = x[ENDT_WITH_USP_USD-38]
_ = x[ENDT_WITH_PSP_USP_USD-39]
_ = x[ENDM_GTP6D-69]
_ = x[ENDM_GTP6DI-70]
_ = x[ENDM_GTP6E-71]
_ = x[ENDM_GTP4E-72]
}
const (
_SRBehavior_name_0 = "RESERVEDENDEND_WITH_PSPEND_WITH_USPEND_WITH_PSP_USPENDXENDX_WITH_PSPENDX_WITH_USPENDX_WITH_PSP_USPENDTENDT_WITH_PSPENDT_WITH_USPENDT_WITH_PSP_USP"
_SRBehavior_name_1 = "END_B6_ENCAPSEND_BMEND_DX6END_DX4END_DT6END_DT4END_DT46END_DX2END_DX2VEND_DT2UEND_DT2M"
_SRBehavior_name_2 = "END_B6_ENCAPS_RedEND_WITH_USDEND_WITH_PSP_USDEND_WITH_USP_USDEND_WITH_PSP_USP_USDENDX_WITH_USDENDX_WITH_PSP_USDENDX_WITH_USP_USDENDX_WITH_PSP_USP_USDENDT_WITH_USDENDT_WITH_PSP_USDENDT_WITH_USP_USDENDT_WITH_PSP_USP_USD"
_SRBehavior_name_3 = "ENDM_GTP6DENDM_GTP6DIENDM_GTP6EENDM_GTP4E"
)
var (
_SRBehavior_index_0 = [...]uint8{0, 8, 11, 23, 35, 51, 55, 68, 81, 98, 102, 115, 128, 145}
_SRBehavior_index_1 = [...]uint8{0, 13, 19, 26, 33, 40, 47, 55, 62, 70, 78, 86}
_SRBehavior_index_2 = [...]uint8{0, 17, 29, 45, 61, 81, 94, 111, 128, 149, 162, 179, 196, 217}
_SRBehavior_index_3 = [...]uint8{0, 10, 21, 31, 41}
)
func (i SRBehavior) String() string {
switch {
case 0 <= i && i <= 12:
return _SRBehavior_name_0[_SRBehavior_index_0[i]:_SRBehavior_index_0[i+1]]
case 14 <= i && i <= 24:
i -= 14
return _SRBehavior_name_1[_SRBehavior_index_1[i]:_SRBehavior_index_1[i+1]]
case 27 <= i && i <= 39:
i -= 27
return _SRBehavior_name_2[_SRBehavior_index_2[i]:_SRBehavior_index_2[i+1]]
case 69 <= i && i <= 72:
i -= 69
return _SRBehavior_name_3[_SRBehavior_index_3[i]:_SRBehavior_index_3[i+1]]
default:
return "SRBehavior(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
-356
View File
@@ -1,356 +0,0 @@
package bgp
import (
"encoding/binary"
"fmt"
"math"
"net"
"strconv"
)
// Validator for BGPUpdate
func ValidateUpdateMsg(m *BGPUpdate, rfs map[RouteFamily]BGPAddPathMode, isEBGP bool, isConfed bool, loopbackNextHopAllowed bool) (bool, error) {
var strongestError error
eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
eSubCodeAttrList := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
eSubCodeMissing := uint8(BGP_ERROR_SUB_MISSING_WELL_KNOWN_ATTRIBUTE)
if len(m.NLRI) > 0 || len(m.WithdrawnRoutes) > 0 {
if _, ok := rfs[RF_IPv4_UC]; !ok {
return false, NewMessageError(0, 0, nil, fmt.Sprintf("Address-family rf %d not available for session", RF_IPv4_UC))
}
}
seen := make(map[BGPAttrType]PathAttributeInterface)
newAttrs := make([]PathAttributeInterface, 0, len(seen))
// check path attribute
for _, a := range m.PathAttributes {
// check duplication
if _, ok := seen[a.GetType()]; !ok {
seen[a.GetType()] = a
newAttrs = append(newAttrs, a)
//check specific path attribute
ok, err := ValidateAttribute(a, rfs, isEBGP, isConfed, loopbackNextHopAllowed)
if !ok {
msgErr := err.(*MessageError)
if msgErr.ErrorHandling == ERROR_HANDLING_SESSION_RESET {
return false, err
} else if msgErr.Stronger(strongestError) {
strongestError = err
}
}
} else if a.GetType() == BGP_ATTR_TYPE_MP_REACH_NLRI || a.GetType() == BGP_ATTR_TYPE_MP_UNREACH_NLRI {
eMsg := "the path attribute appears twice. Type : " + strconv.Itoa(int(a.GetType()))
return false, NewMessageError(eCode, eSubCodeAttrList, nil, eMsg)
} else {
eMsg := "the path attribute appears twice. Type : " + strconv.Itoa(int(a.GetType()))
e := NewMessageErrorWithErrorHandling(eCode, eSubCodeAttrList, nil, ERROR_HANDLING_ATTRIBUTE_DISCARD, nil, eMsg)
if e.(*MessageError).Stronger(strongestError) {
strongestError = e
}
}
}
m.PathAttributes = newAttrs
if _, ok := seen[BGP_ATTR_TYPE_MP_REACH_NLRI]; ok || len(m.NLRI) > 0 {
// check the existence of well-known mandatory attributes
exist := func(attrs []BGPAttrType) (bool, BGPAttrType) {
for _, attr := range attrs {
_, ok := seen[attr]
if !ok {
return false, attr
}
}
return true, 0
}
mandatory := []BGPAttrType{BGP_ATTR_TYPE_ORIGIN, BGP_ATTR_TYPE_AS_PATH}
if len(m.NLRI) > 0 {
mandatory = append(mandatory, BGP_ATTR_TYPE_NEXT_HOP)
}
if ok, t := exist(mandatory); !ok {
eMsg := "well-known mandatory attributes are not present. type : " + strconv.Itoa(int(t))
data := []byte{byte(t)}
e := NewMessageErrorWithErrorHandling(eCode, eSubCodeMissing, data, ERROR_HANDLING_TREAT_AS_WITHDRAW, nil, eMsg)
if e.(*MessageError).Stronger(strongestError) {
strongestError = e
}
}
}
return strongestError == nil, strongestError
}
func ValidateAttribute(a PathAttributeInterface, rfs map[RouteFamily]BGPAddPathMode, isEBGP bool, isConfed bool, loopbackNextHopAllowed bool) (bool, error) {
var strongestError error
eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
eSubCodeBadOrigin := uint8(BGP_ERROR_SUB_INVALID_ORIGIN_ATTRIBUTE)
eSubCodeBadNextHop := uint8(BGP_ERROR_SUB_INVALID_NEXT_HOP_ATTRIBUTE)
eSubCodeUnknown := uint8(BGP_ERROR_SUB_UNRECOGNIZED_WELL_KNOWN_ATTRIBUTE)
eSubCodeMalformedAspath := uint8(BGP_ERROR_SUB_MALFORMED_AS_PATH)
checkPrefix := func(l []AddrPrefixInterface) error {
for _, prefix := range l {
rf := AfiSafiToRouteFamily(prefix.AFI(), prefix.SAFI())
if _, ok := rfs[rf]; !ok {
return NewMessageError(0, 0, nil, fmt.Sprintf("Address-family %s not available for this session", rf))
}
switch rf {
case RF_FS_IPv4_UC, RF_FS_IPv6_UC, RF_FS_IPv4_VPN, RF_FS_IPv6_VPN, RF_FS_L2_VPN:
t := BGPFlowSpecType(0)
value := make([]FlowSpecComponentInterface, 0)
switch rf {
case RF_FS_IPv4_UC:
value = prefix.(*FlowSpecIPv4Unicast).Value
case RF_FS_IPv6_UC:
value = prefix.(*FlowSpecIPv6Unicast).Value
case RF_FS_IPv4_VPN:
value = prefix.(*FlowSpecIPv4VPN).Value
case RF_FS_IPv6_VPN:
value = prefix.(*FlowSpecIPv6VPN).Value
case RF_FS_L2_VPN:
value = prefix.(*FlowSpecL2VPN).Value
}
for _, v := range value {
if v.Type() <= t {
return NewMessageError(0, 0, nil, fmt.Sprintf("%s nlri violate strict type ordering", rf))
}
t = v.Type()
}
}
}
return nil
}
switch p := a.(type) {
case *PathAttributeMpUnreachNLRI:
rf := AfiSafiToRouteFamily(p.AFI, p.SAFI)
if _, ok := rfs[rf]; !ok {
return false, NewMessageError(0, 0, nil, fmt.Sprintf("Address-family rf %d not available for session", rf))
}
if err := checkPrefix(p.Value); err != nil {
return false, err
}
case *PathAttributeMpReachNLRI:
rf := AfiSafiToRouteFamily(p.AFI, p.SAFI)
if _, ok := rfs[rf]; !ok {
return false, NewMessageError(0, 0, nil, fmt.Sprintf("Address-family rf %d not available for session", rf))
}
if err := checkPrefix(p.Value); err != nil {
return false, err
}
case *PathAttributeOrigin:
v := uint8(p.Value)
if v != BGP_ORIGIN_ATTR_TYPE_IGP &&
v != BGP_ORIGIN_ATTR_TYPE_EGP &&
v != BGP_ORIGIN_ATTR_TYPE_INCOMPLETE {
data, _ := a.Serialize()
eMsg := "invalid origin attribute. value : " + strconv.Itoa(int(v))
e := NewMessageErrorWithErrorHandling(eCode, eSubCodeBadOrigin, data, getErrorHandlingFromPathAttribute(p.GetType()), nil, eMsg)
if e.(*MessageError).Stronger(strongestError) {
strongestError = e
}
}
case *PathAttributeNextHop:
isZero := func(ip net.IP) bool {
res := ip[0] & 0xff
return res == 0x00
}
isClassDorE := func(ip net.IP) bool {
if ip.To4() == nil {
// needs to verify ipv6 too?
return false
}
res := ip[0] & 0xe0
return res == 0xe0
}
//check IP address represents host address
if (!loopbackNextHopAllowed && p.Value.IsLoopback()) || isZero(p.Value) || isClassDorE(p.Value) {
eMsg := "invalid nexthop address"
data, _ := a.Serialize()
e := NewMessageErrorWithErrorHandling(eCode, eSubCodeBadNextHop, data, getErrorHandlingFromPathAttribute(p.GetType()), nil, eMsg)
if e.(*MessageError).Stronger(strongestError) {
strongestError = e
}
}
case *PathAttributeAsPath:
if isEBGP {
if isConfed {
if segType := p.Value[0].GetType(); segType != BGP_ASPATH_ATTR_TYPE_CONFED_SEQ {
return false, NewMessageError(eCode, eSubCodeMalformedAspath, nil, fmt.Sprintf("segment type is not confederation seq (%d)", segType))
}
} else {
for _, param := range p.Value {
segType := param.GetType()
switch segType {
case BGP_ASPATH_ATTR_TYPE_CONFED_SET, BGP_ASPATH_ATTR_TYPE_CONFED_SEQ:
err := NewMessageErrorWithErrorHandling(
eCode, eSubCodeMalformedAspath, nil, getErrorHandlingFromPathAttribute(p.GetType()), nil, fmt.Sprintf("segment type confederation(%d) found", segType))
if err.(*MessageError).Stronger(strongestError) {
strongestError = err
}
}
}
}
}
case *PathAttributeLargeCommunities:
uniq := make([]*LargeCommunity, 0, len(p.Values))
for _, x := range p.Values {
found := false
for _, y := range uniq {
if x.Eq(y) {
found = true
break
}
}
if !found {
uniq = append(uniq, x)
}
}
p.Values = uniq
case *PathAttributeUnknown:
if p.GetFlags()&BGP_ATTR_FLAG_OPTIONAL == 0 {
eMsg := fmt.Sprintf("unrecognized well-known attribute %s", p.GetType())
data, _ := a.Serialize()
return false, NewMessageError(eCode, eSubCodeUnknown, data, eMsg)
}
}
return strongestError == nil, strongestError
}
// validator for PathAttribute
func validatePathAttributeFlags(t BGPAttrType, flags BGPAttrFlag) string {
/*
* RFC 4271 P.17 For well-known attributes, the Transitive bit MUST be set to 1.
*/
if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 {
eMsg := fmt.Sprintf("well-known attribute %s must have transitive flag 1", t)
return eMsg
}
/*
* RFC 4271 P.17 For well-known attributes and for optional non-transitive attributes,
* the Partial bit MUST be set to 0.
*/
if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_PARTIAL != 0 {
eMsg := fmt.Sprintf("well-known attribute %s must have partial bit 0", t)
return eMsg
}
if flags&BGP_ATTR_FLAG_OPTIONAL != 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 && flags&BGP_ATTR_FLAG_PARTIAL != 0 {
eMsg := fmt.Sprintf("optional non-transitive attribute %s must have partial bit 0", t)
return eMsg
}
// check flags are correct
if f, ok := PathAttrFlags[t]; ok {
if f != flags & ^BGP_ATTR_FLAG_EXTENDED_LENGTH & ^BGP_ATTR_FLAG_PARTIAL {
eMsg := fmt.Sprintf("flags are invalid. attribute type: %s, expect: %s, actual: %s", t, f, flags)
return eMsg
}
}
return ""
}
func validateAsPathValueBytes(data []byte) (bool, error) {
eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_AS_PATH)
if len(data)%2 != 0 {
return false, NewMessageError(eCode, eSubCode, nil, "AS PATH length is not odd")
}
tryParse := func(data []byte, use4byte bool) (bool, error) {
for len(data) > 0 {
if len(data) < 2 {
return false, NewMessageError(eCode, eSubCode, nil, "AS PATH header is short")
}
segType := data[0]
if segType == 0 || segType > 4 {
return false, NewMessageError(eCode, eSubCode, nil, "unknown AS_PATH seg type")
}
asNum := data[1]
data = data[2:]
if asNum == 0 || int(asNum) > math.MaxUint8 {
return false, NewMessageError(eCode, eSubCode, nil, "AS PATH the number of AS is incorrect")
}
segLength := int(asNum)
if use4byte {
segLength *= 4
} else {
segLength *= 2
}
if int(segLength) > len(data) {
return false, NewMessageError(eCode, eSubCode, nil, "seg length is short")
}
data = data[segLength:]
}
return true, nil
}
_, err := tryParse(data, true)
if err == nil {
return true, nil
}
_, err = tryParse(data, false)
if err == nil {
return false, nil
}
return false, NewMessageError(eCode, eSubCode, nil, "can't parse AS_PATH")
}
func ValidateBGPMessage(m *BGPMessage) error {
if m.Header.Len > BGP_MAX_MESSAGE_LENGTH {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, m.Header.Len)
return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, buf, "too long length")
}
return nil
}
func ValidateOpenMsg(m *BGPOpen, expectedAS uint32, myAS uint32, myId net.IP) (uint32, error) {
if m.Version != 4 {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER, nil, fmt.Sprintf("unsupported version %d", m.Version))
}
as := uint32(m.MyAS)
for _, p := range m.OptParams {
paramCap, y := p.(*OptionParameterCapability)
if !y {
continue
}
for _, c := range paramCap.Capability {
if c.Code() == BGP_CAP_FOUR_OCTET_AS_NUMBER {
cap := c.(*CapFourOctetASNumber)
as = cap.CapValue
}
}
}
// rfc6286 (Autonomous-System-Wide Unique BGP Identifier for BGP-4)
// If the BGP Identifier field of the OPEN message is zero, or if it
// is the same as the BGP Identifier of the local BGP speaker and the
// message is from an internal peer, then the Error Subcode is set to
// "Bad BGP Identifier".
routerId := m.ID
if routerId.IsUnspecified() {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_BGP_IDENTIFIER, nil, fmt.Sprintf("bad BGP identifier %s (0.0.0.0)", routerId.String()))
}
if as == myAS && routerId.Equal(myId) {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_BGP_IDENTIFIER, nil, fmt.Sprintf("bad BGP identifier %s", routerId.String()))
}
if expectedAS != 0 && as != expectedAS {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_PEER_AS, nil, fmt.Sprintf("as number mismatch expected %d, received %d", expectedAS, as))
}
if m.HoldTime < 3 && m.HoldTime != 0 {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNACCEPTABLE_HOLD_TIME, nil, fmt.Sprintf("unacceptable hold time %d", m.HoldTime))
}
return as, nil
}
-208
View File
@@ -1,208 +0,0 @@
package bgp
import (
"encoding/binary"
"encoding/json"
"fmt"
)
// VPLSNLRI represents an NLRI for VPLS, as defined in [RFC 4761, section 3.2.2].
//
// Path Attribute - MP_REACH_NLRI
// Flags: 0x90, Optional, Extended-Length, Non-transitive, Complete
// Type Code: MP_REACH_NLRI (14)
// Length: 28
// Address family identifier (AFI): Layer-2 VPN (25)
// Subsequent address family identifier (SAFI): VPLS (65)
// Next hop: 192.0.2.7
// IPv4 Address: 192.0.2.7
// Number of Subnetwork points of attachment (SNPA): 0
// Network Layer Reachability Information (NLRI)
// Length: 17
// RD: 65017:104
// CE-ID: 1
// Label Block Offset: 1
// Label Block Size: 8
// Label Block Base: 800000 (bottom)
//
// [RFC 4761, section 3.2.2]: https://www.rfc-editor.org/rfc/rfc4761.html#section-3.2.2.
type VPLSNLRI struct {
PrefixDefault
VEID uint16
VEBlockOffset uint16
VEBlockSize uint16
LabelBlockBase uint32
rd RouteDistinguisherInterface
}
func (n *VPLSNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
/*
RFC6074 Section 7 BGP-AD and VPLS-BGP Interoperability
Both BGP-AD and VPLS-BGP [RFC4761] use the same AFI/SAFI. In order
for both BGP-AD and VPLS-BGP to co-exist, the NLRI length must be
used as a demultiplexer.
The BGP-AD NLRI has an NLRI length of 12 bytes, containing only an
8-byte RD and a 4-byte VSI-ID. VPLS-BGP [RFC4761] uses a 17-byte
NLRI length. Therefore, implementations of BGP-AD must ignore NLRI
that are greater than 12 bytes.
*/
length := int(binary.BigEndian.Uint16(data[0:2]))
if len(data) < length+2 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all VPLS NLRI bytes available")
}
if length == 12 { // BGP-AD
// BGP-AD is not supported yet
return nil
}
// VPLS-BGP
n.rd = GetRouteDistinguisher(data[2:10])
n.VEID = binary.BigEndian.Uint16(data[10:12])
n.VEBlockOffset = binary.BigEndian.Uint16(data[12:14])
n.VEBlockSize = binary.BigEndian.Uint16(data[14:16])
labelBlockBase := uint32(data[16])<<16 | uint32(data[17])<<8 | uint32(data[18])
n.LabelBlockBase = labelBlockBase >> 4
return nil
}
func (n *VPLSNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
buf := make([]byte, 16)
labelBaseBuf := make([]byte, 3)
binary.BigEndian.PutUint16(buf[0:2], 17)
rdbuf, err := n.rd.Serialize()
if err != nil {
return nil, err
}
copy(buf[2:10], rdbuf[:8])
binary.BigEndian.PutUint16(buf[10:12], n.VEID)
binary.BigEndian.PutUint16(buf[12:14], n.VEBlockOffset)
binary.BigEndian.PutUint16(buf[14:16], n.VEBlockSize)
labelBlockBase := n.LabelBlockBase << 4
labelBaseBuf[0] = byte((labelBlockBase >> 16) & 0xff)
labelBaseBuf[1] = byte((labelBlockBase >> 8) & 0xff)
labelBaseBuf[2] = byte(labelBlockBase & 0xff)
return append(buf, labelBaseBuf...), nil
}
func (n *VPLSNLRI) AFI() uint16 {
return AFI_L2VPN
}
func (n *VPLSNLRI) SAFI() uint8 {
return SAFI_VPLS
}
func (n *VPLSNLRI) Len(options ...*MarshallingOption) int {
// Length (2) + Route Distinguisher (8) + VE ID (2) + VE Block Offset (2)
// + VE Block Size (2) + Label Block Base (3)
return 19
}
func (n *VPLSNLRI) String() string {
return fmt.Sprintf("%s:%d:%d (Block Size: %d, Label Block Base: %d)", n.rd, n.VEID, n.VEBlockOffset, n.VEBlockSize, n.LabelBlockBase)
}
func (n *VPLSNLRI) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
RD RouteDistinguisherInterface `json:"rd"`
VEID uint16 `json:"id"`
VEBlockOffset uint16 `json:"blockoffset"`
VEBlockSize uint16 `json:"blocksize"`
LabelBlockBase uint32 `json:"labelblockbase"`
}{
RD: n.rd,
VEID: n.VEID,
VEBlockOffset: n.VEBlockOffset,
VEBlockSize: n.VEBlockSize,
LabelBlockBase: n.LabelBlockBase,
})
}
func (n *VPLSNLRI) RD() RouteDistinguisherInterface {
return n.rd
}
func (l *VPLSNLRI) Flat() map[string]string {
return map[string]string{}
}
func NewVPLSNLRI(rd RouteDistinguisherInterface, id uint16, blockOffset uint16, blockSize uint16, labelBlockBase uint32) *VPLSNLRI {
return &VPLSNLRI{
rd: rd,
VEID: id,
VEBlockOffset: blockOffset,
VEBlockSize: blockSize,
LabelBlockBase: labelBlockBase,
}
}
// VPLSExtended repsents BGP VPLS Extended Community as described in [RFC 4761, section 3.2.4].
//
// Path Attribute - EXTENDED_COMMUNITIES
// Flags: 0xc0, Optional, Transitive, Complete
// Type Code: EXTENDED_COMMUNITIES (16)
// Length: 16
// Carried extended communities: (2 communities)
// Route Target: 65017:104 [Transitive 2-Octet AS-Specific]
// Layer2 Info: [Generic Transitive Experimental Use]
// Type: Generic Transitive Experimental Use (0x80)
// Subtype (Experimental): Layer2 Info (0x0a)
// Encaps Type: VPLS (19)
// Control Flags: 0x00
// Layer-2 MTU: 0
//
// [RFC 4761, section 3.2.4]: https://www.rfc-editor.org/rfc/rfc4761.html#section-3.2.4
type VPLSExtended struct {
SubType ExtendedCommunityAttrSubType
ControlFlags uint8
MTU uint16
}
func (e *VPLSExtended) Serialize() ([]byte, error) {
buf := make([]byte, 8)
buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL)
buf[1] = byte(EC_SUBTYPE_L2_INFO)
buf[2] = byte(LAYER2ENCAPSULATION_TYPE_VPLS)
buf[3] = byte(e.ControlFlags)
binary.BigEndian.PutUint16(buf[4:6], e.MTU)
// 6-8: reserved, but Juniper says this is "site preference"
return buf, nil
}
func (e *VPLSExtended) String() string {
return fmt.Sprintf("encaps: VPLS, control flags:0x%x, mtu: %d", e.ControlFlags, e.MTU)
}
func (e *VPLSExtended) MarshalJSON() ([]byte, error) {
t, s := e.GetTypes()
return json.Marshal(struct {
Type ExtendedCommunityAttrType `json:"type"`
Subtype ExtendedCommunityAttrSubType `json:"subtype"`
Value string `json:"value"`
}{
Type: t,
Subtype: s,
Value: e.String(),
})
}
func (e *VPLSExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_SUBTYPE_L2_INFO
}
func (e *VPLSExtended) Flat() map[string]string {
return map[string]string{}
}
func NewVPLSExtended(flags uint8, mtu uint16) *VPLSExtended {
return &VPLSExtended{
SubType: EC_SUBTYPE_L2_INFO,
ControlFlags: flags,
MTU: mtu,
}
}
-27
View File
@@ -1,27 +0,0 @@
// Code generated by "stringer -type=afi"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[afiIP-1]
_ = x[afiIP6-2]
_ = x[afiEther-3]
_ = x[afiMax-4]
}
const _afi_name = "afiIPafiIP6afiEtherafiMax"
var _afi_index = [...]uint8{0, 5, 11, 19, 25}
func (i afi) String() string {
i -= 1
if i >= afi(len(_afi_index)-1) {
return "afi(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _afi_name[_afi_index[i]:_afi_index[i+1]]
}
-272
View File
@@ -1,272 +0,0 @@
// Code generated by "stringer -type=APIType"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[interfaceAdd-0]
_ = x[interfaceDelete-1]
_ = x[interfaceAddressAdd-2]
_ = x[interfaceAddressDelete-3]
_ = x[interfaceUp-4]
_ = x[interfaceDown-5]
_ = x[_interfaceSetMaster-6]
_ = x[_interfaceSetProtoDown-7]
_ = x[RouteAdd-8]
_ = x[RouteDelete-9]
_ = x[_routeNotifyOwner-10]
_ = x[redistributeAdd-11]
_ = x[_redistributeDelete-12]
_ = x[_redistributeDefaultAdd-13]
_ = x[_redistributeDefaultDelete-14]
_ = x[routerIDAdd-15]
_ = x[_routerIDDelete-16]
_ = x[routerIDUpdate-17]
_ = x[Hello-18]
_ = x[_capabilities-19]
_ = x[nexthopRegister-20]
_ = x[nexthopUnregister-21]
_ = x[nexthopUpdate-22]
_ = x[_interfaceNBRAddressAdd-23]
_ = x[_interfaceNBRAddressDelete-24]
_ = x[_interfaceBFDDestUpdate-25]
_ = x[_importRouteRegister-26]
_ = x[_importRouteUnregister-27]
_ = x[_importCheckUpdate-28]
_ = x[_bfdDestRegister-29]
_ = x[_bfdDestDeregister-30]
_ = x[_bfdDestUpdate-31]
_ = x[_bfdDestReplay-32]
_ = x[RedistributeRouteAdd-33]
_ = x[RedistributeRouteDel-34]
_ = x[_vrfUnregister-35]
_ = x[_vrfAdd-36]
_ = x[_vrfDelete-37]
_ = x[vrfLabel-38]
_ = x[_interfaceVRFUpdate-39]
_ = x[_bfdClientRegister-40]
_ = x[_bfdClientDeregister-41]
_ = x[_interfaceEnableRADV-42]
_ = x[_interfaceDisableRADV-43]
_ = x[ipv4NexthopLookupMRIB-44]
_ = x[_interfaceLinkParams-45]
_ = x[_mplsLabelsAdd-46]
_ = x[_mplsLabelsDelete-47]
_ = x[_mplsLabelsReplace-48]
_ = x[_srPolicySet-49]
_ = x[_srPolicyDelete-50]
_ = x[_srPolicyNotifyStatus-51]
_ = x[_ipmrRouteStats-52]
_ = x[labelManagerConnect-53]
_ = x[labelManagerConnectAsync-54]
_ = x[getLabelChunk-55]
_ = x[releaseLabelChunk-56]
_ = x[_fecRegister-57]
_ = x[_fecUnregister-58]
_ = x[_fecUpdate-59]
_ = x[_advertiseDefaultGW-60]
_ = x[_advertiseSviMACIP-61]
_ = x[_advertiseSubnet-62]
_ = x[_advertiseAllVNI-63]
_ = x[_localESAdd-64]
_ = x[_localESDel-65]
_ = x[_remoteESVTEPAdd-66]
_ = x[_remoteESVTEPDel-67]
_ = x[_localESEVIAdd-68]
_ = x[_localESEVIDel-69]
_ = x[_vniAdd-70]
_ = x[_vniDel-71]
_ = x[_l3VNIAdd-72]
_ = x[_l3VNIDel-73]
_ = x[_remoteVTEPAdd-74]
_ = x[_remoteVTEPDel-75]
_ = x[_macIPAdd-76]
_ = x[_macIPDel-77]
_ = x[_ipPrefixRouteAdd-78]
_ = x[_ipPrefixRouteDel-79]
_ = x[_remoteMACIPAdd-80]
_ = x[_remoteMACIPDel-81]
_ = x[_duplicateAddrDetection-82]
_ = x[_pwAdd-83]
_ = x[_pwDelete-84]
_ = x[_pwSet-85]
_ = x[_pwUnset-86]
_ = x[_pwStatusUpdate-87]
_ = x[_ruleAdd-88]
_ = x[_ruleDelete-89]
_ = x[_ruleNotifyOwner-90]
_ = x[_tableManagerConnect-91]
_ = x[_getTableChunk-92]
_ = x[_releaseTableChunk-93]
_ = x[_ipSetCreate-94]
_ = x[_ipSetDestroy-95]
_ = x[_ipSetEntryAdd-96]
_ = x[_ipSetEntryDelete-97]
_ = x[_ipSetNotifyOwner-98]
_ = x[_ipSetEntryNotifyOwner-99]
_ = x[_ipTableAdd-100]
_ = x[_ipTableDelete-101]
_ = x[_ipTableNotifyOwner-102]
_ = x[_vxlanFloodControl-103]
_ = x[_vxlanSgAdd-104]
_ = x[_vxlanSgDel-105]
_ = x[_vxlanSgReplay-106]
_ = x[_mlagProcessUp-107]
_ = x[_mlagProcessDown-108]
_ = x[_mlagClientRegister-109]
_ = x[_mlagClientUnregister-110]
_ = x[_mlagClientForwardMsg-111]
_ = x[_nhgAdd-112]
_ = x[_nhgDel-113]
_ = x[_nhgNotifyOwner-114]
_ = x[_nhgEvpnRemoteNhAdd-115]
_ = x[_nhgEvpnRemoteNhDel-116]
_ = x[_srv6LocatorAdd-117]
_ = x[_srv6LocatorDelete-118]
_ = x[_srv6ManagerGetLocatorChunk-119]
_ = x[_srv6ManagerReleaseLocatorChunk-120]
_ = x[zebraError-121]
_ = x[_clientCapabilities-122]
_ = x[_opaqueMessage-123]
_ = x[_opaqueRegister-124]
_ = x[_opaqueUnregister-125]
_ = x[_neighDiscover-126]
_ = x[_RouteNotifyRequest-127]
_ = x[_ClientCloseNotify-128]
_ = x[_NhrpNeighAdded-129]
_ = x[_NhrpNeighRemoved-130]
_ = x[_NhrpNeighGet-131]
_ = x[_NhrpNeighRegister-132]
_ = x[_NhrpNeighUnregister-133]
_ = x[_NeighIPAdd-134]
_ = x[_NeighIPDel-135]
_ = x[_ConfigureArp-136]
_ = x[_GreGet-137]
_ = x[_GreUpdate-138]
_ = x[_GreSourceSet-139]
_ = x[BackwardIPv6RouteAdd-140]
_ = x[BackwardIPv6RouteDelete-141]
_ = x[zapi6Frr8dot2MinDifferentAPIType-26]
_ = x[zapi6Frr7dot3MinDifferentAPIType-49]
_ = x[zapi6Frr7dot2MinDifferentAPIType-48]
_ = x[zapi6Frr6MinDifferentAPIType-7]
_ = x[zapi5ClMinDifferentAPIType-19]
_ = x[zapi5MinDifferentAPIType-7]
_ = x[zapi4MinDifferentAPIType-6]
_ = x[zapi3MinDifferentAPIType-0]
_ = x[zapi6Frr8dot2RedistributeRouteAdd-30]
_ = x[zapi6Frr8dot2RedistributeRouteDel-31]
_ = x[zapi6Frr8dot2VrfLabel-35]
_ = x[zapi6Frr8dot2Ipv4NexthopLookupMRIB-41]
_ = x[zapi6Frr8dot2LabelManagerConnect-50]
_ = x[zapi6Frr8dot2LabelManagerConnectAsync-51]
_ = x[zapi6Frr8dot2GetLabelChunk-52]
_ = x[zapi6Frr8dot2ReleaseLabelChunk-53]
_ = x[zapi6Frr7dot3LabelManagerConnect-50]
_ = x[zapi6Frr7dot3LabelManagerConnectAsync-51]
_ = x[zapi6Frr7dot3GetLabelChunk-52]
_ = x[zapi6Frr7dot3ReleaseLabelChunk-53]
_ = x[zapi6Frr7dot2LabelManagerConnect-49]
_ = x[zapi6Frr7dot2LabelManagerConnectAsync-50]
_ = x[zapi6Frr7dot2GetLabelChunk-51]
_ = x[zapi6Frr7dot2ReleaseLabelChunk-52]
_ = x[zapi6Frr7RouteAdd-7]
_ = x[zapi6Frr7RouteDelete-8]
_ = x[zapi6Frr7RedistributAdd-10]
_ = x[zapi6Frr7RouterIDAdd-14]
_ = x[zapi6Frr7RouterIDUpdate-16]
_ = x[zapi6Frr7Hello-17]
_ = x[zapi6Frr7NexthopRegister-19]
_ = x[zapi6Frr7NexthopUnregister-20]
_ = x[zapi6Frr7NexthopUpdate-21]
_ = x[zapi6Frr7RedistributeRouteAdd-32]
_ = x[zapi6Frr7RedistributeRouteDel-33]
_ = x[zapi6Frr7VrfLabel-37]
_ = x[zapi6Frr7Ipv4NexthopLookupMRIB-43]
_ = x[zapi6Frr7LabelManagerConnect-48]
_ = x[zapi6Frr7LabelManagerConnectAsync-49]
_ = x[zapi6Frr7GetLabelChunk-50]
_ = x[zapi6Frr7ReleaseLabelChunk-51]
_ = x[zapi5ClIpv4NexthopLookupMRIB-42]
_ = x[zapi5ClLabelManagerConnect-47]
_ = x[zapi5ClGetLabelChunk-48]
_ = x[zapi5ClReleaseLabelChunk-49]
_ = x[zapi5RedistributAdd-14]
_ = x[zapi5RouterIDAdd-18]
_ = x[zapi5RouterIDUpdate-20]
_ = x[zapi5Hello-21]
_ = x[zapi5Frr5NexthopRegister-23]
_ = x[zapi5Frr5NexthopUnregister-24]
_ = x[zapi5Frr5NexthopUpdate-25]
_ = x[zapi5Frr5RedistributeRouteAdd-37]
_ = x[zapi5Frr5RedistributeRouteDel-38]
_ = x[zapi5Frr5VrfLabel-42]
_ = x[zapi5Frr5Ipv4NexthopLookupMRIB-47]
_ = x[zapi5Frr5LabelManagerConnect-52]
_ = x[zapi5Frr5LabelManagerConnectAsync-53]
_ = x[zapi5Frr5GetLabelChunk-54]
_ = x[zapi5Frr5ReleaseLabelChunk-55]
_ = x[zapi5Frr4NexthopRegister-22]
_ = x[zapi5Frr4NexthopUnregister-23]
_ = x[zapi5Frr4NexthopUpdate-24]
_ = x[zapi5Frr4RedistributeRouteAdd-36]
_ = x[zapi5Frr4RedistributeRouteDel-37]
_ = x[zapi5Frr4Ipv4NexthopLookupMRIB-45]
_ = x[zapi5Frr4LabelManagerConnect-50]
_ = x[zapi5Frr4GetLabelChunk-51]
_ = x[zapi5Frr4ReleaseLabelChunk-52]
_ = x[zapi4IPv4RouteAdd-6]
_ = x[zapi4IPv4RouteDelete-7]
_ = x[zapi4IPv6RouteAdd-8]
_ = x[zapi4IPv6RouteDelete-9]
_ = x[zapi4RedistributAdd-10]
_ = x[zapi4RouterIDAdd-14]
_ = x[zapi4RouterIDUpdate-16]
_ = x[zapi4Hello-17]
_ = x[zapi4NexthopRegister-18]
_ = x[zapi4NexthopUnregister-19]
_ = x[zapi4NexthopUpdate-20]
_ = x[zapi4RedistributeIPv4Add-32]
_ = x[zapi4RedistributeIPv4Del-33]
_ = x[zapi4RedistributeIPv6Add-34]
_ = x[zapi4RedistributeIPv6Del-35]
_ = x[zapi4LabelManagerConnect-52]
_ = x[zapi4GetLabelChunk-53]
_ = x[zapi4ReleaseLabelChunk-54]
_ = x[zapi3InterfaceAdd-1]
_ = x[zapi3InterfaceDelete-2]
_ = x[zapi3InterfaceAddressAdd-3]
_ = x[zapi3InterfaceAddressDelete-4]
_ = x[zapi3InterfaceUp-5]
_ = x[zapi3InterfaceDown-6]
_ = x[zapi3IPv4RouteAdd-7]
_ = x[zapi3IPv4RouteDelete-8]
_ = x[zapi3IPv6RouteAdd-9]
_ = x[zapi3IPv6RouteDelete-10]
_ = x[zapi3RedistributeAdd-11]
_ = x[zapi3IPv4NexthopLookup-15]
_ = x[zapi3IPv6NexthopLookup-16]
_ = x[zapi3IPv4ImportLookup-17]
_ = x[zapi3RouterIDAdd-20]
_ = x[zapi3RouterIDUpdate-22]
_ = x[zapi3Hello-23]
_ = x[zapi3Ipv4NexthopLookupMRIB-24]
_ = x[zapi3NexthopRegister-27]
_ = x[zapi3NexthopUnregister-28]
_ = x[zapi3NexthopUpdate-29]
}
const _APIType_name = "interfaceAddinterfaceDeleteinterfaceAddressAddinterfaceAddressDeleteinterfaceUpinterfaceDown_interfaceSetMaster_interfaceSetProtoDownRouteAddRouteDelete_routeNotifyOwnerredistributeAdd_redistributeDelete_redistributeDefaultAdd_redistributeDefaultDeleterouterIDAdd_routerIDDeleterouterIDUpdateHello_capabilitiesnexthopRegisternexthopUnregisternexthopUpdate_interfaceNBRAddressAdd_interfaceNBRAddressDelete_interfaceBFDDestUpdate_importRouteRegister_importRouteUnregister_importCheckUpdate_bfdDestRegister_bfdDestDeregister_bfdDestUpdate_bfdDestReplayRedistributeRouteAddRedistributeRouteDel_vrfUnregister_vrfAdd_vrfDeletevrfLabel_interfaceVRFUpdate_bfdClientRegister_bfdClientDeregister_interfaceEnableRADV_interfaceDisableRADVipv4NexthopLookupMRIB_interfaceLinkParams_mplsLabelsAdd_mplsLabelsDelete_mplsLabelsReplace_srPolicySet_srPolicyDelete_srPolicyNotifyStatus_ipmrRouteStatslabelManagerConnectlabelManagerConnectAsyncgetLabelChunkreleaseLabelChunk_fecRegister_fecUnregister_fecUpdate_advertiseDefaultGW_advertiseSviMACIP_advertiseSubnet_advertiseAllVNI_localESAdd_localESDel_remoteESVTEPAdd_remoteESVTEPDel_localESEVIAdd_localESEVIDel_vniAdd_vniDel_l3VNIAdd_l3VNIDel_remoteVTEPAdd_remoteVTEPDel_macIPAdd_macIPDel_ipPrefixRouteAdd_ipPrefixRouteDel_remoteMACIPAdd_remoteMACIPDel_duplicateAddrDetection_pwAdd_pwDelete_pwSet_pwUnset_pwStatusUpdate_ruleAdd_ruleDelete_ruleNotifyOwner_tableManagerConnect_getTableChunk_releaseTableChunk_ipSetCreate_ipSetDestroy_ipSetEntryAdd_ipSetEntryDelete_ipSetNotifyOwner_ipSetEntryNotifyOwner_ipTableAdd_ipTableDelete_ipTableNotifyOwner_vxlanFloodControl_vxlanSgAdd_vxlanSgDel_vxlanSgReplay_mlagProcessUp_mlagProcessDown_mlagClientRegister_mlagClientUnregister_mlagClientForwardMsg_nhgAdd_nhgDel_nhgNotifyOwner_nhgEvpnRemoteNhAdd_nhgEvpnRemoteNhDel_srv6LocatorAdd_srv6LocatorDelete_srv6ManagerGetLocatorChunk_srv6ManagerReleaseLocatorChunkzebraError_clientCapabilities_opaqueMessage_opaqueRegister_opaqueUnregister_neighDiscover_RouteNotifyRequest_ClientCloseNotify_NhrpNeighAdded_NhrpNeighRemoved_NhrpNeighGet_NhrpNeighRegister_NhrpNeighUnregister_NeighIPAdd_NeighIPDel_ConfigureArp_GreGet_GreUpdate_GreSourceSetBackwardIPv6RouteAddBackwardIPv6RouteDelete"
var _APIType_index = [...]uint16{0, 12, 27, 46, 68, 79, 92, 111, 133, 141, 152, 169, 184, 203, 226, 252, 263, 278, 292, 297, 310, 325, 342, 355, 378, 404, 427, 447, 469, 487, 503, 521, 535, 549, 569, 589, 603, 610, 620, 628, 647, 665, 685, 705, 726, 747, 767, 781, 798, 816, 828, 843, 864, 879, 898, 922, 935, 952, 964, 978, 988, 1007, 1025, 1041, 1057, 1068, 1079, 1095, 1111, 1125, 1139, 1146, 1153, 1162, 1171, 1185, 1199, 1208, 1217, 1234, 1251, 1266, 1281, 1304, 1310, 1319, 1325, 1333, 1348, 1356, 1367, 1383, 1403, 1417, 1435, 1447, 1460, 1474, 1491, 1508, 1530, 1541, 1555, 1574, 1592, 1603, 1614, 1628, 1642, 1658, 1677, 1698, 1719, 1726, 1733, 1748, 1767, 1786, 1801, 1819, 1846, 1877, 1887, 1906, 1920, 1935, 1952, 1966, 1985, 2003, 2018, 2035, 2048, 2066, 2086, 2097, 2108, 2121, 2128, 2138, 2151, 2171, 2194}
func (i APIType) String() string {
if i >= APIType(len(_APIType_index)-1) {
return "APIType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _APIType_name[_APIType_index[i]:_APIType_index[i+1]]
}
@@ -1,72 +0,0 @@
// Code generated by "stringer -type=linkType"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[linkTypeUnknown-0]
_ = x[linkTypeEther-1]
_ = x[linkTypeEEther-2]
_ = x[linkTypeAX25-3]
_ = x[linkTypePRONET-4]
_ = x[linkTypeIeee802-5]
_ = x[linkTypeARCNET-6]
_ = x[linkTypeAPPLETLK-7]
_ = x[linkTypeDLCI-8]
_ = x[linkTypeATM-9]
_ = x[linkTypeMetricOM-10]
_ = x[linkTypeIeee1394-11]
_ = x[linkTypeEUI64-12]
_ = x[linkTypeINFINIBAND-13]
_ = x[linkTypeSLIP-14]
_ = x[linkTypeCSLIP-15]
_ = x[linkTypeSLIP6-16]
_ = x[linkTypeCSLIP6-17]
_ = x[linkTypeRSRVD-18]
_ = x[linkTypeADAPT-19]
_ = x[linkTypeROSE-20]
_ = x[linkTypeX25-21]
_ = x[linkTypePPP-22]
_ = x[linkTypeCHDLC-23]
_ = x[linkTypeLAPB-24]
_ = x[linkTypeRAWHDLC-25]
_ = x[linkTypeIPIP-26]
_ = x[linkTypeIPIP6-27]
_ = x[linkTypeFRAD-28]
_ = x[linkTypeSKIP-29]
_ = x[linkTypeLOOPBACK-30]
_ = x[linkTypeLOCALTLK-31]
_ = x[linkTypeFDDI-32]
_ = x[linkTypeSIT-33]
_ = x[linkTypeIPDDP-34]
_ = x[linkTypeIPGRE-35]
_ = x[linkTypeIP6GRE-36]
_ = x[linkTypePIMREG-37]
_ = x[linkTypeHIPPI-38]
_ = x[linkTypeECONET-39]
_ = x[linkTypeIRDA-40]
_ = x[linkTypeFCPP-41]
_ = x[linkTypeFCAL-42]
_ = x[linkTypeFCPL-43]
_ = x[linkTypeFCFABRIC-44]
_ = x[linkTypeIeee802Tr-45]
_ = x[linkTypeIeee80211-46]
_ = x[linkTypeIeee80211RadioTap-47]
_ = x[linkTypeIeee802154-48]
_ = x[linkTypeIeee802154Phy-49]
}
const _linkType_name = "linkTypeUnknownlinkTypeEtherlinkTypeEEtherlinkTypeAX25linkTypePRONETlinkTypeIeee802linkTypeARCNETlinkTypeAPPLETLKlinkTypeDLCIlinkTypeATMlinkTypeMetricOMlinkTypeIeee1394linkTypeEUI64linkTypeINFINIBANDlinkTypeSLIPlinkTypeCSLIPlinkTypeSLIP6linkTypeCSLIP6linkTypeRSRVDlinkTypeADAPTlinkTypeROSElinkTypeX25linkTypePPPlinkTypeCHDLClinkTypeLAPBlinkTypeRAWHDLClinkTypeIPIPlinkTypeIPIP6linkTypeFRADlinkTypeSKIPlinkTypeLOOPBACKlinkTypeLOCALTLKlinkTypeFDDIlinkTypeSITlinkTypeIPDDPlinkTypeIPGRElinkTypeIP6GRElinkTypePIMREGlinkTypeHIPPIlinkTypeECONETlinkTypeIRDAlinkTypeFCPPlinkTypeFCALlinkTypeFCPLlinkTypeFCFABRIClinkTypeIeee802TrlinkTypeIeee80211linkTypeIeee80211RadioTaplinkTypeIeee802154linkTypeIeee802154Phy"
var _linkType_index = [...]uint16{0, 15, 28, 42, 54, 68, 83, 97, 113, 125, 136, 152, 168, 181, 199, 211, 224, 237, 251, 264, 277, 289, 300, 311, 324, 336, 351, 363, 376, 388, 400, 416, 432, 444, 455, 468, 481, 495, 509, 522, 536, 548, 560, 572, 584, 600, 617, 634, 659, 677, 698}
func (i linkType) String() string {
if i >= linkType(len(_linkType_index)-1) {
return "linkType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _linkType_name[_linkType_index[i]:_linkType_index[i+1]]
}
@@ -1,28 +0,0 @@
// Code generated by "stringer -type=lspTYPE"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[lspNone-0]
_ = x[lspStatic-1]
_ = x[lspLDP-2]
_ = x[lspBGP-3]
_ = x[lspSR-4]
_ = x[lspSHARP-5]
}
const _lspTYPE_name = "lspNonelspStaticlspLDPlspBGPlspSRlspSHARP"
var _lspTYPE_index = [...]uint8{0, 7, 16, 22, 28, 33, 41}
func (i lspTYPE) String() string {
if i >= lspTYPE(len(_lspTYPE_index)-1) {
return "lspTYPE(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _lspTYPE_name[_lspTYPE_index[i]:_lspTYPE_index[i+1]]
}
@@ -1,61 +0,0 @@
// Code generated by "stringer -type=nexthopFlag"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[nexthopFlagActive-1]
_ = x[nexthopFlagFIB-2]
_ = x[nexthopFlagRecursive-4]
_ = x[nexthopFlagOnlink-8]
_ = x[nexthopFlagDuplicate-16]
_ = x[nexthopFlagRnhFiltered-32]
_ = x[nexthopFlagHasBackup-64]
_ = x[nexthopFlagSRTE-128]
_ = x[zapi6Frr7dot3nexthopFlagMatched-16]
_ = x[zapi6Frr7dot3nexthopFlagDuplicate-32]
_ = x[zapi6Frr7dot3nexthopFlagRnhFiltered-64]
_ = x[zapi6Frr7nexthopFlagFiltered-32]
_ = x[zapi6Frr7nexthopFlagDuplicate-64]
_ = x[zapi6Frr7nexthopFlagEvpnRvtep-128]
}
const (
_nexthopFlag_name_0 = "nexthopFlagActivenexthopFlagFIB"
_nexthopFlag_name_1 = "nexthopFlagRecursive"
_nexthopFlag_name_2 = "nexthopFlagOnlink"
_nexthopFlag_name_3 = "nexthopFlagDuplicate"
_nexthopFlag_name_4 = "nexthopFlagRnhFiltered"
_nexthopFlag_name_5 = "nexthopFlagHasBackup"
_nexthopFlag_name_6 = "nexthopFlagSRTE"
)
var (
_nexthopFlag_index_0 = [...]uint8{0, 17, 31}
)
func (i nexthopFlag) String() string {
switch {
case 1 <= i && i <= 2:
i -= 1
return _nexthopFlag_name_0[_nexthopFlag_index_0[i]:_nexthopFlag_index_0[i+1]]
case i == 4:
return _nexthopFlag_name_1
case i == 8:
return _nexthopFlag_name_2
case i == 16:
return _nexthopFlag_name_3
case i == 32:
return _nexthopFlag_name_4
case i == 64:
return _nexthopFlag_name_5
case i == 128:
return _nexthopFlag_name_6
default:
return "nexthopFlag(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
@@ -1,37 +0,0 @@
// Code generated by "stringer -type=nexthopType"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[nexthopTypeIFIndex-1]
_ = x[nexthopTypeIPv4-2]
_ = x[nexthopTypeIPv4IFIndex-3]
_ = x[nexthopTypeIPv6-4]
_ = x[nexthopTypeIPv6IFIndex-5]
_ = x[nexthopTypeBlackhole-6]
_ = x[nexthopTypeIFName-2]
_ = x[backwardNexthopTypeIPv4-3]
_ = x[backwardNexthopTypeIPv4IFIndex-4]
_ = x[nexthopTypeIPv4IFName-5]
_ = x[backwardNexthopTypeIPv6-6]
_ = x[backwardNexthopTypeIPv6IFIndex-7]
_ = x[nexthopTypeIPv6IFName-8]
_ = x[backwardNexthopTypeBlackhole-9]
}
const _nexthopType_name = "nexthopTypeIFIndexnexthopTypeIPv4nexthopTypeIPv4IFIndexnexthopTypeIPv6nexthopTypeIPv6IFIndexnexthopTypeBlackholebackwardNexthopTypeIPv6IFIndexnexthopTypeIPv6IFNamebackwardNexthopTypeBlackhole"
var _nexthopType_index = [...]uint8{0, 18, 33, 55, 70, 92, 112, 142, 163, 191}
func (i nexthopType) String() string {
i -= 1
if i >= nexthopType(len(_nexthopType_index)-1) {
return "nexthopType(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _nexthopType_name[_nexthopType_index[i]:_nexthopType_index[i+1]]
}
@@ -1,25 +0,0 @@
// Code generated by "stringer -type=ptmEnable"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[ptmEnableOff-0]
_ = x[ptmEnableOn-1]
_ = x[ptmEnableUnspec-2]
}
const _ptmEnable_name = "ptmEnableOffptmEnableOnptmEnableUnspec"
var _ptmEnable_index = [...]uint8{0, 12, 23, 38}
func (i ptmEnable) String() string {
if i >= ptmEnable(len(_ptmEnable_index)-1) {
return "ptmEnable(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _ptmEnable_name[_ptmEnable_index[i]:_ptmEnable_index[i+1]]
}
@@ -1,25 +0,0 @@
// Code generated by "stringer -type=ptmStatus"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[ptmStatusDown-0]
_ = x[ptmStatusUp-1]
_ = x[ptmStatusUnknown-2]
}
const _ptmStatus_name = "ptmStatusDownptmStatusUpptmStatusUnknown"
var _ptmStatus_index = [...]uint8{0, 13, 24, 40}
func (i ptmStatus) String() string {
if i >= ptmStatus(len(_ptmStatus_index)-1) {
return "ptmStatus(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _ptmStatus_name[_ptmStatus_index[i]:_ptmStatus_index[i+1]]
}
@@ -1,75 +0,0 @@
// Code generated by "stringer -type=RouteType"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[routeSystem-0]
_ = x[routeKernel-1]
_ = x[routeConnect-2]
_ = x[RouteStatic-3]
_ = x[routeRIP-4]
_ = x[routeRIPNG-5]
_ = x[routeOSPF-6]
_ = x[routeOSPF6-7]
_ = x[routeISIS-8]
_ = x[RouteBGP-9]
_ = x[routePIM-10]
_ = x[routeEIGRP-11]
_ = x[routeNHRP-12]
_ = x[routeHSLS-13]
_ = x[routeOLSR-14]
_ = x[routeTABLE-15]
_ = x[routeLDP-16]
_ = x[routeVNC-17]
_ = x[routeVNCDirect-18]
_ = x[routeVNCDirectRH-19]
_ = x[routeBGPDirect-20]
_ = x[routeBGPDirectEXT-21]
_ = x[routeBABEL-22]
_ = x[routeSHARP-23]
_ = x[routePBR-24]
_ = x[routeBFD-25]
_ = x[routeOpenfabric-26]
_ = x[routeVRRP-27]
_ = x[routeNHG-28]
_ = x[routeSRTE-29]
_ = x[routeAll-30]
_ = x[routeMax-31]
_ = x[zapi5Frr4RouteAll-24]
_ = x[zapi5Frr5RouteAll-25]
_ = x[zapi6Frr6RouteAll-26]
_ = x[zapi6Frr7RouteAll-27]
_ = x[zapi6Frr7dot2RouteAll-28]
_ = x[zapi6Frr7dot3RouteAll-29]
_ = x[zapi4RouteNHRP-11]
_ = x[zapi4RouteHSLS-12]
_ = x[zapi4RouteOLSR-13]
_ = x[zapi4RouteTABLE-14]
_ = x[zapi4RouteLDP-15]
_ = x[zapi4RouteVNC-16]
_ = x[zapi4RouteVNCDirect-17]
_ = x[zapi4RouteVNCDirectRH-18]
_ = x[zapi4RouteBGPDixrect-19]
_ = x[zapi4RouteBGPDirectEXT-20]
_ = x[zapi4RouteAll-21]
_ = x[zapi3RouteHSLS-11]
_ = x[zapi3RouteOLSR-12]
_ = x[zapi3RouteBABEL-13]
_ = x[zapi3RouteNHRP-14]
}
const _RouteType_name = "routeSystemrouteKernelrouteConnectRouteStaticrouteRIProuteRIPNGrouteOSPFrouteOSPF6routeISISRouteBGProutePIMrouteEIGRProuteNHRProuteHSLSrouteOLSRrouteTABLErouteLDProuteVNCrouteVNCDirectrouteVNCDirectRHrouteBGPDirectrouteBGPDirectEXTrouteBABELrouteSHARProutePBRrouteBFDrouteOpenfabricrouteVRRProuteNHGrouteSRTErouteAllrouteMax"
var _RouteType_index = [...]uint16{0, 11, 22, 34, 45, 53, 63, 72, 82, 91, 99, 107, 117, 126, 135, 144, 154, 162, 170, 184, 200, 214, 231, 241, 251, 259, 267, 282, 291, 299, 308, 316, 324}
func (i RouteType) String() string {
if i >= RouteType(len(_RouteType_index)-1) {
return "RouteType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _RouteType_name[_RouteType_index[i]:_RouteType_index[i+1]]
}
-36
View File
@@ -1,36 +0,0 @@
// Code generated by "stringer -type=Safi"; DO NOT EDIT.
package zebra
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[safiUnspec-0]
_ = x[SafiUnicast-1]
_ = x[safiMulticast-2]
_ = x[safiMplsVpn-3]
_ = x[safiEncap-4]
_ = x[safiEvpn-5]
_ = x[safiLabeledUnicast-6]
_ = x[safiFlowspec-7]
_ = x[safiMax-8]
_ = x[zapi4SafiMplsVpn-3]
_ = x[zapi3SafiMplsVpn-4]
_ = x[zapi4SafiEncap-5]
_ = x[zapi4SafiEvpn-6]
_ = x[zapi3SafiEncap-7]
}
const _Safi_name = "safiUnspecSafiUnicastsafiMulticastsafiMplsVpnsafiEncapsafiEvpnsafiLabeledUnicastsafiFlowspecsafiMax"
var _Safi_index = [...]uint8{0, 10, 21, 34, 45, 54, 62, 80, 92, 99}
func (i Safi) String() string {
if i >= Safi(len(_Safi_index)-1) {
return "Safi(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Safi_name[_Safi_index[i]:_Safi_index[i+1]]
}
File diff suppressed because it is too large Load Diff
-59
View File
@@ -1,59 +0,0 @@
// Copyright (C) 2014, 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build freebsd || netbsd || openbsd
// +build freebsd netbsd openbsd
package zebra
import (
"strings"
"syscall"
)
func intfflag2string(flag uint64) string {
ss := make([]string, 0, 10)
if flag&syscall.IFF_UP > 0 {
ss = append(ss, "UP")
}
if flag&syscall.IFF_BROADCAST > 0 {
ss = append(ss, "BROADCAST")
}
if flag&syscall.IFF_DEBUG > 0 {
ss = append(ss, "DEBUG")
}
if flag&syscall.IFF_LOOPBACK > 0 {
ss = append(ss, "LOOPBACK")
}
if flag&syscall.IFF_POINTOPOINT > 0 {
ss = append(ss, "POINTOPOINT")
}
if flag&syscall.IFF_RUNNING > 0 {
ss = append(ss, "RUNNING")
}
if flag&syscall.IFF_NOARP > 0 {
ss = append(ss, "NOARP")
}
if flag&syscall.IFF_PROMISC > 0 {
ss = append(ss, "PROMISC")
}
if flag&syscall.IFF_ALLMULTI > 0 {
ss = append(ss, "ALLMULTI")
}
if flag&syscall.IFF_MULTICAST > 0 {
ss = append(ss, "MULTICAST")
}
return strings.Join(ss, " | ")
}
-59
View File
@@ -1,59 +0,0 @@
// Copyright (C) 2014, 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package zebra
import (
"strings"
"syscall"
)
func intfflag2string(flag uint64) string {
ss := make([]string, 0, 10)
if flag&syscall.IFF_UP > 0 {
ss = append(ss, "UP")
}
if flag&syscall.IFF_BROADCAST > 0 {
ss = append(ss, "BROADCAST")
}
if flag&syscall.IFF_DEBUG > 0 {
ss = append(ss, "DEBUG")
}
if flag&syscall.IFF_LOOPBACK > 0 {
ss = append(ss, "LOOPBACK")
}
if flag&syscall.IFF_POINTOPOINT > 0 {
ss = append(ss, "POINTOPOINT")
}
if flag&syscall.IFF_NOTRAILERS > 0 {
ss = append(ss, "NOTRAILERS")
}
if flag&syscall.IFF_RUNNING > 0 {
ss = append(ss, "RUNNING")
}
if flag&syscall.IFF_NOARP > 0 {
ss = append(ss, "NOARP")
}
if flag&syscall.IFF_PROMISC > 0 {
ss = append(ss, "PROMISC")
}
if flag&syscall.IFF_ALLMULTI > 0 {
ss = append(ss, "ALLMULTI")
}
if flag&syscall.IFF_MULTICAST > 0 {
ss = append(ss, "MULTICAST")
}
return strings.Join(ss, " | ")
}
-83
View File
@@ -1,83 +0,0 @@
// Copyright (C) 2014, 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package zebra
import (
"strings"
"syscall"
)
func intfflag2string(flag uint64) string {
ss := make([]string, 0, 10)
if flag&syscall.IFF_UP > 0 {
ss = append(ss, "UP")
}
if flag&syscall.IFF_BROADCAST > 0 {
ss = append(ss, "BROADCAST")
}
if flag&syscall.IFF_DEBUG > 0 {
ss = append(ss, "DEBUG")
}
if flag&syscall.IFF_LOOPBACK > 0 {
ss = append(ss, "LOOPBACK")
}
if flag&syscall.IFF_POINTOPOINT > 0 {
ss = append(ss, "POINTOPOINT")
}
if flag&syscall.IFF_NOTRAILERS > 0 {
ss = append(ss, "NOTRAILERS")
}
if flag&syscall.IFF_RUNNING > 0 {
ss = append(ss, "RUNNING")
}
if flag&syscall.IFF_NOARP > 0 {
ss = append(ss, "NOARP")
}
if flag&syscall.IFF_PROMISC > 0 {
ss = append(ss, "PROMISC")
}
if flag&syscall.IFF_ALLMULTI > 0 {
ss = append(ss, "ALLMULTI")
}
if flag&syscall.IFF_MASTER > 0 {
ss = append(ss, "MASTER")
}
if flag&syscall.IFF_SLAVE > 0 {
ss = append(ss, "SLAVE")
}
if flag&syscall.IFF_MULTICAST > 0 {
ss = append(ss, "MULTICAST")
}
if flag&syscall.IFF_PORTSEL > 0 {
ss = append(ss, "PORTSEL")
}
if flag&syscall.IFF_AUTOMEDIA > 0 {
ss = append(ss, "AUTOMEDIA")
}
if flag&syscall.IFF_DYNAMIC > 0 {
ss = append(ss, "DYNAMIC")
}
// if flag&syscall.IFF_LOWER_UP > 0 {
// ss = append(ss, "LOWER_UP")
// }
// if flag&syscall.IFF_DORMANT > 0 {
// ss = append(ss, "DORMANT")
// }
// if flag&syscall.IFF_ECHO > 0 {
// ss = append(ss, "ECHO")
// }
return strings.Join(ss, " | ")
}
-38
View File
@@ -1,38 +0,0 @@
// Copyright (C) 2014, 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package zebra
import (
"strings"
"syscall"
)
func intfflag2string(flag uint64) string {
ss := make([]string, 0, 10)
if flag&syscall.IFF_UP > 0 {
ss = append(ss, "UP")
}
if flag&syscall.IFF_BROADCAST > 0 {
ss = append(ss, "BROADCAST")
}
if flag&syscall.IFF_LOOPBACK > 0 {
ss = append(ss, "LOOPBACK")
}
if flag&syscall.IFF_MULTICAST > 0 {
ss = append(ss, "MULTICAST")
}
return strings.Join(ss, " | ")
}
@@ -1,4 +0,0 @@
logrus
vendor
.idea/
-40
View File
@@ -1,40 +0,0 @@
run:
# do not run on test files yet
tests: false
# all available settings of specific linters
linters-settings:
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: false
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: false
lll:
line-length: 100
tab-width: 4
prealloc:
simple: false
range-loops: false
for-loops: false
whitespace:
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-func: false # Enforces newlines (or comments) after every multi-line function signature
linters:
enable:
- megacheck
- govet
disable:
- maligned
- prealloc
disable-all: false
presets:
- bugs
- unused
fast: false
-15
View File
@@ -1,15 +0,0 @@
language: go
go_import_path: github.com/sirupsen/logrus
git:
depth: 1
env:
- GO111MODULE=on
go: 1.15.x
os: linux
install:
- ./travis/install.sh
script:
- cd ci
- go run mage.go -v -w ../ crossBuild
- go run mage.go -v -w ../ lint
- go run mage.go -v -w ../ test
-259
View File
@@ -1,259 +0,0 @@
# 1.8.1
Code quality:
* move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer
* improve timestamp format documentation
Fixes:
* fix race condition on logger hooks
# 1.8.0
Correct versioning number replacing v1.7.1.
# 1.7.1
Beware this release has introduced a new public API and its semver is therefore incorrect.
Code quality:
* use go 1.15 in travis
* use magefile as task runner
Fixes:
* small fixes about new go 1.13 error formatting system
* Fix for long time race condiction with mutating data hooks
Features:
* build support for zos
# 1.7.0
Fixes:
* the dependency toward a windows terminal library has been removed
Features:
* a new buffer pool management API has been added
* a set of `<LogLevel>Fn()` functions have been added
# 1.6.0
Fixes:
* end of line cleanup
* revert the entry concurrency bug fix whic leads to deadlock under some circumstances
* update dependency on go-windows-terminal-sequences to fix a crash with go 1.14
Features:
* add an option to the `TextFormatter` to completely disable fields quoting
# 1.5.0
Code quality:
* add golangci linter run on travis
Fixes:
* add mutex for hooks concurrent access on `Entry` data
* caller function field for go1.14
* fix build issue for gopherjs target
Feature:
* add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level
* add a `DisableHTMLEscape` option in the `JSONFormatter`
* add `ForceQuote` and `PadLevelText` options in the `TextFormatter`
# 1.4.2
* Fixes build break for plan9, nacl, solaris
# 1.4.1
This new release introduces:
* Enhance TextFormatter to not print caller information when they are empty (#944)
* Remove dependency on golang.org/x/crypto (#932, #943)
Fixes:
* Fix Entry.WithContext method to return a copy of the initial entry (#941)
# 1.4.0
This new release introduces:
* Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
* Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911)
* Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
Fixes:
* Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
* Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
* Fix infinite recursion on unknown `Level.String()` (#907)
* Fix race condition in `getCaller` (#916).
# 1.3.0
This new release introduces:
* Log, Logf, Logln functions for Logger and Entry that take a Level
Fixes:
* Building prometheus node_exporter on AIX (#840)
* Race condition in TextFormatter (#468)
* Travis CI import path (#868)
* Remove coloured output on Windows (#862)
* Pointer to func as field in JSONFormatter (#870)
* Properly marshal Levels (#873)
# 1.2.0
This new release introduces:
* A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued
* A new trace level named `Trace` whose level is below `Debug`
* A configurable exit function to be called upon a Fatal trace
* The `Level` object now implements `encoding.TextUnmarshaler` interface
# 1.1.1
This is a bug fix release.
* fix the build break on Solaris
* don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized
# 1.1.0
This new release introduces:
* several fixes:
* a fix for a race condition on entry formatting
* proper cleanup of previously used entries before putting them back in the pool
* the extra new line at the end of message in text formatter has been removed
* a new global public API to check if a level is activated: IsLevelEnabled
* the following methods have been added to the Logger object
* IsLevelEnabled
* SetFormatter
* SetOutput
* ReplaceHooks
* introduction of go module
* an indent configuration for the json formatter
* output colour support for windows
* the field sort function is now configurable for text formatter
* the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater
# 1.0.6
This new release introduces:
* a new api WithTime which allows to easily force the time of the log entry
which is mostly useful for logger wrapper
* a fix reverting the immutability of the entry given as parameter to the hooks
a new configuration field of the json formatter in order to put all the fields
in a nested dictionnary
* a new SetOutput method in the Logger
* a new configuration of the textformatter to configure the name of the default keys
* a new configuration of the text formatter to disable the level truncation
# 1.0.5
* Fix hooks race (#707)
* Fix panic deadlock (#695)
# 1.0.4
* Fix race when adding hooks (#612)
* Fix terminal check in AppEngine (#635)
# 1.0.3
* Replace example files with testable examples
# 1.0.2
* bug: quote non-string values in text formatter (#583)
* Make (*Logger) SetLevel a public method
# 1.0.1
* bug: fix escaping in text formatter (#575)
# 1.0.0
* Officially changed name to lower-case
* bug: colors on Windows 10 (#541)
* bug: fix race in accessing level (#512)
# 0.11.5
* feature: add writer and writerlevel to entry (#372)
# 0.11.4
* bug: fix undefined variable on solaris (#493)
# 0.11.3
* formatter: configure quoting of empty values (#484)
* formatter: configure quoting character (default is `"`) (#484)
* bug: fix not importing io correctly in non-linux environments (#481)
# 0.11.2
* bug: fix windows terminal detection (#476)
# 0.11.1
* bug: fix tty detection with custom out (#471)
# 0.11.0
* performance: Use bufferpool to allocate (#370)
* terminal: terminal detection for app-engine (#343)
* feature: exit handler (#375)
# 0.10.0
* feature: Add a test hook (#180)
* feature: `ParseLevel` is now case-insensitive (#326)
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
* performance: avoid re-allocations on `WithFields` (#335)
# 0.9.0
* logrus/text_formatter: don't emit empty msg
* logrus/hooks/airbrake: move out of main repository
* logrus/hooks/sentry: move out of main repository
* logrus/hooks/papertrail: move out of main repository
* logrus/hooks/bugsnag: move out of main repository
* logrus/core: run tests with `-race`
* logrus/core: detect TTY based on `stderr`
* logrus/core: support `WithError` on logger
* logrus/core: Solaris support
# 0.8.7
* logrus/core: fix possible race (#216)
* logrus/doc: small typo fixes and doc improvements
# 0.8.6
* hooks/raven: allow passing an initialized client
# 0.8.5
* logrus/core: revert #208
# 0.8.4
* formatter/text: fix data race (#218)
# 0.8.3
* logrus/core: fix entry log level (#208)
* logrus/core: improve performance of text formatter by 40%
* logrus/core: expose `LevelHooks` type
* logrus/core: add support for DragonflyBSD and NetBSD
* formatter/text: print structs more verbosely
# 0.8.2
* logrus: fix more Fatal family functions
# 0.8.1
* logrus: fix not exiting on `Fatalf` and `Fatalln`
# 0.8.0
* logrus: defaults to stderr instead of stdout
* hooks/sentry: add special field for `*http.Request`
* formatter/text: ignore Windows for colors
# 0.7.3
* formatter/\*: allow configuration of timestamp layout
# 0.7.2
* formatter/text: Add configuration option for time format (#158)
-515
View File
@@ -1,515 +0,0 @@
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus)
Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger.
**Logrus is in maintenance-mode.** We will not be introducing new features. It's
simply too hard to do in a way that won't break many people's projects, which is
the last thing you want from your Logging library (again...).
This does not mean Logrus is dead. Logrus will continue to be maintained for
security, (backwards compatible) bug fixes, and performance (where we are
limited by the interface).
I believe Logrus' biggest contribution is to have played a part in today's
widespread use of structured logging in Golang. There doesn't seem to be a
reason to do a major, breaking iteration into Logrus V2, since the fantastic Go
community has built those independently. Many fantastic alternatives have sprung
up. Logrus would look like those, had it been re-designed with what we know
about structured logging in Go today. Check out, for example,
[Zerolog][zerolog], [Zap][zap], and [Apex][apex].
[zerolog]: https://github.com/rs/zerolog
[zap]: https://github.com/uber-go/zap
[apex]: https://github.com/apex/log
**Seeing weird case-sensitive problems?** It's in the past been possible to
import Logrus as both upper- and lower-case. Due to the Go package environment,
this caused issues in the community and we needed a standard. Some environments
experienced problems with the upper-case variant, so the lower-case was decided.
Everything using `logrus` will need to use the lower-case:
`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
To fix Glide, see [these
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
For an in-depth explanation of the casing issue, see [this
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
Nicely color-coded in development (when a TTY is attached, otherwise just
plain text):
![Colored](http://i.imgur.com/PY7qMwd.png)
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
or Splunk:
```text
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
{"level":"warning","msg":"The group's number increased tremendously!",
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
```
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
attached, the output is compatible with the
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
```text
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
```
To ensure this behaviour even if a TTY is attached, set your formatter as follows:
```go
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
```
#### Logging Method Name
If you wish to add the calling method as a field, instruct the logger via:
```go
log.SetReportCaller(true)
```
This adds the caller as 'method' like so:
```json
{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by",
"time":"2014-03-10 19:57:38.562543129 -0400 EDT"}
```
```text
time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin
```
Note that this does add measurable overhead - the cost will depend on the version of Go, but is
between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your
environment via benchmarks:
```
go test -bench=.*CallerTracing
```
#### Case-sensitivity
The organization's name was changed to lower-case--and this will not be changed
back. If you are getting import conflicts due to case sensitivity, please use
the lower-case import: `github.com/sirupsen/logrus`.
#### Example
The simplest way to use Logrus is simply the package-level exported logger:
```go
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
}).Info("A walrus appears")
}
```
Note that it's completely api-compatible with the stdlib logger, so you can
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
and you'll now have the flexibility of Logrus. You can customize it all you
want:
```go
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
func init() {
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.WarnLevel)
}
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(log.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(log.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
// A common pattern is to re-use fields between logging statements by re-using
// the logrus.Entry returned from WithFields()
contextLogger := log.WithFields(log.Fields{
"common": "this is a common field",
"other": "I also should be logged always",
})
contextLogger.Info("I'll be logged with common and other field")
contextLogger.Info("Me too")
}
```
For more advanced usage such as logging to multiple locations from the same
application, you can also create an instance of the `logrus` Logger:
```go
package main
import (
"os"
"github.com/sirupsen/logrus"
)
// Create a new instance of the logger. You can have any number of instances.
var log = logrus.New()
func main() {
// The API for setting attributes is a little different than the package level
// exported logger. See Godoc.
log.Out = os.Stdout
// You could set this to any `io.Writer` such as a file
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
// if err == nil {
// log.Out = file
// } else {
// log.Info("Failed to log to file, using default stderr")
// }
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
```
#### Fields
Logrus encourages careful, structured logging through logging fields instead of
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
to send event %s to topic %s with key %d")`, you should log the much more
discoverable:
```go
log.WithFields(log.Fields{
"event": event,
"topic": topic,
"key": key,
}).Fatal("Failed to send event")
```
We've found this API forces you to think about logging in a way that produces
much more useful logging messages. We've been in countless situations where just
a single added field to a log statement that was already there would've saved us
hours. The `WithFields` call is optional.
In general, with Logrus using any of the `printf`-family functions should be
seen as a hint you should add a field, however, you can still use the
`printf`-family functions with Logrus.
#### Default Fields
Often it's helpful to have fields _always_ attached to log statements in an
application or parts of one. For example, you may want to always log the
`request_id` and `user_ip` in the context of a request. Instead of writing
`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
every line, you can create a `logrus.Entry` to pass around instead:
```go
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") # will log request_id and user_ip
requestLogger.Warn("something not great happened")
```
#### Hooks
You can add hooks for logging levels. For example to send errors to an exception
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
multiple places simultaneously, e.g. syslog.
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
`init`:
```go
import (
log "github.com/sirupsen/logrus"
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
"log/syslog"
)
func init() {
// Use the Airbrake hook to report errors that have Error severity or above to
// an exception tracker. You can create custom hooks, see the Hooks section.
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err != nil {
log.Error("Unable to connect to local syslog daemon")
} else {
log.AddHook(hook)
}
}
```
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)
#### Level logging
Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.
```go
log.Trace("Something very low level.")
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")
```
You can set the logging level on a `Logger`, then it will only log entries with
that severity or anything above it:
```go
// Will log anything that is info or above (warn, error, fatal, panic). Default.
log.SetLevel(log.InfoLevel)
```
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
environment if your application has that.
Note: If you want different log levels for global (`log.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging).
#### Entries
Besides the fields added with `WithField` or `WithFields` some fields are
automatically added to all logging events:
1. `time`. The timestamp when the entry was created.
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
the `AddFields` call. E.g. `Failed to send event.`
3. `level`. The logging level. E.g. `info`.
#### Environments
Logrus has no notion of environment.
If you wish for hooks and formatters to only be used in specific environments,
you should handle that yourself. For example, if your application has a global
variable `Environment`, which is a string representation of the environment you
could do:
```go
import (
log "github.com/sirupsen/logrus"
)
func init() {
// do something here to set environment depending on an environment variable
// or command-line flag
if Environment == "production" {
log.SetFormatter(&log.JSONFormatter{})
} else {
// The TextFormatter is default, you don't actually have to do this.
log.SetFormatter(&log.TextFormatter{})
}
}
```
This configuration is how `logrus` was intended to be used, but JSON in
production is mostly only useful if you do log aggregation with tools like
Splunk or Logstash.
#### Formatters
The built-in logging formatters are:
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
without colors.
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
field to `true`. To force no colored output even if there is a TTY set the
`DisableColors` field to `true`. For Windows, see
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
* When colors are enabled, levels are truncated to 4 characters by default. To disable
truncation set the `DisableLevelTruncation` field to `true`.
* When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
* `logrus.JSONFormatter`. Logs fields as JSON.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
Third party logging formatters:
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.
* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html).
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo.
* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files.
* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added.
You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
`Fields` type (`map[string]interface{}`) with all your fields as well as the
default ones (see Entries section above):
```go
type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note this doesn't include Time, Level and Message which are available on
// the Entry. Consult `godoc` on information about those fields or read the
// source of the official loggers.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err)
}
return append(serialized, '\n'), nil
}
```
#### Logger as an `io.Writer`
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
```go
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
```
Each line written to that writer will be printed the usual way, using formatters
and hooks. The level for those entries is `info`.
This means that we can override the standard library logger easily:
```go
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
```
#### Rotation
Log rotation is not provided with Logrus. Log rotation should be done by an
external program (like `logrotate(8)`) that can compress and delete old log
entries. It should not be a feature of the application-level logger.
#### Tools
| Tool | Description |
| ---- | ----------- |
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.|
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
#### Testing
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
```go
import(
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
"testing"
)
func TestSomething(t*testing.T){
logger, hook := test.NewNullLogger()
logger.Error("Helloerror")
assert.Equal(t, 1, len(hook.Entries))
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal(t, "Helloerror", hook.LastEntry().Message)
hook.Reset()
assert.Nil(t, hook.LastEntry())
}
```
#### Fatal handlers
Logrus can register one or more functions that will be called when any `fatal`
level message is logged. The registered handlers will be executed before
logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
```
...
handler := func() {
// gracefully shutdown something...
}
logrus.RegisterExitHandler(handler)
...
```
#### Thread safety
By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs.
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
Situation when locking is not needed includes:
* You have no hooks registered, or hooks calling is already thread-safe.
* Writing to logger.Out is already thread-safe, for example:
1) logger.Out is protected by locks.
2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing)
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
-76
View File
@@ -1,76 +0,0 @@
package logrus
// The following code was sourced and modified from the
// https://github.com/tebeka/atexit package governed by the following license:
//
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import (
"fmt"
"os"
)
var handlers = []func(){}
func runHandler(handler func()) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
}
}()
handler()
}
func runHandlers() {
for _, handler := range handlers {
runHandler(handler)
}
}
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
func Exit(code int) {
runHandlers()
os.Exit(code)
}
// RegisterExitHandler appends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func RegisterExitHandler(handler func()) {
handlers = append(handlers, handler)
}
// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func DeferExitHandler(handler func()) {
handlers = append([]func(){handler}, handlers...)
}
-14
View File
@@ -1,14 +0,0 @@
version: "{build}"
platform: x64
clone_folder: c:\gopath\src\github.com\sirupsen\logrus
environment:
GOPATH: c:\gopath
branches:
only:
- master
install:
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- go version
build_script:
- go get -t
- go test
-43
View File
@@ -1,43 +0,0 @@
package logrus
import (
"bytes"
"sync"
)
var (
bufferPool BufferPool
)
type BufferPool interface {
Put(*bytes.Buffer)
Get() *bytes.Buffer
}
type defaultPool struct {
pool *sync.Pool
}
func (p *defaultPool) Put(buf *bytes.Buffer) {
p.pool.Put(buf)
}
func (p *defaultPool) Get() *bytes.Buffer {
return p.pool.Get().(*bytes.Buffer)
}
// SetBufferPool allows to replace the default logrus buffer pool
// to better meets the specific needs of an application.
func SetBufferPool(bp BufferPool) {
bufferPool = bp
}
func init() {
SetBufferPool(&defaultPool{
pool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
})
}
-26
View File
@@ -1,26 +0,0 @@
/*
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
The simplest way to use Logrus is simply the package-level exported logger:
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"number": 1,
"size": 10,
}).Info("A walrus appears")
}
Output:
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
For a full guide visit https://github.com/sirupsen/logrus
*/
package logrus
-442
View File
@@ -1,442 +0,0 @@
package logrus
import (
"bytes"
"context"
"fmt"
"os"
"reflect"
"runtime"
"strings"
"sync"
"time"
)
var (
// qualified package name, cached at first use
logrusPackage string
// Positions in the call stack when tracing to report the calling method
minimumCallerDepth int
// Used for caller information initialisation
callerInitOnce sync.Once
)
const (
maximumCallerDepth int = 25
knownLogrusFrames int = 4
)
func init() {
// start at the bottom of the stack before the package-name cache is primed
minimumCallerDepth = 1
}
// Defines the key when adding errors using WithError.
var ErrorKey = "error"
// An entry is the final or intermediate Logrus logging entry. It contains all
// the fields passed with WithField{,s}. It's finally logged when Trace, Debug,
// Info, Warn, Error, Fatal or Panic is called on it. These objects can be
// reused and passed around as much as you wish to avoid field duplication.
type Entry struct {
Logger *Logger
// Contains all the fields set by the user.
Data Fields
// Time at which the log entry was created
Time time.Time
// Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
// This field will be set on entry firing and the value will be equal to the one in Logger struct field.
Level Level
// Calling method, with package name
Caller *runtime.Frame
// Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
Message string
// When formatter is called in entry.log(), a Buffer may be set to entry
Buffer *bytes.Buffer
// Contains the context set by the user. Useful for hook processing etc.
Context context.Context
// err may contain a field formatting error
err string
}
func NewEntry(logger *Logger) *Entry {
return &Entry{
Logger: logger,
// Default is three fields, plus one optional. Give a little extra room.
Data: make(Fields, 6),
}
}
func (entry *Entry) Dup() *Entry {
data := make(Fields, len(entry.Data))
for k, v := range entry.Data {
data[k] = v
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err}
}
// Returns the bytes representation of this entry from the formatter.
func (entry *Entry) Bytes() ([]byte, error) {
return entry.Logger.Formatter.Format(entry)
}
// Returns the string representation from the reader and ultimately the
// formatter.
func (entry *Entry) String() (string, error) {
serialized, err := entry.Bytes()
if err != nil {
return "", err
}
str := string(serialized)
return str, nil
}
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
func (entry *Entry) WithError(err error) *Entry {
return entry.WithField(ErrorKey, err)
}
// Add a context to the Entry.
func (entry *Entry) WithContext(ctx context.Context) *Entry {
dataCopy := make(Fields, len(entry.Data))
for k, v := range entry.Data {
dataCopy[k] = v
}
return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx}
}
// Add a single field to the Entry.
func (entry *Entry) WithField(key string, value interface{}) *Entry {
return entry.WithFields(Fields{key: value})
}
// Add a map of fields to the Entry.
func (entry *Entry) WithFields(fields Fields) *Entry {
data := make(Fields, len(entry.Data)+len(fields))
for k, v := range entry.Data {
data[k] = v
}
fieldErr := entry.err
for k, v := range fields {
isErrField := false
if t := reflect.TypeOf(v); t != nil {
switch {
case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func:
isErrField = true
}
}
if isErrField {
tmp := fmt.Sprintf("can not add field %q", k)
if fieldErr != "" {
fieldErr = entry.err + ", " + tmp
} else {
fieldErr = tmp
}
} else {
data[k] = v
}
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
}
// Overrides the time of the Entry.
func (entry *Entry) WithTime(t time.Time) *Entry {
dataCopy := make(Fields, len(entry.Data))
for k, v := range entry.Data {
dataCopy[k] = v
}
return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context}
}
// getPackageName reduces a fully qualified function name to the package name
// There really ought to be to be a better way...
func getPackageName(f string) string {
for {
lastPeriod := strings.LastIndex(f, ".")
lastSlash := strings.LastIndex(f, "/")
if lastPeriod > lastSlash {
f = f[:lastPeriod]
} else {
break
}
}
return f
}
// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
pcs := make([]uintptr, maximumCallerDepth)
_ = runtime.Callers(0, pcs)
// dynamic get the package name and the minimum caller depth
for i := 0; i < maximumCallerDepth; i++ {
funcName := runtime.FuncForPC(pcs[i]).Name()
if strings.Contains(funcName, "getCaller") {
logrusPackage = getPackageName(funcName)
break
}
}
minimumCallerDepth = knownLogrusFrames
})
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
// If the caller isn't part of this package, we're done
if pkg != logrusPackage {
return &f //nolint:scopelint
}
}
// if we got here, we failed to find the caller's context
return nil
}
func (entry Entry) HasCaller() (has bool) {
return entry.Logger != nil &&
entry.Logger.ReportCaller &&
entry.Caller != nil
}
func (entry *Entry) log(level Level, msg string) {
var buffer *bytes.Buffer
newEntry := entry.Dup()
if newEntry.Time.IsZero() {
newEntry.Time = time.Now()
}
newEntry.Level = level
newEntry.Message = msg
newEntry.Logger.mu.Lock()
reportCaller := newEntry.Logger.ReportCaller
bufPool := newEntry.getBufferPool()
newEntry.Logger.mu.Unlock()
if reportCaller {
newEntry.Caller = getCaller()
}
newEntry.fireHooks()
buffer = bufPool.Get()
defer func() {
newEntry.Buffer = nil
buffer.Reset()
bufPool.Put(buffer)
}()
buffer.Reset()
newEntry.Buffer = buffer
newEntry.write()
newEntry.Buffer = nil
// To avoid Entry#log() returning a value that only would make sense for
// panic() to use in Entry#Panic(), we avoid the allocation by checking
// directly here.
if level <= PanicLevel {
panic(newEntry)
}
}
func (entry *Entry) getBufferPool() (pool BufferPool) {
if entry.Logger.BufferPool != nil {
return entry.Logger.BufferPool
}
return bufferPool
}
func (entry *Entry) fireHooks() {
var tmpHooks LevelHooks
entry.Logger.mu.Lock()
tmpHooks = make(LevelHooks, len(entry.Logger.Hooks))
for k, v := range entry.Logger.Hooks {
tmpHooks[k] = v
}
entry.Logger.mu.Unlock()
err := tmpHooks.Fire(entry.Level, entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
}
}
func (entry *Entry) write() {
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
serialized, err := entry.Logger.Formatter.Format(entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
return
}
if _, err := entry.Logger.Out.Write(serialized); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
}
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Entry.Panic or Entry.Fatal should be used instead.
func (entry *Entry) Log(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.log(level, fmt.Sprint(args...))
}
}
func (entry *Entry) Trace(args ...interface{}) {
entry.Log(TraceLevel, args...)
}
func (entry *Entry) Debug(args ...interface{}) {
entry.Log(DebugLevel, args...)
}
func (entry *Entry) Print(args ...interface{}) {
entry.Info(args...)
}
func (entry *Entry) Info(args ...interface{}) {
entry.Log(InfoLevel, args...)
}
func (entry *Entry) Warn(args ...interface{}) {
entry.Log(WarnLevel, args...)
}
func (entry *Entry) Warning(args ...interface{}) {
entry.Warn(args...)
}
func (entry *Entry) Error(args ...interface{}) {
entry.Log(ErrorLevel, args...)
}
func (entry *Entry) Fatal(args ...interface{}) {
entry.Log(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panic(args ...interface{}) {
entry.Log(PanicLevel, args...)
}
// Entry Printf family functions
func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Tracef(format string, args ...interface{}) {
entry.Logf(TraceLevel, format, args...)
}
func (entry *Entry) Debugf(format string, args ...interface{}) {
entry.Logf(DebugLevel, format, args...)
}
func (entry *Entry) Infof(format string, args ...interface{}) {
entry.Logf(InfoLevel, format, args...)
}
func (entry *Entry) Printf(format string, args ...interface{}) {
entry.Infof(format, args...)
}
func (entry *Entry) Warnf(format string, args ...interface{}) {
entry.Logf(WarnLevel, format, args...)
}
func (entry *Entry) Warningf(format string, args ...interface{}) {
entry.Warnf(format, args...)
}
func (entry *Entry) Errorf(format string, args ...interface{}) {
entry.Logf(ErrorLevel, format, args...)
}
func (entry *Entry) Fatalf(format string, args ...interface{}) {
entry.Logf(FatalLevel, format, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...interface{}) {
entry.Logf(PanicLevel, format, args...)
}
// Entry Println family functions
func (entry *Entry) Logln(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, entry.sprintlnn(args...))
}
}
func (entry *Entry) Traceln(args ...interface{}) {
entry.Logln(TraceLevel, args...)
}
func (entry *Entry) Debugln(args ...interface{}) {
entry.Logln(DebugLevel, args...)
}
func (entry *Entry) Infoln(args ...interface{}) {
entry.Logln(InfoLevel, args...)
}
func (entry *Entry) Println(args ...interface{}) {
entry.Infoln(args...)
}
func (entry *Entry) Warnln(args ...interface{}) {
entry.Logln(WarnLevel, args...)
}
func (entry *Entry) Warningln(args ...interface{}) {
entry.Warnln(args...)
}
func (entry *Entry) Errorln(args ...interface{}) {
entry.Logln(ErrorLevel, args...)
}
func (entry *Entry) Fatalln(args ...interface{}) {
entry.Logln(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicln(args ...interface{}) {
entry.Logln(PanicLevel, args...)
}
// Sprintlnn => Sprint no newline. This is to get the behavior of how
// fmt.Sprintln where spaces are always added between operands, regardless of
// their type. Instead of vendoring the Sprintln implementation to spare a
// string allocation, we do the simplest thing.
func (entry *Entry) sprintlnn(args ...interface{}) string {
msg := fmt.Sprintln(args...)
return msg[:len(msg)-1]
}
-270
View File
@@ -1,270 +0,0 @@
package logrus
import (
"context"
"io"
"time"
)
var (
// std is the name of the standard logger in stdlib `log`
std = New()
)
func StandardLogger() *Logger {
return std
}
// SetOutput sets the standard logger output.
func SetOutput(out io.Writer) {
std.SetOutput(out)
}
// SetFormatter sets the standard logger formatter.
func SetFormatter(formatter Formatter) {
std.SetFormatter(formatter)
}
// SetReportCaller sets whether the standard logger will include the calling
// method as a field.
func SetReportCaller(include bool) {
std.SetReportCaller(include)
}
// SetLevel sets the standard logger level.
func SetLevel(level Level) {
std.SetLevel(level)
}
// GetLevel returns the standard logger level.
func GetLevel() Level {
return std.GetLevel()
}
// IsLevelEnabled checks if the log level of the standard logger is greater than the level param
func IsLevelEnabled(level Level) bool {
return std.IsLevelEnabled(level)
}
// AddHook adds a hook to the standard logger hooks.
func AddHook(hook Hook) {
std.AddHook(hook)
}
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
func WithError(err error) *Entry {
return std.WithField(ErrorKey, err)
}
// WithContext creates an entry from the standard logger and adds a context to it.
func WithContext(ctx context.Context) *Entry {
return std.WithContext(ctx)
}
// WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithField(key string, value interface{}) *Entry {
return std.WithField(key, value)
}
// WithFields creates an entry from the standard logger and adds multiple
// fields to it. This is simply a helper for `WithField`, invoking it
// once for each field.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithFields(fields Fields) *Entry {
return std.WithFields(fields)
}
// WithTime creates an entry from the standard logger and overrides the time of
// logs generated with it.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithTime(t time.Time) *Entry {
return std.WithTime(t)
}
// Trace logs a message at level Trace on the standard logger.
func Trace(args ...interface{}) {
std.Trace(args...)
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) {
std.Debug(args...)
}
// Print logs a message at level Info on the standard logger.
func Print(args ...interface{}) {
std.Print(args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
std.Info(args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...interface{}) {
std.Warn(args...)
}
// Warning logs a message at level Warn on the standard logger.
func Warning(args ...interface{}) {
std.Warning(args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...interface{}) {
std.Error(args...)
}
// Panic logs a message at level Panic on the standard logger.
func Panic(args ...interface{}) {
std.Panic(args...)
}
// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatal(args ...interface{}) {
std.Fatal(args...)
}
// TraceFn logs a message from a func at level Trace on the standard logger.
func TraceFn(fn LogFunction) {
std.TraceFn(fn)
}
// DebugFn logs a message from a func at level Debug on the standard logger.
func DebugFn(fn LogFunction) {
std.DebugFn(fn)
}
// PrintFn logs a message from a func at level Info on the standard logger.
func PrintFn(fn LogFunction) {
std.PrintFn(fn)
}
// InfoFn logs a message from a func at level Info on the standard logger.
func InfoFn(fn LogFunction) {
std.InfoFn(fn)
}
// WarnFn logs a message from a func at level Warn on the standard logger.
func WarnFn(fn LogFunction) {
std.WarnFn(fn)
}
// WarningFn logs a message from a func at level Warn on the standard logger.
func WarningFn(fn LogFunction) {
std.WarningFn(fn)
}
// ErrorFn logs a message from a func at level Error on the standard logger.
func ErrorFn(fn LogFunction) {
std.ErrorFn(fn)
}
// PanicFn logs a message from a func at level Panic on the standard logger.
func PanicFn(fn LogFunction) {
std.PanicFn(fn)
}
// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.
func FatalFn(fn LogFunction) {
std.FatalFn(fn)
}
// Tracef logs a message at level Trace on the standard logger.
func Tracef(format string, args ...interface{}) {
std.Tracef(format, args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
std.Debugf(format, args...)
}
// Printf logs a message at level Info on the standard logger.
func Printf(format string, args ...interface{}) {
std.Printf(format, args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...interface{}) {
std.Infof(format, args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
std.Warnf(format, args...)
}
// Warningf logs a message at level Warn on the standard logger.
func Warningf(format string, args ...interface{}) {
std.Warningf(format, args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
std.Errorf(format, args...)
}
// Panicf logs a message at level Panic on the standard logger.
func Panicf(format string, args ...interface{}) {
std.Panicf(format, args...)
}
// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalf(format string, args ...interface{}) {
std.Fatalf(format, args...)
}
// Traceln logs a message at level Trace on the standard logger.
func Traceln(args ...interface{}) {
std.Traceln(args...)
}
// Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) {
std.Debugln(args...)
}
// Println logs a message at level Info on the standard logger.
func Println(args ...interface{}) {
std.Println(args...)
}
// Infoln logs a message at level Info on the standard logger.
func Infoln(args ...interface{}) {
std.Infoln(args...)
}
// Warnln logs a message at level Warn on the standard logger.
func Warnln(args ...interface{}) {
std.Warnln(args...)
}
// Warningln logs a message at level Warn on the standard logger.
func Warningln(args ...interface{}) {
std.Warningln(args...)
}
// Errorln logs a message at level Error on the standard logger.
func Errorln(args ...interface{}) {
std.Errorln(args...)
}
// Panicln logs a message at level Panic on the standard logger.
func Panicln(args ...interface{}) {
std.Panicln(args...)
}
// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalln(args ...interface{}) {
std.Fatalln(args...)
}
-78
View File
@@ -1,78 +0,0 @@
package logrus
import "time"
// Default key names for the default fields
const (
defaultTimestampFormat = time.RFC3339
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
FieldKeyLogrusError = "logrus_error"
FieldKeyFunc = "func"
FieldKeyFile = "file"
)
// The Formatter interface is used to implement a custom Formatter. It takes an
// `Entry`. It exposes all the fields, including the default ones:
//
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
// * `entry.Data["time"]`. The timestamp.
// * `entry.Data["level"]. The level the entry was logged at.
//
// Any additional fields added with `WithField` or `WithFields` are also in
// `entry.Data`. Format is expected to return an array of bytes which are then
// logged to `logger.Out`.
type Formatter interface {
Format(*Entry) ([]byte, error)
}
// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when
// dumping it. If this code wasn't there doing:
//
// logrus.WithField("level", 1).Info("hello")
//
// Would just silently drop the user provided level. Instead with this code
// it'll logged as:
//
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
//
// It's not exported because it's still using Data in an opinionated way. It's to
// avoid code duplication between the two default formatters.
func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) {
timeKey := fieldMap.resolve(FieldKeyTime)
if t, ok := data[timeKey]; ok {
data["fields."+timeKey] = t
delete(data, timeKey)
}
msgKey := fieldMap.resolve(FieldKeyMsg)
if m, ok := data[msgKey]; ok {
data["fields."+msgKey] = m
delete(data, msgKey)
}
levelKey := fieldMap.resolve(FieldKeyLevel)
if l, ok := data[levelKey]; ok {
data["fields."+levelKey] = l
delete(data, levelKey)
}
logrusErrKey := fieldMap.resolve(FieldKeyLogrusError)
if l, ok := data[logrusErrKey]; ok {
data["fields."+logrusErrKey] = l
delete(data, logrusErrKey)
}
// If reportCaller is not set, 'func' will not conflict.
if reportCaller {
funcKey := fieldMap.resolve(FieldKeyFunc)
if l, ok := data[funcKey]; ok {
data["fields."+funcKey] = l
}
fileKey := fieldMap.resolve(FieldKeyFile)
if l, ok := data[fileKey]; ok {
data["fields."+fileKey] = l
}
}
}
-34
View File
@@ -1,34 +0,0 @@
package logrus
// A hook to be fired when logging on the logging levels returned from
// `Levels()` on your implementation of the interface. Note that this is not
// fired in a goroutine or a channel with workers, you should handle such
// functionality yourself if your call is non-blocking and you don't wish for
// the logging calls for levels returned from `Levels()` to block.
type Hook interface {
Levels() []Level
Fire(*Entry) error
}
// Internal type for storing the hooks on a logger instance.
type LevelHooks map[Level][]Hook
// Add a hook to an instance of logger. This is called with
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
func (hooks LevelHooks) Add(hook Hook) {
for _, level := range hook.Levels() {
hooks[level] = append(hooks[level], hook)
}
}
// Fire all the hooks for the passed level. Used by `entry.log` to fire
// appropriate hooks for a log entry.
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
for _, hook := range hooks[level] {
if err := hook.Fire(entry); err != nil {
return err
}
}
return nil
}
-128
View File
@@ -1,128 +0,0 @@
package logrus
import (
"bytes"
"encoding/json"
"fmt"
"runtime"
)
type fieldKey string
// FieldMap allows customization of the key names for default fields.
type FieldMap map[fieldKey]string
func (f FieldMap) resolve(key fieldKey) string {
if k, ok := f[key]; ok {
return k
}
return string(key)
}
// JSONFormatter formats logs into parsable json
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
// The format to use is the same than for time.Format or time.Parse from the standard
// library.
// The standard Library already provides a set of predefined format.
TimestampFormat string
// DisableTimestamp allows disabling automatic timestamps in output
DisableTimestamp bool
// DisableHTMLEscape allows disabling html escaping in output
DisableHTMLEscape bool
// DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
DataKey string
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message",
// FieldKeyFunc: "@caller",
// },
// }
FieldMap FieldMap
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the json data when ReportCaller is
// activated. If any of the returned value is the empty string the
// corresponding key will be removed from json fields.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
// PrettyPrint will indent all json logs
PrettyPrint bool
}
// Format renders a single log entry
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+4)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
if f.DataKey != "" {
newData := make(Fields, 4)
newData[f.DataKey] = data
data = newData
}
prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if entry.err != "" {
data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err
}
if !f.DisableTimestamp {
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
}
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
if entry.HasCaller() {
funcVal := entry.Caller.Function
fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
}
if funcVal != "" {
data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal
}
if fileVal != "" {
data[f.FieldMap.resolve(FieldKeyFile)] = fileVal
}
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
encoder := json.NewEncoder(b)
encoder.SetEscapeHTML(!f.DisableHTMLEscape)
if f.PrettyPrint {
encoder.SetIndent("", " ")
}
if err := encoder.Encode(data); err != nil {
return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err)
}
return b.Bytes(), nil
}
-417
View File
@@ -1,417 +0,0 @@
package logrus
import (
"context"
"io"
"os"
"sync"
"sync/atomic"
"time"
)
// LogFunction For big messages, it can be more efficient to pass a function
// and only call it if the log level is actually enables rather than
// generating the log message and then checking if the level is enabled
type LogFunction func() []interface{}
type Logger struct {
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
// file, or leave it default which is `os.Stderr`. You can also set this to
// something more adventurous, such as logging to Kafka.
Out io.Writer
// Hooks for the logger instance. These allow firing events based on logging
// levels and log entries. For example, to send errors to an error tracking
// service, log to StatsD or dump the core on fatal errors.
Hooks LevelHooks
// All log entries pass through the formatter before logged to Out. The
// included formatters are `TextFormatter` and `JSONFormatter` for which
// TextFormatter is the default. In development (when a TTY is attached) it
// logs with colors, but to a file it wouldn't. You can easily implement your
// own that implements the `Formatter` interface, see the `README` or included
// formatters for examples.
Formatter Formatter
// Flag for whether to log caller info (off by default)
ReportCaller bool
// The logging level the logger should log at. This is typically (and defaults
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
// logged.
Level Level
// Used to sync writing to the log. Locking is enabled by Default
mu MutexWrap
// Reusable empty entry
entryPool sync.Pool
// Function to exit the application, defaults to `os.Exit()`
ExitFunc exitFunc
// The buffer pool used to format the log. If it is nil, the default global
// buffer pool will be used.
BufferPool BufferPool
}
type exitFunc func(int)
type MutexWrap struct {
lock sync.Mutex
disabled bool
}
func (mw *MutexWrap) Lock() {
if !mw.disabled {
mw.lock.Lock()
}
}
func (mw *MutexWrap) Unlock() {
if !mw.disabled {
mw.lock.Unlock()
}
}
func (mw *MutexWrap) Disable() {
mw.disabled = true
}
// Creates a new logger. Configuration should be set by changing `Formatter`,
// `Out` and `Hooks` directly on the default logger instance. You can also just
// instantiate your own:
//
// var log = &logrus.Logger{
// Out: os.Stderr,
// Formatter: new(logrus.TextFormatter),
// Hooks: make(logrus.LevelHooks),
// Level: logrus.DebugLevel,
// }
//
// It's recommended to make this a global instance called `log`.
func New() *Logger {
return &Logger{
Out: os.Stderr,
Formatter: new(TextFormatter),
Hooks: make(LevelHooks),
Level: InfoLevel,
ExitFunc: os.Exit,
ReportCaller: false,
}
}
func (logger *Logger) newEntry() *Entry {
entry, ok := logger.entryPool.Get().(*Entry)
if ok {
return entry
}
return NewEntry(logger)
}
func (logger *Logger) releaseEntry(entry *Entry) {
entry.Data = map[string]interface{}{}
logger.entryPool.Put(entry)
}
// WithField allocates a new entry and adds a field to it.
// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
// this new returned entry.
// If you want multiple fields, use `WithFields`.
func (logger *Logger) WithField(key string, value interface{}) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithField(key, value)
}
// Adds a struct of fields to the log entry. All it does is call `WithField` for
// each `Field`.
func (logger *Logger) WithFields(fields Fields) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithFields(fields)
}
// Add an error as single field to the log entry. All it does is call
// `WithError` for the given `error`.
func (logger *Logger) WithError(err error) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithError(err)
}
// Add a context to the log entry.
func (logger *Logger) WithContext(ctx context.Context) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithContext(ctx)
}
// Overrides the time of the log entry.
func (logger *Logger) WithTime(t time.Time) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithTime(t)
}
func (logger *Logger) Logf(level Level, format string, args ...interface{}) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Logf(level, format, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Tracef(format string, args ...interface{}) {
logger.Logf(TraceLevel, format, args...)
}
func (logger *Logger) Debugf(format string, args ...interface{}) {
logger.Logf(DebugLevel, format, args...)
}
func (logger *Logger) Infof(format string, args ...interface{}) {
logger.Logf(InfoLevel, format, args...)
}
func (logger *Logger) Printf(format string, args ...interface{}) {
entry := logger.newEntry()
entry.Printf(format, args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warnf(format string, args ...interface{}) {
logger.Logf(WarnLevel, format, args...)
}
func (logger *Logger) Warningf(format string, args ...interface{}) {
logger.Warnf(format, args...)
}
func (logger *Logger) Errorf(format string, args ...interface{}) {
logger.Logf(ErrorLevel, format, args...)
}
func (logger *Logger) Fatalf(format string, args ...interface{}) {
logger.Logf(FatalLevel, format, args...)
logger.Exit(1)
}
func (logger *Logger) Panicf(format string, args ...interface{}) {
logger.Logf(PanicLevel, format, args...)
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Logger.Panic or Logger.Fatal should be used instead.
func (logger *Logger) Log(level Level, args ...interface{}) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Log(level, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) LogFn(level Level, fn LogFunction) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Log(level, fn()...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Trace(args ...interface{}) {
logger.Log(TraceLevel, args...)
}
func (logger *Logger) Debug(args ...interface{}) {
logger.Log(DebugLevel, args...)
}
func (logger *Logger) Info(args ...interface{}) {
logger.Log(InfoLevel, args...)
}
func (logger *Logger) Print(args ...interface{}) {
entry := logger.newEntry()
entry.Print(args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warn(args ...interface{}) {
logger.Log(WarnLevel, args...)
}
func (logger *Logger) Warning(args ...interface{}) {
logger.Warn(args...)
}
func (logger *Logger) Error(args ...interface{}) {
logger.Log(ErrorLevel, args...)
}
func (logger *Logger) Fatal(args ...interface{}) {
logger.Log(FatalLevel, args...)
logger.Exit(1)
}
func (logger *Logger) Panic(args ...interface{}) {
logger.Log(PanicLevel, args...)
}
func (logger *Logger) TraceFn(fn LogFunction) {
logger.LogFn(TraceLevel, fn)
}
func (logger *Logger) DebugFn(fn LogFunction) {
logger.LogFn(DebugLevel, fn)
}
func (logger *Logger) InfoFn(fn LogFunction) {
logger.LogFn(InfoLevel, fn)
}
func (logger *Logger) PrintFn(fn LogFunction) {
entry := logger.newEntry()
entry.Print(fn()...)
logger.releaseEntry(entry)
}
func (logger *Logger) WarnFn(fn LogFunction) {
logger.LogFn(WarnLevel, fn)
}
func (logger *Logger) WarningFn(fn LogFunction) {
logger.WarnFn(fn)
}
func (logger *Logger) ErrorFn(fn LogFunction) {
logger.LogFn(ErrorLevel, fn)
}
func (logger *Logger) FatalFn(fn LogFunction) {
logger.LogFn(FatalLevel, fn)
logger.Exit(1)
}
func (logger *Logger) PanicFn(fn LogFunction) {
logger.LogFn(PanicLevel, fn)
}
func (logger *Logger) Logln(level Level, args ...interface{}) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Logln(level, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Traceln(args ...interface{}) {
logger.Logln(TraceLevel, args...)
}
func (logger *Logger) Debugln(args ...interface{}) {
logger.Logln(DebugLevel, args...)
}
func (logger *Logger) Infoln(args ...interface{}) {
logger.Logln(InfoLevel, args...)
}
func (logger *Logger) Println(args ...interface{}) {
entry := logger.newEntry()
entry.Println(args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warnln(args ...interface{}) {
logger.Logln(WarnLevel, args...)
}
func (logger *Logger) Warningln(args ...interface{}) {
logger.Warnln(args...)
}
func (logger *Logger) Errorln(args ...interface{}) {
logger.Logln(ErrorLevel, args...)
}
func (logger *Logger) Fatalln(args ...interface{}) {
logger.Logln(FatalLevel, args...)
logger.Exit(1)
}
func (logger *Logger) Panicln(args ...interface{}) {
logger.Logln(PanicLevel, args...)
}
func (logger *Logger) Exit(code int) {
runHandlers()
if logger.ExitFunc == nil {
logger.ExitFunc = os.Exit
}
logger.ExitFunc(code)
}
//When file is opened with appending mode, it's safe to
//write concurrently to a file (within 4k message on Linux).
//In these cases user can choose to disable the lock.
func (logger *Logger) SetNoLock() {
logger.mu.Disable()
}
func (logger *Logger) level() Level {
return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
}
// SetLevel sets the logger level.
func (logger *Logger) SetLevel(level Level) {
atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
}
// GetLevel returns the logger level.
func (logger *Logger) GetLevel() Level {
return logger.level()
}
// AddHook adds a hook to the logger hooks.
func (logger *Logger) AddHook(hook Hook) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Hooks.Add(hook)
}
// IsLevelEnabled checks if the log level of the logger is greater than the level param
func (logger *Logger) IsLevelEnabled(level Level) bool {
return logger.level() >= level
}
// SetFormatter sets the logger formatter.
func (logger *Logger) SetFormatter(formatter Formatter) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Formatter = formatter
}
// SetOutput sets the logger output.
func (logger *Logger) SetOutput(output io.Writer) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Out = output
}
func (logger *Logger) SetReportCaller(reportCaller bool) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.ReportCaller = reportCaller
}
// ReplaceHooks replaces the logger hooks and returns the old ones
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
logger.mu.Lock()
oldHooks := logger.Hooks
logger.Hooks = hooks
logger.mu.Unlock()
return oldHooks
}
// SetBufferPool sets the logger buffer pool.
func (logger *Logger) SetBufferPool(pool BufferPool) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.BufferPool = pool
}
-186
View File
@@ -1,186 +0,0 @@
package logrus
import (
"fmt"
"log"
"strings"
)
// Fields type, used to pass to `WithFields`.
type Fields map[string]interface{}
// Level type
type Level uint32
// Convert the Level to a string. E.g. PanicLevel becomes "panic".
func (level Level) String() string {
if b, err := level.MarshalText(); err == nil {
return string(b)
} else {
return "unknown"
}
}
// ParseLevel takes a string level and returns the Logrus log level constant.
func ParseLevel(lvl string) (Level, error) {
switch strings.ToLower(lvl) {
case "panic":
return PanicLevel, nil
case "fatal":
return FatalLevel, nil
case "error":
return ErrorLevel, nil
case "warn", "warning":
return WarnLevel, nil
case "info":
return InfoLevel, nil
case "debug":
return DebugLevel, nil
case "trace":
return TraceLevel, nil
}
var l Level
return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (level *Level) UnmarshalText(text []byte) error {
l, err := ParseLevel(string(text))
if err != nil {
return err
}
*level = l
return nil
}
func (level Level) MarshalText() ([]byte, error) {
switch level {
case TraceLevel:
return []byte("trace"), nil
case DebugLevel:
return []byte("debug"), nil
case InfoLevel:
return []byte("info"), nil
case WarnLevel:
return []byte("warning"), nil
case ErrorLevel:
return []byte("error"), nil
case FatalLevel:
return []byte("fatal"), nil
case PanicLevel:
return []byte("panic"), nil
}
return nil, fmt.Errorf("not a valid logrus level %d", level)
}
// A constant exposing all logging levels
var AllLevels = []Level{
PanicLevel,
FatalLevel,
ErrorLevel,
WarnLevel,
InfoLevel,
DebugLevel,
TraceLevel,
}
// These are the different logging levels. You can set the logging level to log
// on your instance of logger, obtained with `logrus.New()`.
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel Level = iota
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
// TraceLevel level. Designates finer-grained informational events than the Debug.
TraceLevel
)
// Won't compile if StdLogger can't be realized by a log.Logger
var (
_ StdLogger = &log.Logger{}
_ StdLogger = &Entry{}
_ StdLogger = &Logger{}
)
// StdLogger is what your logrus-enabled library should take, that way
// it'll accept a stdlib logger and a logrus logger. There's no standard
// interface, this is the closest we get, unfortunately.
type StdLogger interface {
Print(...interface{})
Printf(string, ...interface{})
Println(...interface{})
Fatal(...interface{})
Fatalf(string, ...interface{})
Fatalln(...interface{})
Panic(...interface{})
Panicf(string, ...interface{})
Panicln(...interface{})
}
// The FieldLogger interface generalizes the Entry and Logger types
type FieldLogger interface {
WithField(key string, value interface{}) *Entry
WithFields(fields Fields) *Entry
WithError(err error) *Entry
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Printf(format string, args ...interface{})
Warnf(format string, args ...interface{})
Warningf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Panicf(format string, args ...interface{})
Debug(args ...interface{})
Info(args ...interface{})
Print(args ...interface{})
Warn(args ...interface{})
Warning(args ...interface{})
Error(args ...interface{})
Fatal(args ...interface{})
Panic(args ...interface{})
Debugln(args ...interface{})
Infoln(args ...interface{})
Println(args ...interface{})
Warnln(args ...interface{})
Warningln(args ...interface{})
Errorln(args ...interface{})
Fatalln(args ...interface{})
Panicln(args ...interface{})
// IsDebugEnabled() bool
// IsInfoEnabled() bool
// IsWarnEnabled() bool
// IsErrorEnabled() bool
// IsFatalEnabled() bool
// IsPanicEnabled() bool
}
// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is
// here for consistancy. Do not use. Use Logger or Entry instead.
type Ext1FieldLogger interface {
FieldLogger
Tracef(format string, args ...interface{})
Trace(args ...interface{})
Traceln(args ...interface{})
}
@@ -1,11 +0,0 @@
// +build appengine
package logrus
import (
"io"
)
func checkIfTerminal(w io.Writer) bool {
return true
}
-13
View File
@@ -1,13 +0,0 @@
// +build darwin dragonfly freebsd netbsd openbsd
// +build !js
package logrus
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TIOCGETA
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}
-7
View File
@@ -1,7 +0,0 @@
// +build js
package logrus
func isTerminal(fd int) bool {
return false
}
@@ -1,11 +0,0 @@
// +build js nacl plan9
package logrus
import (
"io"
)
func checkIfTerminal(w io.Writer) bool {
return false
}
@@ -1,17 +0,0 @@
// +build !appengine,!js,!windows,!nacl,!plan9
package logrus
import (
"io"
"os"
)
func checkIfTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
return isTerminal(int(v.Fd()))
default:
return false
}
}
@@ -1,11 +0,0 @@
package logrus
import (
"golang.org/x/sys/unix"
)
// IsTerminal returns true if the given file descriptor is a terminal.
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermio(fd, unix.TCGETA)
return err == nil
}
-13
View File
@@ -1,13 +0,0 @@
// +build linux aix zos
// +build !js
package logrus
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TCGETS
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}
@@ -1,27 +0,0 @@
// +build !appengine,!js,windows
package logrus
import (
"io"
"os"
"golang.org/x/sys/windows"
)
func checkIfTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
handle := windows.Handle(v.Fd())
var mode uint32
if err := windows.GetConsoleMode(handle, &mode); err != nil {
return false
}
mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
if err := windows.SetConsoleMode(handle, mode); err != nil {
return false
}
return true
}
return false
}
-339
View File
@@ -1,339 +0,0 @@
package logrus
import (
"bytes"
"fmt"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
const (
red = 31
yellow = 33
blue = 36
gray = 37
)
var baseTimestamp time.Time
func init() {
baseTimestamp = time.Now()
}
// TextFormatter formats logs into text
type TextFormatter struct {
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
// Force disabling colors.
DisableColors bool
// Force quoting of all values
ForceQuote bool
// DisableQuote disables quoting for all values.
// DisableQuote will have a lower priority than ForceQuote.
// If both of them are set to true, quote will be forced on all values.
DisableQuote bool
// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
EnvironmentOverrideColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
// Enable logging the full timestamp when a TTY is attached instead of just
// the time passed since beginning of execution.
FullTimestamp bool
// TimestampFormat to use for display when a full timestamp is printed.
// The format to use is the same than for time.Format or time.Parse from the standard
// library.
// The standard Library already provides a set of predefined format.
TimestampFormat string
// The fields are sorted by default for a consistent output. For applications
// that log extremely frequently and don't use the JSON formatter this may not
// be desired.
DisableSorting bool
// The keys sorting function, when uninitialized it uses sort.Strings.
SortingFunc func([]string)
// Disables the truncation of the level text to 4 characters.
DisableLevelTruncation bool
// PadLevelText Adds padding the level text so that all the levels output at the same length
// PadLevelText is a superset of the DisableLevelTruncation option
PadLevelText bool
// QuoteEmptyFields will wrap empty fields in quotes if true
QuoteEmptyFields bool
// Whether the logger's out is to a terminal
isTerminal bool
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &TextFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message"}}
FieldMap FieldMap
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the data when ReportCaller is
// activated. If any of the returned value is the empty string the
// corresponding key will be removed from fields.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
terminalInitOnce sync.Once
// The max length of the level text, generated dynamically on init
levelTextMaxLength int
}
func (f *TextFormatter) init(entry *Entry) {
if entry.Logger != nil {
f.isTerminal = checkIfTerminal(entry.Logger.Out)
}
// Get the max length of the level text
for _, level := range AllLevels {
levelTextLength := utf8.RuneCount([]byte(level.String()))
if levelTextLength > f.levelTextMaxLength {
f.levelTextMaxLength = levelTextLength
}
}
}
func (f *TextFormatter) isColored() bool {
isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows"))
if f.EnvironmentOverrideColors {
switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); {
case ok && force != "0":
isColored = true
case ok && force == "0", os.Getenv("CLICOLOR") == "0":
isColored = false
}
}
return isColored && !f.DisableColors
}
// Format renders a single log entry
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields)
for k, v := range entry.Data {
data[k] = v
}
prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
var funcVal, fileVal string
fixedKeys := make([]string, 0, 4+len(data))
if !f.DisableTimestamp {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
}
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
if entry.Message != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
}
if entry.err != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
}
if entry.HasCaller() {
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
} else {
funcVal = entry.Caller.Function
fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
}
if funcVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))
}
if fileVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))
}
}
if !f.DisableSorting {
if f.SortingFunc == nil {
sort.Strings(keys)
fixedKeys = append(fixedKeys, keys...)
} else {
if !f.isColored() {
fixedKeys = append(fixedKeys, keys...)
f.SortingFunc(fixedKeys)
} else {
f.SortingFunc(keys)
}
}
} else {
fixedKeys = append(fixedKeys, keys...)
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
f.terminalInitOnce.Do(func() { f.init(entry) })
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if f.isColored() {
f.printColored(b, entry, keys, data, timestampFormat)
} else {
for _, key := range fixedKeys {
var value interface{}
switch {
case key == f.FieldMap.resolve(FieldKeyTime):
value = entry.Time.Format(timestampFormat)
case key == f.FieldMap.resolve(FieldKeyLevel):
value = entry.Level.String()
case key == f.FieldMap.resolve(FieldKeyMsg):
value = entry.Message
case key == f.FieldMap.resolve(FieldKeyLogrusError):
value = entry.err
case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
value = funcVal
case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
value = fileVal
default:
value = data[key]
}
f.appendKeyValue(b, key, value)
}
}
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) {
var levelColor int
switch entry.Level {
case DebugLevel, TraceLevel:
levelColor = gray
case WarnLevel:
levelColor = yellow
case ErrorLevel, FatalLevel, PanicLevel:
levelColor = red
case InfoLevel:
levelColor = blue
default:
levelColor = blue
}
levelText := strings.ToUpper(entry.Level.String())
if !f.DisableLevelTruncation && !f.PadLevelText {
levelText = levelText[0:4]
}
if f.PadLevelText {
// Generates the format string used in the next line, for example "%-6s" or "%-7s".
// Based on the max level text length.
formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s"
// Formats the level text by appending spaces up to the max length, for example:
// - "INFO "
// - "WARNING"
levelText = fmt.Sprintf(formatString, levelText)
}
// Remove a single newline if it already exists in the message to keep
// the behavior of logrus text_formatter the same as the stdlib log package
entry.Message = strings.TrimSuffix(entry.Message, "\n")
caller := ""
if entry.HasCaller() {
funcVal := fmt.Sprintf("%s()", entry.Caller.Function)
fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
}
if fileVal == "" {
caller = funcVal
} else if funcVal == "" {
caller = fileVal
} else {
caller = fileVal + " " + funcVal
}
}
switch {
case f.DisableTimestamp:
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message)
case !f.FullTimestamp:
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
default:
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
}
for _, k := range keys {
v := data[k]
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
f.appendValue(b, v)
}
}
func (f *TextFormatter) needsQuoting(text string) bool {
if f.ForceQuote {
return true
}
if f.QuoteEmptyFields && len(text) == 0 {
return true
}
if f.DisableQuote {
return false
}
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
return true
}
}
return false
}
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
if b.Len() > 0 {
b.WriteByte(' ')
}
b.WriteString(key)
b.WriteByte('=')
f.appendValue(b, value)
}
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
stringVal, ok := value.(string)
if !ok {
stringVal = fmt.Sprint(value)
}
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}
-102
View File
@@ -1,102 +0,0 @@
package logrus
import (
"bufio"
"io"
"runtime"
"strings"
)
// Writer at INFO level. See WriterLevel for details.
func (logger *Logger) Writer() *io.PipeWriter {
return logger.WriterLevel(InfoLevel)
}
// WriterLevel returns an io.Writer that can be used to write arbitrary text to
// the logger at the given log level. Each line written to the writer will be
// printed in the usual way using formatters and hooks. The writer is part of an
// io.Pipe and it is the callers responsibility to close the writer when done.
// This can be used to override the standard library logger easily.
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
return NewEntry(logger).WriterLevel(level)
}
// Writer returns an io.Writer that writes to the logger at the info log level
func (entry *Entry) Writer() *io.PipeWriter {
return entry.WriterLevel(InfoLevel)
}
// WriterLevel returns an io.Writer that writes to the logger at the given log level
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
reader, writer := io.Pipe()
var printFunc func(args ...interface{})
// Determine which log function to use based on the specified log level
switch level {
case TraceLevel:
printFunc = entry.Trace
case DebugLevel:
printFunc = entry.Debug
case InfoLevel:
printFunc = entry.Info
case WarnLevel:
printFunc = entry.Warn
case ErrorLevel:
printFunc = entry.Error
case FatalLevel:
printFunc = entry.Fatal
case PanicLevel:
printFunc = entry.Panic
default:
printFunc = entry.Print
}
// Start a new goroutine to scan the input and write it to the logger using the specified print function.
// It splits the input into chunks of up to 64KB to avoid buffer overflows.
go entry.writerScanner(reader, printFunc)
// Set a finalizer function to close the writer when it is garbage collected
runtime.SetFinalizer(writer, writerFinalizer)
return writer
}
// writerScanner scans the input from the reader and writes it to the logger
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
scanner := bufio.NewScanner(reader)
// Set the buffer size to the maximum token size to avoid buffer overflows
scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize)
// Define a split function to split the input into chunks of up to 64KB
chunkSize := bufio.MaxScanTokenSize // 64KB
splitFunc := func(data []byte, atEOF bool) (int, []byte, error) {
if len(data) >= chunkSize {
return chunkSize, data[:chunkSize], nil
}
return bufio.ScanLines(data, atEOF)
}
// Use the custom split function to split the input
scanner.Split(splitFunc)
// Scan the input and write it to the logger using the specified print function
for scanner.Scan() {
printFunc(strings.TrimRight(scanner.Text(), "\r\n"))
}
// If there was an error while scanning the input, log an error
if err := scanner.Err(); err != nil {
entry.Errorf("Error while reading from Writer: %s", err)
}
// Close the reader when we are done
reader.Close()
}
// WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected
func writerFinalizer(writer *io.PipeWriter) {
writer.Close()
}
+27
View File
@@ -0,0 +1,27 @@
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+22
View File
@@ -0,0 +1,22 @@
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
+90
View File
@@ -0,0 +1,90 @@
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package curve25519 provides an implementation of the X25519 function, which
// performs scalar multiplication on the elliptic curve known as Curve25519.
// See RFC 7748.
//
// This package is a wrapper for the X25519 implementation
// in the crypto/ecdh package.
package curve25519
import "crypto/ecdh"
// ScalarMult sets dst to the product scalar * point.
//
// Deprecated: when provided a low-order point, ScalarMult will set dst to all
// zeroes, irrespective of the scalar. Instead, use the X25519 function, which
// will return an error.
func ScalarMult(dst, scalar, point *[32]byte) {
if _, err := x25519(dst, scalar[:], point[:]); err != nil {
// The only error condition for x25519 when the inputs are 32 bytes long
// is if the output would have been the all-zero value.
for i := range dst {
dst[i] = 0
}
}
}
// ScalarBaseMult sets dst to the product scalar * base where base is the
// standard generator.
//
// It is recommended to use the X25519 function with Basepoint instead, as
// copying into fixed size arrays can lead to unexpected bugs.
func ScalarBaseMult(dst, scalar *[32]byte) {
curve := ecdh.X25519()
priv, err := curve.NewPrivateKey(scalar[:])
if err != nil {
panic("curve25519: internal error: scalarBaseMult was not 32 bytes")
}
copy(dst[:], priv.PublicKey().Bytes())
}
const (
// ScalarSize is the size of the scalar input to X25519.
ScalarSize = 32
// PointSize is the size of the point input to X25519.
PointSize = 32
)
// Basepoint is the canonical Curve25519 generator.
var Basepoint []byte
var basePoint = [32]byte{9}
func init() { Basepoint = basePoint[:] }
// X25519 returns the result of the scalar multiplication (scalar * point),
// according to RFC 7748, Section 5. scalar, point and the return value are
// slices of 32 bytes.
//
// scalar can be generated at random, for example with crypto/rand. point should
// be either Basepoint or the output of another X25519 call.
//
// If point is Basepoint (but not if it's a different slice with the same
// contents) a precomputed implementation might be used for performance.
func X25519(scalar, point []byte) ([]byte, error) {
// Outline the body of function, to let the allocation be inlined in the
// caller, and possibly avoid escaping to the heap.
var dst [32]byte
return x25519(&dst, scalar, point)
}
func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) {
curve := ecdh.X25519()
pub, err := curve.NewPublicKey(point)
if err != nil {
return nil, err
}
priv, err := curve.NewPrivateKey(scalar)
if err != nil {
return nil, err
}
out, err := priv.ECDH(pub)
if err != nil {
return nil, err
}
copy(dst[:], out)
return dst[:], nil
}
+2 -2
View File
@@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
+3
View File
@@ -4,6 +4,9 @@
// Package errgroup provides synchronization, error propagation, and Context
// cancelation for groups of goroutines working on subtasks of a common task.
//
// [errgroup.Group] is related to [sync.WaitGroup] but adds handling of tasks
// returning errors.
package errgroup
import (
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.20
// +build go1.20
package errgroup
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !go1.20
// +build !go1.20
package errgroup
@@ -1,21 +1,17 @@
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
Copyright (c) 2014 Simon Eskildsen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+287
View File
@@ -0,0 +1,287 @@
// Copyright 2021 The Go Authors. All rights reserved.
// Copyright 2015 Microsoft
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package namedpipe
import (
"io"
"os"
"runtime"
"sync"
"sync/atomic"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
type timeoutChan chan struct{}
var (
ioInitOnce sync.Once
ioCompletionPort windows.Handle
)
// ioResult contains the result of an asynchronous IO operation
type ioResult struct {
bytes uint32
err error
}
// ioOperation represents an outstanding asynchronous Win32 IO
type ioOperation struct {
o windows.Overlapped
ch chan ioResult
}
func initIo() {
h, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0)
if err != nil {
panic(err)
}
ioCompletionPort = h
go ioCompletionProcessor(h)
}
// file implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall.
// It takes ownership of this handle and will close it if it is garbage collected.
type file struct {
handle windows.Handle
wg sync.WaitGroup
wgLock sync.RWMutex
closing atomic.Bool
socket bool
readDeadline deadlineHandler
writeDeadline deadlineHandler
}
type deadlineHandler struct {
setLock sync.Mutex
channel timeoutChan
channelLock sync.RWMutex
timer *time.Timer
timedout atomic.Bool
}
// makeFile makes a new file from an existing file handle
func makeFile(h windows.Handle) (*file, error) {
f := &file{handle: h}
ioInitOnce.Do(initIo)
_, err := windows.CreateIoCompletionPort(h, ioCompletionPort, 0, 0)
if err != nil {
return nil, err
}
err = windows.SetFileCompletionNotificationModes(h, windows.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS|windows.FILE_SKIP_SET_EVENT_ON_HANDLE)
if err != nil {
return nil, err
}
f.readDeadline.channel = make(timeoutChan)
f.writeDeadline.channel = make(timeoutChan)
return f, nil
}
// closeHandle closes the resources associated with a Win32 handle
func (f *file) closeHandle() {
f.wgLock.Lock()
// Atomically set that we are closing, releasing the resources only once.
if f.closing.Swap(true) == false {
f.wgLock.Unlock()
// cancel all IO and wait for it to complete
windows.CancelIoEx(f.handle, nil)
f.wg.Wait()
// at this point, no new IO can start
windows.Close(f.handle)
f.handle = 0
} else {
f.wgLock.Unlock()
}
}
// Close closes a file.
func (f *file) Close() error {
f.closeHandle()
return nil
}
// prepareIo prepares for a new IO operation.
// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning.
func (f *file) prepareIo() (*ioOperation, error) {
f.wgLock.RLock()
if f.closing.Load() {
f.wgLock.RUnlock()
return nil, os.ErrClosed
}
f.wg.Add(1)
f.wgLock.RUnlock()
c := &ioOperation{}
c.ch = make(chan ioResult)
return c, nil
}
// ioCompletionProcessor processes completed async IOs forever
func ioCompletionProcessor(h windows.Handle) {
for {
var bytes uint32
var key uintptr
var op *ioOperation
err := windows.GetQueuedCompletionStatus(h, &bytes, &key, (**windows.Overlapped)(unsafe.Pointer(&op)), windows.INFINITE)
if op == nil {
panic(err)
}
op.ch <- ioResult{bytes, err}
}
}
// asyncIo processes the return value from ReadFile or WriteFile, blocking until
// the operation has actually completed.
func (f *file) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) {
if err != windows.ERROR_IO_PENDING {
return int(bytes), err
}
if f.closing.Load() {
windows.CancelIoEx(f.handle, &c.o)
}
var timeout timeoutChan
if d != nil {
d.channelLock.Lock()
timeout = d.channel
d.channelLock.Unlock()
}
var r ioResult
select {
case r = <-c.ch:
err = r.err
if err == windows.ERROR_OPERATION_ABORTED {
if f.closing.Load() {
err = os.ErrClosed
}
} else if err != nil && f.socket {
// err is from Win32. Query the overlapped structure to get the winsock error.
var bytes, flags uint32
err = windows.WSAGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags)
}
case <-timeout:
windows.CancelIoEx(f.handle, &c.o)
r = <-c.ch
err = r.err
if err == windows.ERROR_OPERATION_ABORTED {
err = os.ErrDeadlineExceeded
}
}
// runtime.KeepAlive is needed, as c is passed via native
// code to ioCompletionProcessor, c must remain alive
// until the channel read is complete.
runtime.KeepAlive(c)
return int(r.bytes), err
}
// Read reads from a file handle.
func (f *file) Read(b []byte) (int, error) {
c, err := f.prepareIo()
if err != nil {
return 0, err
}
defer f.wg.Done()
if f.readDeadline.timedout.Load() {
return 0, os.ErrDeadlineExceeded
}
var bytes uint32
err = windows.ReadFile(f.handle, b, &bytes, &c.o)
n, err := f.asyncIo(c, &f.readDeadline, bytes, err)
runtime.KeepAlive(b)
// Handle EOF conditions.
if err == nil && n == 0 && len(b) != 0 {
return 0, io.EOF
} else if err == windows.ERROR_BROKEN_PIPE {
return 0, io.EOF
} else {
return n, err
}
}
// Write writes to a file handle.
func (f *file) Write(b []byte) (int, error) {
c, err := f.prepareIo()
if err != nil {
return 0, err
}
defer f.wg.Done()
if f.writeDeadline.timedout.Load() {
return 0, os.ErrDeadlineExceeded
}
var bytes uint32
err = windows.WriteFile(f.handle, b, &bytes, &c.o)
n, err := f.asyncIo(c, &f.writeDeadline, bytes, err)
runtime.KeepAlive(b)
return n, err
}
func (f *file) SetReadDeadline(deadline time.Time) error {
return f.readDeadline.set(deadline)
}
func (f *file) SetWriteDeadline(deadline time.Time) error {
return f.writeDeadline.set(deadline)
}
func (f *file) Flush() error {
return windows.FlushFileBuffers(f.handle)
}
func (f *file) Fd() uintptr {
return uintptr(f.handle)
}
func (d *deadlineHandler) set(deadline time.Time) error {
d.setLock.Lock()
defer d.setLock.Unlock()
if d.timer != nil {
if !d.timer.Stop() {
<-d.channel
}
d.timer = nil
}
d.timedout.Store(false)
select {
case <-d.channel:
d.channelLock.Lock()
d.channel = make(chan struct{})
d.channelLock.Unlock()
default:
}
if deadline.IsZero() {
return nil
}
timeoutIO := func() {
d.timedout.Store(true)
close(d.channel)
}
now := time.Now()
duration := deadline.Sub(now)
if deadline.After(now) {
// Deadline is in the future, set a timer to wait
d.timer = time.AfterFunc(duration, timeoutIO)
} else {
// Deadline is in the past. Cancel all pending IO now.
timeoutIO()
}
return nil
}
@@ -0,0 +1,485 @@
// Copyright 2021 The Go Authors. All rights reserved.
// Copyright 2015 Microsoft
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
// Package namedpipe implements a net.Conn and net.Listener around Windows named pipes.
package namedpipe
import (
"context"
"io"
"net"
"os"
"runtime"
"sync/atomic"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
type pipe struct {
*file
path string
}
type messageBytePipe struct {
pipe
writeClosed atomic.Bool
readEOF bool
}
type pipeAddress string
func (f *pipe) LocalAddr() net.Addr {
return pipeAddress(f.path)
}
func (f *pipe) RemoteAddr() net.Addr {
return pipeAddress(f.path)
}
func (f *pipe) SetDeadline(t time.Time) error {
f.SetReadDeadline(t)
f.SetWriteDeadline(t)
return nil
}
// CloseWrite closes the write side of a message pipe in byte mode.
func (f *messageBytePipe) CloseWrite() error {
if !f.writeClosed.CompareAndSwap(false, true) {
return io.ErrClosedPipe
}
err := f.file.Flush()
if err != nil {
f.writeClosed.Store(false)
return err
}
_, err = f.file.Write(nil)
if err != nil {
f.writeClosed.Store(false)
return err
}
return nil
}
// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since
// they are used to implement CloseWrite.
func (f *messageBytePipe) Write(b []byte) (int, error) {
if f.writeClosed.Load() {
return 0, io.ErrClosedPipe
}
if len(b) == 0 {
return 0, nil
}
return f.file.Write(b)
}
// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message
// mode pipe will return io.EOF, as will all subsequent reads.
func (f *messageBytePipe) Read(b []byte) (int, error) {
if f.readEOF {
return 0, io.EOF
}
n, err := f.file.Read(b)
if err == io.EOF {
// If this was the result of a zero-byte read, then
// it is possible that the read was due to a zero-size
// message. Since we are simulating CloseWrite with a
// zero-byte message, ensure that all future Read calls
// also return EOF.
f.readEOF = true
} else if err == windows.ERROR_MORE_DATA {
// ERROR_MORE_DATA indicates that the pipe's read mode is message mode
// and the message still has more bytes. Treat this as a success, since
// this package presents all named pipes as byte streams.
err = nil
}
return n, err
}
func (f *pipe) Handle() windows.Handle {
return f.handle
}
func (s pipeAddress) Network() string {
return "pipe"
}
func (s pipeAddress) String() string {
return string(s)
}
// tryDialPipe attempts to dial the specified pipe until cancellation or timeout.
func tryDialPipe(ctx context.Context, path *string) (windows.Handle, error) {
for {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
path16, err := windows.UTF16PtrFromString(*path)
if err != nil {
return 0, err
}
h, err := windows.CreateFile(path16, windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OVERLAPPED|windows.SECURITY_SQOS_PRESENT|windows.SECURITY_ANONYMOUS, 0)
if err == nil {
return h, nil
}
if err != windows.ERROR_PIPE_BUSY {
return h, &os.PathError{Err: err, Op: "open", Path: *path}
}
// Wait 10 msec and try again. This is a rather simplistic
// view, as we always try each 10 milliseconds.
time.Sleep(10 * time.Millisecond)
}
}
}
// DialConfig exposes various options for use in Dial and DialContext.
type DialConfig struct {
ExpectedOwner *windows.SID // If non-nil, the pipe is verified to be owned by this SID.
}
// DialTimeout connects to the specified named pipe by path, timing out if the
// connection takes longer than the specified duration. If timeout is zero, then
// we use a default timeout of 2 seconds.
func (config *DialConfig) DialTimeout(path string, timeout time.Duration) (net.Conn, error) {
if timeout == 0 {
timeout = time.Second * 2
}
absTimeout := time.Now().Add(timeout)
ctx, _ := context.WithDeadline(context.Background(), absTimeout)
conn, err := config.DialContext(ctx, path)
if err == context.DeadlineExceeded {
return nil, os.ErrDeadlineExceeded
}
return conn, err
}
// DialContext attempts to connect to the specified named pipe by path.
func (config *DialConfig) DialContext(ctx context.Context, path string) (net.Conn, error) {
var err error
var h windows.Handle
h, err = tryDialPipe(ctx, &path)
if err != nil {
return nil, err
}
if config.ExpectedOwner != nil {
sd, err := windows.GetSecurityInfo(h, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION)
if err != nil {
windows.Close(h)
return nil, err
}
realOwner, _, err := sd.Owner()
if err != nil {
windows.Close(h)
return nil, err
}
if !realOwner.Equals(config.ExpectedOwner) {
windows.Close(h)
return nil, windows.ERROR_ACCESS_DENIED
}
}
var flags uint32
err = windows.GetNamedPipeInfo(h, &flags, nil, nil, nil)
if err != nil {
windows.Close(h)
return nil, err
}
f, err := makeFile(h)
if err != nil {
windows.Close(h)
return nil, err
}
// If the pipe is in message mode, return a message byte pipe, which
// supports CloseWrite.
if flags&windows.PIPE_TYPE_MESSAGE != 0 {
return &messageBytePipe{
pipe: pipe{file: f, path: path},
}, nil
}
return &pipe{file: f, path: path}, nil
}
var defaultDialer DialConfig
// DialTimeout calls DialConfig.DialTimeout using an empty configuration.
func DialTimeout(path string, timeout time.Duration) (net.Conn, error) {
return defaultDialer.DialTimeout(path, timeout)
}
// DialContext calls DialConfig.DialContext using an empty configuration.
func DialContext(ctx context.Context, path string) (net.Conn, error) {
return defaultDialer.DialContext(ctx, path)
}
type acceptResponse struct {
f *file
err error
}
type pipeListener struct {
firstHandle windows.Handle
path string
config ListenConfig
acceptCh chan chan acceptResponse
closeCh chan int
doneCh chan int
}
func makeServerPipeHandle(path string, sd *windows.SECURITY_DESCRIPTOR, c *ListenConfig, isFirstPipe bool) (windows.Handle, error) {
path16, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, &os.PathError{Op: "open", Path: path, Err: err}
}
var oa windows.OBJECT_ATTRIBUTES
oa.Length = uint32(unsafe.Sizeof(oa))
var ntPath windows.NTUnicodeString
if err := windows.RtlDosPathNameToNtPathName(path16, &ntPath, nil, nil); err != nil {
if ntstatus, ok := err.(windows.NTStatus); ok {
err = ntstatus.Errno()
}
return 0, &os.PathError{Op: "open", Path: path, Err: err}
}
defer windows.LocalFree(windows.Handle(unsafe.Pointer(ntPath.Buffer)))
oa.ObjectName = &ntPath
// The security descriptor is only needed for the first pipe.
if isFirstPipe {
if sd != nil {
oa.SecurityDescriptor = sd
} else {
// Construct the default named pipe security descriptor.
var acl *windows.ACL
if err := windows.RtlDefaultNpAcl(&acl); err != nil {
return 0, err
}
defer windows.LocalFree(windows.Handle(unsafe.Pointer(acl)))
sd, err = windows.NewSecurityDescriptor()
if err != nil {
return 0, err
}
if err = sd.SetDACL(acl, true, false); err != nil {
return 0, err
}
oa.SecurityDescriptor = sd
}
}
typ := uint32(windows.FILE_PIPE_REJECT_REMOTE_CLIENTS)
if c.MessageMode {
typ |= windows.FILE_PIPE_MESSAGE_TYPE
}
disposition := uint32(windows.FILE_OPEN)
access := uint32(windows.GENERIC_READ | windows.GENERIC_WRITE | windows.SYNCHRONIZE)
if isFirstPipe {
disposition = windows.FILE_CREATE
// By not asking for read or write access, the named pipe file system
// will put this pipe into an initially disconnected state, blocking
// client connections until the next call with isFirstPipe == false.
access = windows.SYNCHRONIZE
}
timeout := int64(-50 * 10000) // 50ms
var (
h windows.Handle
iosb windows.IO_STATUS_BLOCK
)
err = windows.NtCreateNamedPipeFile(&h, access, &oa, &iosb, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, disposition, 0, typ, 0, 0, 0xffffffff, uint32(c.InputBufferSize), uint32(c.OutputBufferSize), &timeout)
if err != nil {
if ntstatus, ok := err.(windows.NTStatus); ok {
err = ntstatus.Errno()
}
return 0, &os.PathError{Op: "open", Path: path, Err: err}
}
runtime.KeepAlive(ntPath)
return h, nil
}
func (l *pipeListener) makeServerPipe() (*file, error) {
h, err := makeServerPipeHandle(l.path, nil, &l.config, false)
if err != nil {
return nil, err
}
f, err := makeFile(h)
if err != nil {
windows.Close(h)
return nil, err
}
return f, nil
}
func (l *pipeListener) makeConnectedServerPipe() (*file, error) {
p, err := l.makeServerPipe()
if err != nil {
return nil, err
}
// Wait for the client to connect.
ch := make(chan error)
go func(p *file) {
ch <- connectPipe(p)
}(p)
select {
case err = <-ch:
if err != nil {
p.Close()
p = nil
}
case <-l.closeCh:
// Abort the connect request by closing the handle.
p.Close()
p = nil
err = <-ch
if err == nil || err == os.ErrClosed {
err = net.ErrClosed
}
}
return p, err
}
func (l *pipeListener) listenerRoutine() {
closed := false
for !closed {
select {
case <-l.closeCh:
closed = true
case responseCh := <-l.acceptCh:
var (
p *file
err error
)
for {
p, err = l.makeConnectedServerPipe()
// If the connection was immediately closed by the client, try
// again.
if err != windows.ERROR_NO_DATA {
break
}
}
responseCh <- acceptResponse{p, err}
closed = err == net.ErrClosed
}
}
windows.Close(l.firstHandle)
l.firstHandle = 0
// Notify Close and Accept callers that the handle has been closed.
close(l.doneCh)
}
// ListenConfig contains configuration for the pipe listener.
type ListenConfig struct {
// SecurityDescriptor contains a Windows security descriptor. If nil, the default from RtlDefaultNpAcl is used.
SecurityDescriptor *windows.SECURITY_DESCRIPTOR
// MessageMode determines whether the pipe is in byte or message mode. In either
// case the pipe is read in byte mode by default. The only practical difference in
// this implementation is that CloseWrite is only supported for message mode pipes;
// CloseWrite is implemented as a zero-byte write, but zero-byte writes are only
// transferred to the reader (and returned as io.EOF in this implementation)
// when the pipe is in message mode.
MessageMode bool
// InputBufferSize specifies the initial size of the input buffer, in bytes, which the OS will grow as needed.
InputBufferSize int32
// OutputBufferSize specifies the initial size of the output buffer, in bytes, which the OS will grow as needed.
OutputBufferSize int32
}
// Listen creates a listener on a Windows named pipe path,such as \\.\pipe\mypipe.
// The pipe must not already exist.
func (c *ListenConfig) Listen(path string) (net.Listener, error) {
h, err := makeServerPipeHandle(path, c.SecurityDescriptor, c, true)
if err != nil {
return nil, err
}
l := &pipeListener{
firstHandle: h,
path: path,
config: *c,
acceptCh: make(chan chan acceptResponse),
closeCh: make(chan int),
doneCh: make(chan int),
}
// The first connection is swallowed on Windows 7 & 8, so synthesize it.
if maj, min, _ := windows.RtlGetNtVersionNumbers(); maj < 6 || (maj == 6 && min < 4) {
path16, err := windows.UTF16PtrFromString(path)
if err == nil {
h, err = windows.CreateFile(path16, 0, 0, nil, windows.OPEN_EXISTING, windows.SECURITY_SQOS_PRESENT|windows.SECURITY_ANONYMOUS, 0)
if err == nil {
windows.CloseHandle(h)
}
}
}
go l.listenerRoutine()
return l, nil
}
var defaultListener ListenConfig
// Listen calls ListenConfig.Listen using an empty configuration.
func Listen(path string) (net.Listener, error) {
return defaultListener.Listen(path)
}
func connectPipe(p *file) error {
c, err := p.prepareIo()
if err != nil {
return err
}
defer p.wg.Done()
err = windows.ConnectNamedPipe(p.handle, &c.o)
_, err = p.asyncIo(c, nil, 0, err)
if err != nil && err != windows.ERROR_PIPE_CONNECTED {
return err
}
return nil
}
func (l *pipeListener) Accept() (net.Conn, error) {
ch := make(chan acceptResponse)
select {
case l.acceptCh <- ch:
response := <-ch
err := response.err
if err != nil {
return nil, err
}
if l.config.MessageMode {
return &messageBytePipe{
pipe: pipe{file: response.f, path: l.path},
}, nil
}
return &pipe{file: response.f, path: l.path}, nil
case <-l.doneCh:
return nil, net.ErrClosed
}
}
func (l *pipeListener) Close() error {
select {
case l.closeCh <- 1:
<-l.doneCh
case <-l.doneCh:
}
return nil
}
func (l *pipeListener) Addr() net.Addr {
return pipeAddress(l.path)
}
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
set -e
set -x
# !! This script is meant for use in CI build use only !!
KERNEL=$(uname -s)
# Use doas in place of sudo for OpenBSD.
SUDO="sudo"
if [ "${KERNEL}" == "OpenBSD" ]; then
SUDO="doas"
# Configure a WireGuard interface.
doas ifconfig wg0 create
doas ifconfig wg0 up
fi
if [ "${KERNEL}" == "FreeBSD" ]; then
# Configure a WireGuard interface.
sudo ifconfig wg create name wg0
sudo ifconfig wg0 up
fi
if [ "${KERNEL}" == "Linux" ]; then
# Configure a WireGuard interface.
sudo ip link add wg0 type wireguard
sudo ip link set up wg0
fi
# Set up wireguard-go on all OSes.
git clone https://git.zx2c4.com/wireguard-go
cd wireguard-go
if [ "${KERNEL}" == "Linux" ]; then
# Bypass Linux compilation restriction.
make
else
# Build directly to avoid Makefile.
go build -o wireguard-go
fi
${SUDO} mv ./wireguard-go /usr/local/bin/wireguard-go
cd ..
${SUDO} rm -rf ./wireguard-go
@@ -0,0 +1,2 @@
cmd/wgctrl/wgctrl
*.test
+22
View File
@@ -0,0 +1,22 @@
# Contributing
The `wgctrl` project makes use of the [GitHub Flow](https://guides.github.com/introduction/flow/)
for contributions.
If you'd like to contribute to the project, please
[open an issue](https://github.com/WireGuard/wgctrl-go/issues/new) or find an
[existing issue](https://github.com/WireGuard/wgctrl-go/issues) that you'd like
to take on. This ensures that efforts are not duplicated, and that a new feature
aligns with the focus of the rest of the repository.
Once your suggestion has been submitted and discussed, please be sure that your
code meets the following criteria:
- code is completely `gofmt`'d
- new features or codepaths have appropriate test coverage
- `go test ./...` passes
- `go vet ./...` passes
- `staticcheck ./...` passes
- `golint ./...` returns no warnings, including documentation comment warnings
Finally, submit a pull request for review!
+9
View File
@@ -0,0 +1,9 @@
# MIT License
Copyright (C) 2018-2022 Matt Layher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+30
View File
@@ -0,0 +1,30 @@
# wgctrl [![Test Status](https://github.com/WireGuard/wgctrl-go/workflows/Linux%20Test/badge.svg)](https://github.com/WireGuard/wgctrl-go/actions) [![Go Reference](https://pkg.go.dev/badge/golang.zx2c4.com/wireguard/wgctrl.svg)](https://pkg.go.dev/golang.zx2c4.com/wireguard/wgctrl) [![Go Report Card](https://goreportcard.com/badge/golang.zx2c4.com/wireguard/wgctrl)](https://goreportcard.com/report/golang.zx2c4.com/wireguard/wgctrl)
Package `wgctrl` enables control of WireGuard devices on multiple platforms.
For more information on WireGuard, please see <https://www.wireguard.com/>.
MIT Licensed.
## Overview
`wgctrl` can control multiple types of WireGuard devices, including:
- Kernel module devices
- Linux: via generic netlink
- FreeBSD: via ioctl interface
- OpenBSD: via ioctl interface (read-only)
- Windows: via ioctl interface
- Userspace devices via the userspace configuration protocol
As new operating systems add support for in-kernel WireGuard implementations,
this package should also be extended to support those native implementations.
If you are aware of any efforts on this front, please
[file an issue](https://github.com/WireGuard/wgctrl-go/issues/new).
This package implements WireGuard configuration protocol operations, enabling
the configuration of existing WireGuard devices. Operations such as creating
WireGuard devices, or applying IP addresses to those devices, are out of scope
for this package.
+101
View File
@@ -0,0 +1,101 @@
package wgctrl
import (
"errors"
"os"
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// Expose an identical interface to the underlying packages.
var _ wginternal.Client = &Client{}
// A Client provides access to WireGuard device information.
type Client struct {
// Seamlessly use different wginternal.Client implementations to provide an
// interface similar to wg(8).
cs []wginternal.Client
}
// New creates a new Client.
func New() (*Client, error) {
cs, err := newClients()
if err != nil {
return nil, err
}
return &Client{
cs: cs,
}, nil
}
// Close releases resources used by a Client.
func (c *Client) Close() error {
for _, wgc := range c.cs {
if err := wgc.Close(); err != nil {
return err
}
}
return nil
}
// Devices retrieves all WireGuard devices on this system.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
var out []*wgtypes.Device
for _, wgc := range c.cs {
devs, err := wgc.Devices()
if err != nil {
return nil, err
}
out = append(out, devs...)
}
return out, nil
}
// Device retrieves a WireGuard device by its interface name.
//
// If the device specified by name does not exist or is not a WireGuard device,
// an error is returned which can be checked using `errors.Is(err, os.ErrNotExist)`.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
for _, wgc := range c.cs {
d, err := wgc.Device(name)
switch {
case err == nil:
return d, nil
case errors.Is(err, os.ErrNotExist):
continue
default:
return nil, err
}
}
return nil, os.ErrNotExist
}
// ConfigureDevice configures a WireGuard device by its interface name.
//
// Because the zero value of some Go types may be significant to WireGuard for
// Config fields, only fields which are not nil will be applied when
// configuring a device.
//
// If the device specified by name does not exist or is not a WireGuard device,
// an error is returned which can be checked using `errors.Is(err, os.ErrNotExist)`.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
for _, wgc := range c.cs {
err := wgc.ConfigureDevice(name, cfg)
switch {
case err == nil:
return nil
case errors.Is(err, os.ErrNotExist):
continue
default:
return err
}
}
return os.ErrNotExist
}
+9
View File
@@ -0,0 +1,9 @@
// Package wgctrl enables control of WireGuard devices on multiple platforms.
//
// For more information on WireGuard, please see https://www.wireguard.com/.
//
// This package implements WireGuard configuration protocol operations, enabling
// the configuration of existing WireGuard devices. Operations such as creating
// WireGuard devices, or applying IP addresses to those devices, are out of scope
// for this package.
package wgctrl // import "golang.zx2c4.com/wireguard/wgctrl"
@@ -0,0 +1,532 @@
//go:build freebsd
// +build freebsd
package wgfreebsd
// #include <stdlib.h>
// #include <netinet/in.h>
import "C"
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"os"
"runtime"
"time"
"unsafe"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgfreebsd/internal/nv"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgfreebsd/internal/wgh"
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// ifGroupWG is the WireGuard interface group name passed to the kernel.
var ifGroupWG = [16]byte{0: 'w', 1: 'g'}
var _ wginternal.Client = &Client{}
// A Client provides access to FreeBSD WireGuard ioctl information.
type Client struct {
// Hooks which use system calls by default, but can also be swapped out
// during tests.
close func() error
ioctlIfgroupreq func(*wgh.Ifgroupreq) error
ioctlWGDataIO func(uint, *wgh.WGDataIO) error
}
// New creates a new Client and returns whether or not the ioctl interface
// is available.
func New() (*Client, bool, error) {
// The FreeBSD ioctl interface operates on a generic AF_INET socket.
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, 0)
if err != nil {
return nil, false, err
}
// TODO(mdlayher): find a call to invoke here to probe for availability.
// c.Devices won't work because it returns a "not found" error when the
// kernel WireGuard implementation is available but the interface group
// has no members.
// By default, use system call implementations for all hook functions.
return &Client{
close: func() error { return unix.Close(fd) },
ioctlIfgroupreq: ioctlIfgroupreq(fd),
ioctlWGDataIO: ioctlWGDataIO(fd),
}, true, nil
}
// Close implements wginternal.Client.
func (c *Client) Close() error {
return c.close()
}
// Devices implements wginternal.Client.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
ifg := wgh.Ifgroupreq{
// Query for devices in the "wg" group.
Name: ifGroupWG,
}
// Determine how many device names we must allocate memory for.
if err := c.ioctlIfgroupreq(&ifg); err != nil {
return nil, err
}
// ifg.Len is size in bytes; allocate enough memory for the correct number
// of wgh.Ifgreq and then store a pointer to the memory where the data
// should be written (ifgrs) in ifg.Groups.
//
// From a thread in golang-nuts, this pattern is valid:
// "It would be OK to pass a pointer to a struct to ioctl if the struct
// contains a pointer to other Go memory, but the struct field must have
// pointer type."
// See: https://groups.google.com/forum/#!topic/golang-nuts/FfasFTZvU_o.
ifgrs := make([]wgh.Ifgreq, ifg.Len/wgh.SizeofIfgreq)
ifg.Groups = &ifgrs[0]
// Now actually fetch the device names.
if err := c.ioctlIfgroupreq(&ifg); err != nil {
return nil, err
}
// Keep this alive until we're done doing the ioctl dance.
runtime.KeepAlive(&ifg)
devices := make([]*wgtypes.Device, 0, len(ifgrs))
for _, ifgr := range ifgrs {
// Remove any trailing NULL bytes from the interface names.
name := string(bytes.TrimRight(ifgr.Ifgrqu[:], "\x00"))
device, err := c.Device(name)
if err != nil {
return nil, err
}
devices = append(devices, device)
}
return devices, nil
}
// Device implements wginternal.Client.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
dname, err := deviceName(name)
if err != nil {
return nil, err
}
// First, specify the name of the device and determine how much memory
// must be allocated.
data := wgh.WGDataIO{
Name: dname,
}
var mem []byte
for {
if err := c.ioctlWGDataIO(wgh.SIOCGWG, &data); err != nil {
// ioctl functions always return a wrapped unix.Errno value.
// Conform to the wgctrl contract by unwrapping some values:
// ENXIO: "no such device": (no such WireGuard device)
// EINVAL: "inappropriate ioctl for device" (device is not a
// WireGuard device)
switch err.(*os.SyscallError).Err {
case unix.ENXIO, unix.EINVAL:
return nil, os.ErrNotExist
default:
return nil, err
}
}
if len(mem) >= int(data.Size) {
// Allocated enough memory!
break
}
// Allocate the appropriate amount of memory and point the kernel at
// the first byte of our slice's backing array. When the loop continues,
// we will check if we've allocated enough memory.
mem = make([]byte, data.Size)
data.Data = &mem[0]
}
dev, err := parseDevice(mem)
if err != nil {
return nil, err
}
dev.Name = name
return dev, nil
}
// ConfigureDevice implements wginternal.Client.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
// Check if there is a peer with the UpdateOnly flag set.
// This is not supported on FreeBSD yet. So error out..
// TODO(stv0g): remove this check once kernel support has landed.
for _, peer := range cfg.Peers {
if peer.UpdateOnly {
// Check that this device is really an existing kernel
// device
if _, err := c.Device(name); err != os.ErrNotExist {
return wgtypes.ErrUpdateOnlyNotSupported
}
}
}
m := unparseConfig(cfg)
mem, sz, err := nv.Marshal(m)
if err != nil {
return err
}
defer C.free(unsafe.Pointer(mem))
dname, err := deviceName(name)
if err != nil {
return err
}
data := wgh.WGDataIO{
Name: dname,
Data: mem,
Size: uint64(sz),
}
if err := c.ioctlWGDataIO(wgh.SIOCSWG, &data); err != nil {
// ioctl functions always return a wrapped unix.Errno value.
// Conform to the wgctrl contract by unwrapping some values:
// ENXIO: "no such device": (no such WireGuard device)
// EINVAL: "inappropriate ioctl for device" (device is not a
// WireGuard device)
switch err.(*os.SyscallError).Err {
case unix.ENXIO, unix.EINVAL:
return os.ErrNotExist
default:
return err
}
}
return nil
}
// deviceName converts an interface name string to the format required to pass
// with wgh.WGGetServ.
func deviceName(name string) ([16]byte, error) {
var out [unix.IFNAMSIZ]byte
if len(name) > unix.IFNAMSIZ {
return out, fmt.Errorf("wgfreebsd: interface name %q too long", name)
}
copy(out[:], name)
return out, nil
}
// ioctlIfgroupreq returns a function which performs the appropriate ioctl on
// fd to retrieve members of an interface group.
func ioctlIfgroupreq(fd int) func(*wgh.Ifgroupreq) error {
return func(ifg *wgh.Ifgroupreq) error {
return ioctl(fd, unix.SIOCGIFGMEMB, unsafe.Pointer(ifg))
}
}
// ioctlWGDataIO returns a function which performs the appropriate ioctl on
// fd to issue a WireGuard data I/O.
func ioctlWGDataIO(fd int) func(uint, *wgh.WGDataIO) error {
return func(req uint, data *wgh.WGDataIO) error {
return ioctl(fd, req, unsafe.Pointer(data))
}
}
// ioctl is a raw wrapper for the ioctl system call.
func ioctl(fd int, req uint, arg unsafe.Pointer) error {
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if errno != 0 {
return os.NewSyscallError("ioctl", errno)
}
return nil
}
func panicf(format string, a ...interface{}) {
panic(fmt.Sprintf(format, a...))
}
func ntohs(i uint16) int {
b := *(*[2]byte)(unsafe.Pointer(&i))
return int(binary.BigEndian.Uint16(b[:]))
}
func htons(i int) uint16 {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, uint16(i))
return *(*uint16)(unsafe.Pointer(&b[0]))
}
// parseEndpoint converts a struct sockaddr to a Go net.UDPAddr
func parseEndpoint(ep []byte) *net.UDPAddr {
sa := (*unix.RawSockaddr)(unsafe.Pointer(&ep[0]))
switch sa.Family {
case unix.AF_INET:
sa := (*unix.RawSockaddrInet4)(unsafe.Pointer(&ep[0]))
ep := &net.UDPAddr{
IP: make(net.IP, net.IPv4len),
Port: ntohs(sa.Port),
}
copy(ep.IP, sa.Addr[:])
return ep
case unix.AF_INET6:
sa := (*unix.RawSockaddrInet6)(unsafe.Pointer(&ep[0]))
// TODO(mdlayher): IPv6 zone?
ep := &net.UDPAddr{
IP: make(net.IP, net.IPv6len),
Port: ntohs(sa.Port),
}
copy(ep.IP, sa.Addr[:])
return ep
default:
// No endpoint configured.
return nil
}
}
func unparseEndpoint(ep net.UDPAddr) []byte {
var b []byte
if v4 := ep.IP.To4(); v4 != nil {
b = make([]byte, unsafe.Sizeof(unix.RawSockaddrInet4{}))
sa := (*unix.RawSockaddrInet4)(unsafe.Pointer(&b[0]))
sa.Family = unix.AF_INET
sa.Port = htons(ep.Port)
copy(sa.Addr[:], v4)
} else if v6 := ep.IP.To16(); v6 != nil {
b = make([]byte, unsafe.Sizeof(unix.RawSockaddrInet6{}))
sa := (*unix.RawSockaddrInet6)(unsafe.Pointer(&b[0]))
sa.Family = unix.AF_INET6
sa.Port = htons(ep.Port)
copy(sa.Addr[:], v6)
}
return b
}
// parseAllowedIP unpacks a net.IPNet from a WGAIP structure.
func parseAllowedIP(aip nv.List) net.IPNet {
cidr := int(aip["cidr"].(uint64))
if ip, ok := aip["ipv4"]; ok {
return net.IPNet{
IP: net.IP(ip.([]byte)),
Mask: net.CIDRMask(cidr, 32),
}
} else if ip, ok := aip["ipv6"]; ok {
return net.IPNet{
IP: net.IP(ip.([]byte)),
Mask: net.CIDRMask(cidr, 128),
}
} else {
panicf("wgfreebsd: invalid address family for allowed IP: %+v", aip)
return net.IPNet{}
}
}
func unparseAllowedIP(aip net.IPNet) nv.List {
m := nv.List{}
ones, _ := aip.Mask.Size()
m["cidr"] = uint64(ones)
if v4 := aip.IP.To4(); v4 != nil {
m["ipv4"] = []byte(v4)
} else if v6 := aip.IP.To16(); v6 != nil {
m["ipv6"] = []byte(v6)
}
return m
}
// parseTimestamp parses a binary timestamp to a Go time.Time
func parseTimestamp(b []byte) time.Time {
var secs, nsecs int64
buf := bytes.NewReader(b)
// TODO(stv0g): Handle non-little endian machines
binary.Read(buf, binary.LittleEndian, &secs)
binary.Read(buf, binary.LittleEndian, &nsecs)
if secs == 0 && nsecs == 0 {
return time.Time{}
}
return time.Unix(secs, nsecs)
}
// parsePeer unpacks a wgtypes.Peer from a name-value list (nvlist).
func parsePeer(v nv.List) wgtypes.Peer {
p := wgtypes.Peer{
ProtocolVersion: 1,
}
if v, ok := v["public-key"]; ok {
pk := (*wgtypes.Key)(v.([]byte))
p.PublicKey = *pk
}
if v, ok := v["preshared-key"]; ok {
psk := (*wgtypes.Key)(v.([]byte))
p.PresharedKey = *psk
}
if v, ok := v["last-handshake-time"]; ok {
p.LastHandshakeTime = parseTimestamp(v.([]byte))
}
if v, ok := v["endpoint"]; ok {
p.Endpoint = parseEndpoint(v.([]byte))
}
if v, ok := v["persistent-keepalive-interval"]; ok {
p.PersistentKeepaliveInterval = time.Second * time.Duration(v.(uint64))
}
if v, ok := v["rx-bytes"]; ok {
p.ReceiveBytes = int64(v.(uint64))
}
if v, ok := v["tx-bytes"]; ok {
p.TransmitBytes = int64(v.(uint64))
}
if v, ok := v["allowed-ips"]; ok {
m := v.([]nv.List)
for _, aip := range m {
p.AllowedIPs = append(p.AllowedIPs, parseAllowedIP(aip))
}
}
return p
}
// parseDevice decodes the device from a FreeBSD name-value list (nvlist)
func parseDevice(data []byte) (*wgtypes.Device, error) {
dev := &wgtypes.Device{
Type: wgtypes.FreeBSDKernel,
}
m := nv.List{}
if err := nv.Unmarshal(data, m); err != nil {
return nil, err
}
if v, ok := m["public-key"]; ok {
pk := (*wgtypes.Key)(v.([]byte))
dev.PublicKey = *pk
}
if v, ok := m["private-key"]; ok {
sk := (*wgtypes.Key)(v.([]byte))
dev.PrivateKey = *sk
}
if v, ok := m["user-cookie"]; ok {
dev.FirewallMark = int(v.(uint64))
}
if v, ok := m["listen-port"]; ok {
dev.ListenPort = int(v.(uint64))
}
if v, ok := m["peers"]; ok {
m := v.([]nv.List)
for _, n := range m {
peer := parsePeer(n)
dev.Peers = append(dev.Peers, peer)
}
}
return dev, nil
}
// unparsePeerConfig encodes a PeerConfig to a name-value list (nvlist).
func unparsePeerConfig(cfg wgtypes.PeerConfig) nv.List {
m := nv.List{}
m["public-key"] = cfg.PublicKey[:]
if v := cfg.PresharedKey; v != nil {
m["preshared-key"] = v[:]
}
if v := cfg.PersistentKeepaliveInterval; v != nil {
m["persistent-keepalive-interval"] = uint64(v.Seconds())
}
if v := cfg.Endpoint; v != nil {
m["endpoint"] = unparseEndpoint(*v)
}
if cfg.ReplaceAllowedIPs {
m["replace-allowedips"] = true
}
if cfg.Remove {
m["remove"] = true
}
if cfg.AllowedIPs != nil {
aips := []nv.List{}
for _, aip := range cfg.AllowedIPs {
aips = append(aips, unparseAllowedIP(aip))
}
m["allowed-ips"] = aips
}
return m
}
// unparseDevice encodes the device configuration as a FreeBSD name-value list (nvlist).
func unparseConfig(cfg wgtypes.Config) nv.List {
m := nv.List{}
if v := cfg.PrivateKey; v != nil {
m["private-key"] = v[:]
}
if v := cfg.ListenPort; v != nil {
m["listen-port"] = uint64(*v)
}
if v := cfg.FirewallMark; v != nil {
m["user-cookie"] = uint64(*v)
}
if cfg.ReplacePeers {
m["replace-peers"] = true
}
if v := cfg.Peers; v != nil {
peers := []nv.List{}
for _, p := range v {
peer := unparsePeerConfig(p)
peers = append(peers, peer)
}
m["peers"] = peers
}
return m
}
@@ -0,0 +1,6 @@
// Package wgfreebsd provides internal access to FreeBSD's WireGuard
// ioctl interface.
//
// This package is internal-only and not meant for end users to consume.
// Please use package wgctrl (an abstraction over this package) instead.
package wgfreebsd
@@ -0,0 +1,71 @@
//go:build freebsd
// +build freebsd
package nv
// #cgo LDFLAGS: -lnv
// #include <sys/nv.h>
import "C"
import (
"unsafe"
)
// Unmarshal decodes a FreeBSD name-value list (nv(9)) to a Go map
func Unmarshal(d []byte, out List) error {
sz := C.ulong(len(d))
dp := unsafe.Pointer(&d[0])
nvl := C.nvlist_unpack(dp, sz, 0)
return unmarshal(nvl, out)
}
func unmarshal(nvl *C.struct_nvlist, out List) error {
// For debugging
// C.nvlist_dump(nvl, C.int(os.Stdout.Fd()))
var cookie unsafe.Pointer
for {
var typ C.int
ckey := C.nvlist_next(nvl, &typ, &cookie)
if ckey == nil {
break
}
var sz C.size_t
var value interface{}
switch typ {
case C.NV_TYPE_BINARY:
v := C.nvlist_get_binary(nvl, ckey, &sz)
value = C.GoBytes(v, C.int(sz))
case C.NV_TYPE_BOOL:
value = C.nvlist_get_bool(nvl, ckey)
case C.NV_TYPE_NUMBER:
v := C.nvlist_get_number(nvl, ckey)
value = uint64(v)
case C.NV_TYPE_NVLIST_ARRAY:
items := []List{}
nvlSubListsBuf := C.nvlist_get_nvlist_array(nvl, ckey, &sz)
nvlSubLists := unsafe.Slice(nvlSubListsBuf, sz)
for _, nvlSubList := range nvlSubLists {
item := map[string]interface{}{}
if err := unmarshal(nvlSubList, item); err != nil {
return err
}
items = append(items, item)
}
value = items
}
name := C.GoString(ckey)
out[name] = value
}
return nil
}
@@ -0,0 +1,3 @@
// Package nv marshals and unmarshals Go maps to/from FreeBSDs nv(9) name/value lists
// See: https://www.freebsd.org/cgi/man.cgi?query=nv&sektion=9
package nv
@@ -0,0 +1,75 @@
//go:build freebsd
// +build freebsd
package nv
/*
#cgo LDFLAGS: -lnv
#include <stdlib.h>
#include <sys/nv.h>
// For sizeof(*struct nvlist)
typedef struct nvlist *nvlist_ptr;
*/
import "C"
import (
"unsafe"
)
// Marshal encodes a Go map to a FreeBSD name-value list (nv(9))
func Marshal(m List) (*byte, int, error) {
nvl, err := marshal(m)
if err != nil {
return nil, -1, err
}
// For debugging
// C.nvlist_dump(nvl, C.int(os.Stdout.Fd()))
var sz C.size_t
buf := C.nvlist_pack(nvl, &sz)
return (*byte)(buf), int(sz), nil
}
func marshal(m List) (nvl *C.struct_nvlist, err error) {
nvl = C.nvlist_create(0)
for key, value := range m {
ckey := C.CString(key)
switch value := value.(type) {
case bool:
C.nvlist_add_bool(nvl, ckey, C.bool(value))
case uint64:
C.nvlist_add_number(nvl, ckey, C.ulong(value))
case []byte:
sz := len(value)
ptr := C.CBytes(value)
C.nvlist_add_binary(nvl, ckey, ptr, C.size_t(sz))
C.free(ptr)
case []List:
sz := len(value)
buf := C.malloc(C.size_t(C.sizeof_nvlist_ptr * sz))
items := (*[1<<30 - 1]*C.struct_nvlist)(buf)
for i, val := range value {
if items[i], err = marshal(val); err != nil {
C.free(unsafe.Pointer(ckey))
return nil, err
}
}
C.nvlist_add_nvlist_array(nvl, ckey, (**C.struct_nvlist)(buf), C.size_t(sz))
C.free(buf)
}
C.free(unsafe.Pointer(ckey))
}
return
}
@@ -0,0 +1,6 @@
//go:build freebsd
// +build freebsd
package nv
type List map[string]interface{}
@@ -0,0 +1,32 @@
//go:build freebsd && 386
// +build freebsd,386
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go
package wgh
const (
SizeofIfgreq = 0x10
SIOCGWG = 0xc01869d3
SIOCSWG = 0xc01869d2
)
type Ifgroupreq struct {
Name [16]byte
Len uint32
Pad1 [0]byte
Groups *Ifgreq
Pad2 [12]byte
}
type Ifgreq struct {
Ifgrqu [16]byte
}
type WGDataIO struct {
Name [16]byte
Data *byte
Size uint32
}
@@ -0,0 +1,32 @@
//go:build freebsd && amd64
// +build freebsd,amd64
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go
package wgh
const (
SizeofIfgreq = 0x10
SIOCGWG = 0xc02069d3
SIOCSWG = 0xc02069d2
)
type Ifgroupreq struct {
Name [16]byte
Len uint32
Pad1 [4]byte
Groups *Ifgreq
Pad2 [8]byte
}
type Ifgreq struct {
Ifgrqu [16]byte
}
type WGDataIO struct {
Name [16]byte
Data *byte
Size uint64
}
@@ -0,0 +1,32 @@
//go:build freebsd && arm
// +build freebsd,arm
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go
package wgh
const (
SizeofIfgreq = 0x10
SIOCGWG = 0xc01c69d3
SIOCSWG = 0xc01c69d2
)
type Ifgroupreq struct {
Name [16]byte
Len uint32
Pad1 [0]byte
Groups *Ifgreq
Pad2 [12]byte
}
type Ifgreq struct {
Ifgrqu [16]byte
}
type WGDataIO struct {
Name [16]byte
Data *byte
Size uint64
}
@@ -0,0 +1,32 @@
//go:build freebsd && arm64
// +build freebsd,arm64
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go
package wgh
const (
SizeofIfgreq = 0x10
SIOCGWG = 0xc02069d3
SIOCSWG = 0xc02069d2
)
type Ifgroupreq struct {
Name [16]byte
Len uint32
Pad1 [4]byte
Groups *Ifgreq
Pad2 [8]byte
}
type Ifgreq struct {
Ifgrqu [16]byte
}
type WGDataIO struct {
Name [16]byte
Data *byte
Size uint64
}
@@ -0,0 +1,3 @@
// Package wgh is an auto-generated package which contains constants and
// types used to access WireGuard information using ioctl calls.
package wgh
@@ -0,0 +1,33 @@
#/bin/sh
set -x
# Fix up generated code.
gofix()
{
IN=$1
OUT=$2
# Change types that are a nuisance to deal with in Go, use byte for
# consistency, and produce gofmt'd output.
sed 's/]u*int8/]byte/g' $1 | gofmt -s > $2
}
echo -e "//+build freebsd,amd64\n" > /tmp/wgamd64.go
GOARCH=amd64 go tool cgo -godefs defs.go >> /tmp/wgamd64.go
echo -e "//+build freebsd,386\n" > /tmp/wg386.go
GOARCH=386 go tool cgo -godefs defs.go >> /tmp/wg386.go
echo -e "//+build freebsd,arm64\n" > /tmp/wgarm64.go
GOARCH=arm64 go tool cgo -godefs defs.go >> /tmp/wgarm64.go
echo -e "//+build freebsd,arm\n" > /tmp/wgarm.go
GOARCH=arm go tool cgo -godefs defs.go >> /tmp/wgarm.go
gofix /tmp/wgamd64.go defs_freebsd_amd64.go
gofix /tmp/wg386.go defs_freebsd_386.go
gofix /tmp/wgarm64.go defs_freebsd_arm64.go
gofix /tmp/wgarm.go defs_freebsd_arm.go
rm -rf _obj/ /tmp/wg*.go
@@ -0,0 +1,21 @@
package wginternal
import (
"errors"
"io"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// ErrReadOnly indicates that the driver backing a device is read-only. It is
// a sentinel value used in integration tests.
// TODO(mdlayher): consider exposing in API.
var ErrReadOnly = errors.New("driver is read-only")
// A Client is a type which can control a WireGuard device.
type Client interface {
io.Closer
Devices() ([]*wgtypes.Device, error)
Device(name string) (*wgtypes.Device, error)
ConfigureDevice(name string, cfg wgtypes.Config) error
}
@@ -0,0 +1,5 @@
// Package wginternal contains shared internal types for wgctrl.
//
// This package is internal-only and not meant for end users to consume.
// Please use package wgctrl (an abstraction over this package) instead.
package wginternal
@@ -0,0 +1,272 @@
//go:build linux
// +build linux
package wglinux
import (
"errors"
"fmt"
"os"
"syscall"
"github.com/mdlayher/genetlink"
"github.com/mdlayher/netlink"
"github.com/mdlayher/netlink/nlenc"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
var _ wginternal.Client = &Client{}
// A Client provides access to Linux WireGuard netlink information.
type Client struct {
c *genetlink.Conn
family genetlink.Family
interfaces func() ([]string, error)
}
// New creates a new Client and returns whether or not the generic netlink
// interface is available.
func New() (*Client, bool, error) {
c, err := genetlink.Dial(nil)
if err != nil {
return nil, false, err
}
// Best effort version of netlink.Config.Strict due to CentOS 7.
for _, o := range []netlink.ConnOption{
netlink.ExtendedAcknowledge,
netlink.GetStrictCheck,
} {
_ = c.SetOption(o, true)
}
return initClient(c)
}
// initClient is the internal Client constructor used in some tests.
func initClient(c *genetlink.Conn) (*Client, bool, error) {
f, err := c.GetFamily(unix.WG_GENL_NAME)
if err != nil {
_ = c.Close()
if errors.Is(err, os.ErrNotExist) {
// The generic netlink interface is not available.
return nil, false, nil
}
return nil, false, err
}
return &Client{
c: c,
family: f,
// By default, gather only WireGuard interfaces using rtnetlink.
interfaces: rtnlInterfaces,
}, true, nil
}
// Close implements wginternal.Client.
func (c *Client) Close() error {
return c.c.Close()
}
// Devices implements wginternal.Client.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
// By default, rtnetlink is used to fetch a list of all interfaces and then
// filter that list to only find WireGuard interfaces.
//
// The remainder of this function assumes that any returned device from this
// function is a valid WireGuard device.
ifis, err := c.interfaces()
if err != nil {
return nil, err
}
ds := make([]*wgtypes.Device, 0, len(ifis))
for _, ifi := range ifis {
d, err := c.Device(ifi)
if err != nil {
return nil, err
}
ds = append(ds, d)
}
return ds, nil
}
// Device implements wginternal.Client.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
// Don't bother querying netlink with empty input.
if name == "" {
return nil, os.ErrNotExist
}
// Fetching a device by interface index is possible as well, but we only
// support fetching by name as it seems to be more convenient in general.
b, err := netlink.MarshalAttributes([]netlink.Attribute{{
Type: unix.WGDEVICE_A_IFNAME,
Data: nlenc.Bytes(name),
}})
if err != nil {
return nil, err
}
msgs, err := c.execute(unix.WG_CMD_GET_DEVICE, netlink.Request|netlink.Dump, b)
if err != nil {
return nil, err
}
return parseDevice(msgs)
}
// ConfigureDevice implements wginternal.Client.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
// Large configurations are split into batches for use with netlink.
for _, b := range buildBatches(cfg) {
attrs, err := configAttrs(name, b)
if err != nil {
return err
}
// Request acknowledgement of our request from netlink, even though the
// output messages are unused. The netlink package checks and trims the
// status code value.
if _, err := c.execute(unix.WG_CMD_SET_DEVICE, netlink.Request|netlink.Acknowledge, attrs); err != nil {
return err
}
}
return nil
}
// execute executes a single WireGuard netlink request with the specified command,
// header flags, and attribute arguments.
func (c *Client) execute(command uint8, flags netlink.HeaderFlags, attrb []byte) ([]genetlink.Message, error) {
msg := genetlink.Message{
Header: genetlink.Header{
Command: command,
Version: unix.WG_GENL_VERSION,
},
Data: attrb,
}
msgs, err := c.c.Execute(msg, c.family.ID, flags)
if err == nil {
return msgs, nil
}
// We don't want to expose netlink errors directly to callers so unpack to
// something more generic.
oerr, ok := err.(*netlink.OpError)
if !ok {
// Expect all errors to conform to netlink.OpError.
return nil, fmt.Errorf("wglinux: netlink operation returned non-netlink error (please file a bug: https://golang.zx2c4.com/wireguard/wgctrl): %v", err)
}
switch oerr.Err {
// Convert "no such device" and "not a wireguard device" to an error
// compatible with os.ErrNotExist for easy checking.
case unix.ENODEV, unix.ENOTSUP:
return nil, os.ErrNotExist
default:
// Expose the inner error directly (such as EPERM).
return nil, oerr.Err
}
}
// rtnlInterfaces uses rtnetlink to fetch a list of WireGuard interfaces.
func rtnlInterfaces() ([]string, error) {
// Use the stdlib's rtnetlink helpers to get ahold of a table of all
// interfaces, so we can begin filtering it down to just WireGuard devices.
tab, err := syscall.NetlinkRIB(unix.RTM_GETLINK, unix.AF_UNSPEC)
if err != nil {
return nil, fmt.Errorf("wglinux: failed to get list of interfaces from rtnetlink: %v", err)
}
msgs, err := syscall.ParseNetlinkMessage(tab)
if err != nil {
return nil, fmt.Errorf("wglinux: failed to parse rtnetlink messages: %v", err)
}
return parseRTNLInterfaces(msgs)
}
// parseRTNLInterfaces unpacks rtnetlink messages and returns WireGuard
// interface names.
func parseRTNLInterfaces(msgs []syscall.NetlinkMessage) ([]string, error) {
var ifis []string
for _, m := range msgs {
// Only deal with link messages, and they must have an ifinfomsg
// structure appear before the attributes.
if m.Header.Type != unix.RTM_NEWLINK {
continue
}
if len(m.Data) < unix.SizeofIfInfomsg {
return nil, fmt.Errorf("wglinux: rtnetlink message is too short for ifinfomsg: %d", len(m.Data))
}
ad, err := netlink.NewAttributeDecoder(m.Data[syscall.SizeofIfInfomsg:])
if err != nil {
return nil, err
}
// Determine the interface's name and if it's a WireGuard device.
var (
ifi string
isWG bool
)
for ad.Next() {
switch ad.Type() {
case unix.IFLA_IFNAME:
ifi = ad.String()
case unix.IFLA_LINKINFO:
ad.Do(isWGKind(&isWG))
}
}
if err := ad.Err(); err != nil {
return nil, err
}
if isWG {
// Found one; append it to the list.
ifis = append(ifis, ifi)
}
}
return ifis, nil
}
// wgKind is the IFLA_INFO_KIND value for WireGuard devices.
const wgKind = "wireguard"
// isWGKind parses netlink attributes to determine if a link is a WireGuard
// device, then populates ok with the result.
func isWGKind(ok *bool) func(b []byte) error {
return func(b []byte) error {
ad, err := netlink.NewAttributeDecoder(b)
if err != nil {
return err
}
for ad.Next() {
if ad.Type() != unix.IFLA_INFO_KIND {
continue
}
if ad.String() == wgKind {
*ok = true
return nil
}
}
return ad.Err()
}
}
@@ -0,0 +1,293 @@
//go:build linux
// +build linux
package wglinux
import (
"encoding/binary"
"fmt"
"net"
"unsafe"
"github.com/mdlayher/netlink"
"github.com/mdlayher/netlink/nlenc"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// configAttrs creates the required encoded netlink attributes to configure
// the device specified by name using the non-nil fields in cfg.
func configAttrs(name string, cfg wgtypes.Config) ([]byte, error) {
ae := netlink.NewAttributeEncoder()
ae.String(unix.WGDEVICE_A_IFNAME, name)
if cfg.PrivateKey != nil {
ae.Bytes(unix.WGDEVICE_A_PRIVATE_KEY, (*cfg.PrivateKey)[:])
}
if cfg.ListenPort != nil {
ae.Uint16(unix.WGDEVICE_A_LISTEN_PORT, uint16(*cfg.ListenPort))
}
if cfg.FirewallMark != nil {
ae.Uint32(unix.WGDEVICE_A_FWMARK, uint32(*cfg.FirewallMark))
}
if cfg.ReplacePeers {
ae.Uint32(unix.WGDEVICE_A_FLAGS, unix.WGDEVICE_F_REPLACE_PEERS)
}
// Only apply peer attributes if necessary.
if len(cfg.Peers) > 0 {
ae.Nested(unix.WGDEVICE_A_PEERS, func(nae *netlink.AttributeEncoder) error {
// Netlink arrays use type as an array index.
for i, p := range cfg.Peers {
nae.Nested(uint16(i), encodePeer(p))
}
return nil
})
}
return ae.Encode()
}
// ipBatchChunk is a tunable allowed IP batch limit per peer.
//
// Because we don't necessarily know how much space a given peer will occupy,
// we play it safe and use a reasonably small value. Note that this constant
// is used both in this package and tests, so be aware when making changes.
const ipBatchChunk = 256
// peerBatchChunk specifies the number of peers that can appear in a
// configuration before we start splitting it into chunks.
const peerBatchChunk = 32
// shouldBatch determines if a configuration is sufficiently complex that it
// should be split into batches.
func shouldBatch(cfg wgtypes.Config) bool {
if len(cfg.Peers) > peerBatchChunk {
return true
}
var ips int
for _, p := range cfg.Peers {
ips += len(p.AllowedIPs)
}
return ips > ipBatchChunk
}
// buildBatches produces a batch of configs from a single config, if needed.
func buildBatches(cfg wgtypes.Config) []wgtypes.Config {
// Is this a small configuration; no need to batch?
if !shouldBatch(cfg) {
return []wgtypes.Config{cfg}
}
// Use most fields of cfg for our "base" configuration, and only differ
// peers in each batch.
base := cfg
base.Peers = nil
// Track the known peers so that peer IPs are not replaced if a single
// peer has its allowed IPs split into multiple batches.
knownPeers := make(map[wgtypes.Key]struct{})
batches := make([]wgtypes.Config, 0)
for _, p := range cfg.Peers {
batch := base
// Iterate until no more allowed IPs.
var done bool
for !done {
var tmp []net.IPNet
if len(p.AllowedIPs) < ipBatchChunk {
// IPs all fit within a batch; we are done.
tmp = make([]net.IPNet, len(p.AllowedIPs))
copy(tmp, p.AllowedIPs)
done = true
} else {
// IPs are larger than a single batch, copy a batch out and
// advance the cursor.
tmp = make([]net.IPNet, ipBatchChunk)
copy(tmp, p.AllowedIPs[:ipBatchChunk])
p.AllowedIPs = p.AllowedIPs[ipBatchChunk:]
if len(p.AllowedIPs) == 0 {
// IPs ended on a batch boundary; no more IPs left so end
// iteration after this loop.
done = true
}
}
pcfg := wgtypes.PeerConfig{
// PublicKey denotes the peer and must be present.
PublicKey: p.PublicKey,
// Apply the update only flag to every chunk to ensure
// consistency between batches when the kernel module processes
// them.
UpdateOnly: p.UpdateOnly,
// It'd be a bit weird to have a remove peer message with many
// IPs, but just in case, add this to every peer's message.
Remove: p.Remove,
// The IPs for this chunk.
AllowedIPs: tmp,
}
// Only pass certain fields on the first occurrence of a peer, so
// that subsequent IPs won't be wiped out and space isn't wasted.
if _, ok := knownPeers[p.PublicKey]; !ok {
knownPeers[p.PublicKey] = struct{}{}
pcfg.PresharedKey = p.PresharedKey
pcfg.Endpoint = p.Endpoint
pcfg.PersistentKeepaliveInterval = p.PersistentKeepaliveInterval
// Important: do not move or appending peers won't work.
pcfg.ReplaceAllowedIPs = p.ReplaceAllowedIPs
}
// Add a peer configuration to this batch and keep going.
batch.Peers = []wgtypes.PeerConfig{pcfg}
batches = append(batches, batch)
}
}
// Do not allow peer replacement beyond the first message in a batch,
// so we don't overwrite our previous batch work.
for i := range batches {
if i > 0 {
batches[i].ReplacePeers = false
}
}
return batches
}
// encodePeer returns a function to encode PeerConfig nested attributes.
func encodePeer(p wgtypes.PeerConfig) func(ae *netlink.AttributeEncoder) error {
return func(ae *netlink.AttributeEncoder) error {
ae.Bytes(unix.WGPEER_A_PUBLIC_KEY, p.PublicKey[:])
// Flags are stored in a single attribute.
var flags uint32
if p.Remove {
flags |= unix.WGPEER_F_REMOVE_ME
}
if p.ReplaceAllowedIPs {
flags |= unix.WGPEER_F_REPLACE_ALLOWEDIPS
}
if p.UpdateOnly {
flags |= unix.WGPEER_F_UPDATE_ONLY
}
if flags != 0 {
ae.Uint32(unix.WGPEER_A_FLAGS, flags)
}
if p.PresharedKey != nil {
ae.Bytes(unix.WGPEER_A_PRESHARED_KEY, (*p.PresharedKey)[:])
}
if p.Endpoint != nil {
ae.Do(unix.WGPEER_A_ENDPOINT, encodeSockaddr(*p.Endpoint))
}
if p.PersistentKeepaliveInterval != nil {
ae.Uint16(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, uint16(p.PersistentKeepaliveInterval.Seconds()))
}
// Only apply allowed IPs if necessary.
if len(p.AllowedIPs) > 0 {
ae.Nested(unix.WGPEER_A_ALLOWEDIPS, encodeAllowedIPs(p.AllowedIPs))
}
return nil
}
}
// encodeSockaddr returns a function which encodes a net.UDPAddr as raw
// sockaddr_in or sockaddr_in6 bytes.
func encodeSockaddr(endpoint net.UDPAddr) func() ([]byte, error) {
return func() ([]byte, error) {
if !isValidIP(endpoint.IP) {
return nil, fmt.Errorf("wglinux: invalid endpoint IP: %s", endpoint.IP.String())
}
// Is this an IPv6 address?
if isIPv6(endpoint.IP) {
var addr [16]byte
copy(addr[:], endpoint.IP.To16())
sa := unix.RawSockaddrInet6{
Family: unix.AF_INET6,
Port: sockaddrPort(endpoint.Port),
Addr: addr,
}
return (*(*[unix.SizeofSockaddrInet6]byte)(unsafe.Pointer(&sa)))[:], nil
}
// IPv4 address handling.
var addr [4]byte
copy(addr[:], endpoint.IP.To4())
sa := unix.RawSockaddrInet4{
Family: unix.AF_INET,
Port: sockaddrPort(endpoint.Port),
Addr: addr,
}
return (*(*[unix.SizeofSockaddrInet4]byte)(unsafe.Pointer(&sa)))[:], nil
}
}
// encodeAllowedIPs returns a function to encode allowed IP nested attributes.
func encodeAllowedIPs(ipns []net.IPNet) func(ae *netlink.AttributeEncoder) error {
return func(ae *netlink.AttributeEncoder) error {
for i, ipn := range ipns {
if !isValidIP(ipn.IP) {
return fmt.Errorf("wglinux: invalid allowed IP: %s", ipn.IP.String())
}
family := uint16(unix.AF_INET6)
if !isIPv6(ipn.IP) {
// Make sure address is 4 bytes if IPv4.
family = unix.AF_INET
ipn.IP = ipn.IP.To4()
}
// Netlink arrays use type as an array index.
ae.Nested(uint16(i), func(nae *netlink.AttributeEncoder) error {
nae.Uint16(unix.WGALLOWEDIP_A_FAMILY, family)
nae.Bytes(unix.WGALLOWEDIP_A_IPADDR, ipn.IP)
ones, _ := ipn.Mask.Size()
nae.Uint8(unix.WGALLOWEDIP_A_CIDR_MASK, uint8(ones))
return nil
})
}
return nil
}
}
// isValidIP determines if IP is a valid IPv4 or IPv6 address.
func isValidIP(ip net.IP) bool {
return ip.To16() != nil
}
// isIPv6 determines if IP is a valid IPv6 address.
func isIPv6(ip net.IP) bool {
return isValidIP(ip) && ip.To4() == nil
}
// sockaddrPort interprets port as a big endian uint16 for use passing sockaddr
// structures to the kernel.
func sockaddrPort(port int) uint16 {
return binary.BigEndian.Uint16(nlenc.Uint16Bytes(uint16(port)))
}
@@ -0,0 +1,6 @@
// Package wglinux provides internal access to Linux's WireGuard generic
// netlink interface.
//
// This package is internal-only and not meant for end users to consume.
// Please use package wgctrl (an abstraction over this package) instead.
package wglinux
@@ -0,0 +1,303 @@
//go:build linux
// +build linux
package wglinux
import (
"fmt"
"net"
"time"
"unsafe"
"github.com/mdlayher/genetlink"
"github.com/mdlayher/netlink"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// parseDevice parses a Device from a slice of generic netlink messages,
// automatically merging peer lists from subsequent messages into the Device
// from the first message.
func parseDevice(msgs []genetlink.Message) (*wgtypes.Device, error) {
var first wgtypes.Device
knownPeers := make(map[wgtypes.Key]int)
for i, m := range msgs {
d, err := parseDeviceLoop(m)
if err != nil {
return nil, err
}
if i == 0 {
// First message contains our target device.
first = *d
// Gather the known peers so that we can merge
// them later if needed
for i := range first.Peers {
knownPeers[first.Peers[i].PublicKey] = i
}
continue
}
// Any subsequent messages have their peer contents merged into the
// first "target" message.
mergeDevices(&first, d, knownPeers)
}
return &first, nil
}
// parseDeviceLoop parses a Device from a single generic netlink message.
func parseDeviceLoop(m genetlink.Message) (*wgtypes.Device, error) {
ad, err := netlink.NewAttributeDecoder(m.Data)
if err != nil {
return nil, err
}
d := wgtypes.Device{Type: wgtypes.LinuxKernel}
for ad.Next() {
switch ad.Type() {
case unix.WGDEVICE_A_IFINDEX:
// Ignored; interface index isn't exposed at all in the userspace
// configuration protocol, and name is more friendly anyway.
case unix.WGDEVICE_A_IFNAME:
d.Name = ad.String()
case unix.WGDEVICE_A_PRIVATE_KEY:
ad.Do(parseKey(&d.PrivateKey))
case unix.WGDEVICE_A_PUBLIC_KEY:
ad.Do(parseKey(&d.PublicKey))
case unix.WGDEVICE_A_LISTEN_PORT:
d.ListenPort = int(ad.Uint16())
case unix.WGDEVICE_A_FWMARK:
d.FirewallMark = int(ad.Uint32())
case unix.WGDEVICE_A_PEERS:
// Netlink array of peers.
//
// Errors while parsing are propagated up to top-level ad.Err check.
ad.Nested(func(nad *netlink.AttributeDecoder) error {
// Initialize to the number of peers in this decoder and begin
// handling nested Peer attributes.
d.Peers = make([]wgtypes.Peer, 0, nad.Len())
for nad.Next() {
nad.Nested(func(nnad *netlink.AttributeDecoder) error {
d.Peers = append(d.Peers, parsePeer(nnad))
return nil
})
}
return nil
})
}
}
if err := ad.Err(); err != nil {
return nil, err
}
return &d, nil
}
// parseAllowedIPs parses a wgtypes.Peer from a netlink attribute payload.
func parsePeer(ad *netlink.AttributeDecoder) wgtypes.Peer {
var p wgtypes.Peer
for ad.Next() {
switch ad.Type() {
case unix.WGPEER_A_PUBLIC_KEY:
ad.Do(parseKey(&p.PublicKey))
case unix.WGPEER_A_PRESHARED_KEY:
ad.Do(parseKey(&p.PresharedKey))
case unix.WGPEER_A_ENDPOINT:
p.Endpoint = &net.UDPAddr{}
ad.Do(parseSockaddr(p.Endpoint))
case unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL:
p.PersistentKeepaliveInterval = time.Duration(ad.Uint16()) * time.Second
case unix.WGPEER_A_LAST_HANDSHAKE_TIME:
ad.Do(parseTimespec(&p.LastHandshakeTime))
case unix.WGPEER_A_RX_BYTES:
p.ReceiveBytes = int64(ad.Uint64())
case unix.WGPEER_A_TX_BYTES:
p.TransmitBytes = int64(ad.Uint64())
case unix.WGPEER_A_ALLOWEDIPS:
ad.Nested(parseAllowedIPs(&p.AllowedIPs))
case unix.WGPEER_A_PROTOCOL_VERSION:
p.ProtocolVersion = int(ad.Uint32())
}
}
return p
}
// parseAllowedIPs parses a slice of net.IPNet from a netlink attribute payload.
func parseAllowedIPs(ipns *[]net.IPNet) func(ad *netlink.AttributeDecoder) error {
return func(ad *netlink.AttributeDecoder) error {
// Initialize to the number of allowed IPs and begin iterating through
// the netlink array to decode each one.
*ipns = make([]net.IPNet, 0, ad.Len())
for ad.Next() {
// Allowed IP nested attributes.
ad.Nested(func(nad *netlink.AttributeDecoder) error {
var (
ipn net.IPNet
mask int
family int
)
for nad.Next() {
switch nad.Type() {
case unix.WGALLOWEDIP_A_IPADDR:
nad.Do(parseAddr(&ipn.IP))
case unix.WGALLOWEDIP_A_CIDR_MASK:
mask = int(nad.Uint8())
case unix.WGALLOWEDIP_A_FAMILY:
family = int(nad.Uint16())
}
}
if err := nad.Err(); err != nil {
return err
}
// The address family determines the correct number of bits in
// the mask.
switch family {
case unix.AF_INET:
ipn.Mask = net.CIDRMask(mask, 32)
case unix.AF_INET6:
ipn.Mask = net.CIDRMask(mask, 128)
}
*ipns = append(*ipns, ipn)
return nil
})
}
return nil
}
}
// parseKey parses a wgtypes.Key from a byte slice.
func parseKey(key *wgtypes.Key) func(b []byte) error {
return func(b []byte) error {
k, err := wgtypes.NewKey(b)
if err != nil {
return err
}
*key = k
return nil
}
}
// parseAddr parses a net.IP from raw in_addr or in6_addr struct bytes.
func parseAddr(ip *net.IP) func(b []byte) error {
return func(b []byte) error {
switch len(b) {
case net.IPv4len, net.IPv6len:
// Okay to convert directly to net.IP; memory layout is identical.
*ip = make(net.IP, len(b))
copy(*ip, b)
return nil
default:
return fmt.Errorf("wglinux: unexpected IP address size: %d", len(b))
}
}
}
// parseSockaddr parses a *net.UDPAddr from raw sockaddr_in or sockaddr_in6 bytes.
func parseSockaddr(endpoint *net.UDPAddr) func(b []byte) error {
return func(b []byte) error {
switch len(b) {
case unix.SizeofSockaddrInet4:
// IPv4 address parsing.
sa := *(*unix.RawSockaddrInet4)(unsafe.Pointer(&b[0]))
*endpoint = net.UDPAddr{
IP: net.IP(sa.Addr[:]).To4(),
Port: int(sockaddrPort(int(sa.Port))),
}
return nil
case unix.SizeofSockaddrInet6:
// IPv6 address parsing.
sa := *(*unix.RawSockaddrInet6)(unsafe.Pointer(&b[0]))
*endpoint = net.UDPAddr{
IP: net.IP(sa.Addr[:]),
Port: int(sockaddrPort(int(sa.Port))),
}
return nil
default:
return fmt.Errorf("wglinux: unexpected sockaddr size: %d", len(b))
}
}
}
// timespec32 is a unix.Timespec with 32-bit integers.
type timespec32 struct {
Sec int32
Nsec int32
}
// timespec64 is a unix.Timespec with 64-bit integers.
type timespec64 struct {
Sec int64
Nsec int64
}
const (
sizeofTimespec32 = int(unsafe.Sizeof(timespec32{}))
sizeofTimespec64 = int(unsafe.Sizeof(timespec64{}))
)
// parseTimespec parses a time.Time from raw timespec bytes.
func parseTimespec(t *time.Time) func(b []byte) error {
return func(b []byte) error {
// It would appear that WireGuard can return a __kernel_timespec which
// uses 64-bit integers, even on 32-bit platforms. Clarification of this
// behavior is being sought in:
// https://lists.zx2c4.com/pipermail/wireguard/2019-April/004088.html.
//
// In the mean time, be liberal and accept 32-bit and 64-bit variants.
var sec, nsec int64
switch len(b) {
case sizeofTimespec32:
ts := *(*timespec32)(unsafe.Pointer(&b[0]))
sec = int64(ts.Sec)
nsec = int64(ts.Nsec)
case sizeofTimespec64:
ts := *(*timespec64)(unsafe.Pointer(&b[0]))
sec = ts.Sec
nsec = ts.Nsec
default:
return fmt.Errorf("wglinux: unexpected timespec size: %d bytes, expected 8 or 16 bytes", len(b))
}
// Only set fields if UNIX timestamp value is greater than 0, so the
// caller will see a zero-value time.Time otherwise.
if sec > 0 || nsec > 0 {
*t = time.Unix(sec, nsec)
}
return nil
}
}
// mergeDevices merges Peer information from d into target. mergeDevices is
// used to deal with multiple incoming netlink messages for the same device.
func mergeDevices(target, d *wgtypes.Device, knownPeers map[wgtypes.Key]int) {
for i := range d.Peers {
// Peer is already known, append to it's allowed IP networks
if peerIndex, ok := knownPeers[d.Peers[i].PublicKey]; ok {
target.Peers[peerIndex].AllowedIPs = append(target.Peers[peerIndex].AllowedIPs, d.Peers[i].AllowedIPs...)
} else { // New peer, add it to the target peers.
target.Peers = append(target.Peers, d.Peers[i])
knownPeers[d.Peers[i].PublicKey] = len(target.Peers) - 1
}
}
}
@@ -0,0 +1,372 @@
//go:build openbsd
// +build openbsd
package wgopenbsd
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"os"
"runtime"
"time"
"unsafe"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgopenbsd/internal/wgh"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// ifGroupWG is the WireGuard interface group name passed to the kernel.
var ifGroupWG = [16]byte{0: 'w', 1: 'g'}
var _ wginternal.Client = &Client{}
// A Client provides access to OpenBSD WireGuard ioctl information.
type Client struct {
// Hooks which use system calls by default, but can also be swapped out
// during tests.
close func() error
ioctlIfgroupreq func(ifg *wgh.Ifgroupreq) error
ioctlWGDataIO func(data *wgh.WGDataIO) error
}
// New creates a new Client and returns whether or not the ioctl interface
// is available.
func New() (*Client, bool, error) {
// The OpenBSD ioctl interface operates on a generic AF_INET socket.
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, 0)
if err != nil {
return nil, false, err
}
// TODO(mdlayher): find a call to invoke here to probe for availability.
// c.Devices won't work because it returns a "not found" error when the
// kernel WireGuard implementation is available but the interface group
// has no members.
// By default, use system call implementations for all hook functions.
return &Client{
close: func() error { return unix.Close(fd) },
ioctlIfgroupreq: ioctlIfgroupreq(fd),
ioctlWGDataIO: ioctlWGDataIO(fd),
}, true, nil
}
// Close implements wginternal.Client.
func (c *Client) Close() error {
return c.close()
}
// Devices implements wginternal.Client.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
ifg := wgh.Ifgroupreq{
// Query for devices in the "wg" group.
Name: ifGroupWG,
}
// Determine how many device names we must allocate memory for.
if err := c.ioctlIfgroupreq(&ifg); err != nil {
return nil, err
}
// ifg.Len is size in bytes; allocate enough memory for the correct number
// of wgh.Ifgreq and then store a pointer to the memory where the data
// should be written (ifgrs) in ifg.Groups.
//
// From a thread in golang-nuts, this pattern is valid:
// "It would be OK to pass a pointer to a struct to ioctl if the struct
// contains a pointer to other Go memory, but the struct field must have
// pointer type."
// See: https://groups.google.com/forum/#!topic/golang-nuts/FfasFTZvU_o.
ifgrs := make([]wgh.Ifgreq, ifg.Len/wgh.SizeofIfgreq)
ifg.Groups = &ifgrs[0]
// Now actually fetch the device names.
if err := c.ioctlIfgroupreq(&ifg); err != nil {
return nil, err
}
// Keep this alive until we're done doing the ioctl dance.
runtime.KeepAlive(&ifg)
devices := make([]*wgtypes.Device, 0, len(ifgrs))
for _, ifgr := range ifgrs {
// Remove any trailing NULL bytes from the interface names.
d, err := c.Device(string(bytes.TrimRight(ifgr.Ifgrqu[:], "\x00")))
if err != nil {
return nil, err
}
devices = append(devices, d)
}
return devices, nil
}
// Device implements wginternal.Client.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
dname, err := deviceName(name)
if err != nil {
return nil, err
}
// First, specify the name of the device and determine how much memory
// must be allocated in order to store the WGInterfaceIO structure and
// any trailing WGPeerIO/WGAIPIOs.
data := wgh.WGDataIO{Name: dname}
// TODO: consider preallocating some memory to avoid a second system call
// if it proves to be a concern.
var mem []byte
for {
if err := c.ioctlWGDataIO(&data); err != nil {
// ioctl functions always return a wrapped unix.Errno value.
// Conform to the wgctrl contract by unwrapping some values:
// ENXIO: "no such device": (no such WireGuard device)
// ENOTTY: "inappropriate ioctl for device" (device is not a
// WireGuard device)
switch err.(*os.SyscallError).Err {
case unix.ENXIO, unix.ENOTTY:
return nil, os.ErrNotExist
default:
return nil, err
}
}
if len(mem) >= int(data.Size) {
// Allocated enough memory!
break
}
// Ensure we don't unsafe cast into uninitialized memory. We need at very
// least a single WGInterfaceIO with no peers.
if data.Size < wgh.SizeofWGInterfaceIO {
return nil, fmt.Errorf("wgopenbsd: kernel returned unexpected number of bytes for WGInterfaceIO: %d", data.Size)
}
// Allocate the appropriate amount of memory and point the kernel at
// the first byte of our slice's backing array. When the loop continues,
// we will check if we've allocated enough memory.
mem = make([]byte, data.Size)
data.Interface = (*wgh.WGInterfaceIO)(unsafe.Pointer(&mem[0]))
}
return parseDevice(name, data.Interface)
}
// parseDevice unpacks a Device from ifio, along with its associated peers
// and their allowed IPs.
func parseDevice(name string, ifio *wgh.WGInterfaceIO) (*wgtypes.Device, error) {
d := &wgtypes.Device{
Name: name,
Type: wgtypes.OpenBSDKernel,
}
// The kernel populates ifio.Flags to indicate which fields are present.
if ifio.Flags&wgh.WG_INTERFACE_HAS_PRIVATE != 0 {
d.PrivateKey = wgtypes.Key(ifio.Private)
}
if ifio.Flags&wgh.WG_INTERFACE_HAS_PUBLIC != 0 {
d.PublicKey = wgtypes.Key(ifio.Public)
}
if ifio.Flags&wgh.WG_INTERFACE_HAS_PORT != 0 {
d.ListenPort = int(ifio.Port)
}
if ifio.Flags&wgh.WG_INTERFACE_HAS_RTABLE != 0 {
d.FirewallMark = int(ifio.Rtable)
}
d.Peers = make([]wgtypes.Peer, 0, ifio.Peers_count)
// If there were no peers, exit early so we do not advance the pointer
// beyond the end of the WGInterfaceIO structure.
if ifio.Peers_count == 0 {
return d, nil
}
// Set our pointer to the beginning of the first peer's location in memory.
peer := (*wgh.WGPeerIO)(unsafe.Pointer(
uintptr(unsafe.Pointer(ifio)) + wgh.SizeofWGInterfaceIO,
))
for i := 0; i < int(ifio.Peers_count); i++ {
p := parsePeer(peer)
// Same idea, we know how many allowed IPs we need to account for, so
// reserve the space and advance the pointer through each WGAIP structure.
p.AllowedIPs = make([]net.IPNet, 0, peer.Aips_count)
for j := uintptr(0); j < uintptr(peer.Aips_count); j++ {
aip := (*wgh.WGAIPIO)(unsafe.Pointer(
uintptr(unsafe.Pointer(peer)) + wgh.SizeofWGPeerIO + j*wgh.SizeofWGAIPIO,
))
p.AllowedIPs = append(p.AllowedIPs, parseAllowedIP(aip))
}
// Prepare for the next iteration.
d.Peers = append(d.Peers, p)
peer = (*wgh.WGPeerIO)(unsafe.Pointer(
uintptr(unsafe.Pointer(peer)) + wgh.SizeofWGPeerIO +
uintptr(peer.Aips_count)*wgh.SizeofWGAIPIO,
))
}
return d, nil
}
// ConfigureDevice implements wginternal.Client.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
// Currently read-only: we must determine if a device belongs to this driver,
// and if it does, return a sentinel so integration tests that configure a
// device can be skipped.
if _, err := c.Device(name); err != nil {
return err
}
return wginternal.ErrReadOnly
}
// deviceName converts an interface name string to the format required to pass
// with wgh.WGGetServ.
func deviceName(name string) ([16]byte, error) {
var out [unix.IFNAMSIZ]byte
if len(name) > unix.IFNAMSIZ {
return out, fmt.Errorf("wgopenbsd: interface name %q too long", name)
}
copy(out[:], name)
return out, nil
}
// parsePeer unpacks a wgtypes.Peer from a WGPeerIO structure.
func parsePeer(pio *wgh.WGPeerIO) wgtypes.Peer {
p := wgtypes.Peer{
ReceiveBytes: int64(pio.Rxbytes),
TransmitBytes: int64(pio.Txbytes),
ProtocolVersion: int(pio.Protocol_version),
}
// Only set last handshake if a non-zero timespec was provided, matching
// the time.Time.IsZero() behavior of internal/wglinux.
if pio.Last_handshake.Sec > 0 && pio.Last_handshake.Nsec > 0 {
p.LastHandshakeTime = time.Unix(
pio.Last_handshake.Sec,
// Conversion required for GOARCH=386.
int64(pio.Last_handshake.Nsec),
)
}
if pio.Flags&wgh.WG_PEER_HAS_PUBLIC != 0 {
p.PublicKey = wgtypes.Key(pio.Public)
}
if pio.Flags&wgh.WG_PEER_HAS_PSK != 0 {
p.PresharedKey = wgtypes.Key(pio.Psk)
}
if pio.Flags&wgh.WG_PEER_HAS_PKA != 0 {
p.PersistentKeepaliveInterval = time.Duration(pio.Pka) * time.Second
}
if pio.Flags&wgh.WG_PEER_HAS_ENDPOINT != 0 {
p.Endpoint = parseEndpoint(pio.Endpoint)
}
return p
}
// parseAllowedIP unpacks a net.IPNet from a WGAIP structure.
func parseAllowedIP(aip *wgh.WGAIPIO) net.IPNet {
switch aip.Af {
case unix.AF_INET:
return net.IPNet{
IP: net.IP(aip.Addr[:net.IPv4len]),
Mask: net.CIDRMask(int(aip.Cidr), 32),
}
case unix.AF_INET6:
return net.IPNet{
IP: net.IP(aip.Addr[:]),
Mask: net.CIDRMask(int(aip.Cidr), 128),
}
default:
panicf("wgopenbsd: invalid address family for allowed IP: %+v", aip)
return net.IPNet{}
}
}
// parseEndpoint parses a peer endpoint from a wgh.WGIP structure.
func parseEndpoint(ep [28]byte) *net.UDPAddr {
// sockaddr* structures have family at index 1.
switch ep[1] {
case unix.AF_INET:
sa := *(*unix.RawSockaddrInet4)(unsafe.Pointer(&ep[0]))
ep := &net.UDPAddr{
IP: make(net.IP, net.IPv4len),
Port: bePort(sa.Port),
}
copy(ep.IP, sa.Addr[:])
return ep
case unix.AF_INET6:
sa := *(*unix.RawSockaddrInet6)(unsafe.Pointer(&ep[0]))
// TODO(mdlayher): IPv6 zone?
ep := &net.UDPAddr{
IP: make(net.IP, net.IPv6len),
Port: bePort(sa.Port),
}
copy(ep.IP, sa.Addr[:])
return ep
default:
// No endpoint configured.
return nil
}
}
// bePort interprets a port integer stored in native endianness as a big
// endian value. This is necessary for proper endpoint port handling on
// little endian machines.
func bePort(port uint16) int {
b := *(*[2]byte)(unsafe.Pointer(&port))
return int(binary.BigEndian.Uint16(b[:]))
}
// ioctlIfgroupreq returns a function which performs the appropriate ioctl on
// fd to retrieve members of an interface group.
func ioctlIfgroupreq(fd int) func(*wgh.Ifgroupreq) error {
return func(ifg *wgh.Ifgroupreq) error {
return ioctl(fd, unix.SIOCGIFGMEMB, unsafe.Pointer(ifg))
}
}
// ioctlWGDataIO returns a function which performs the appropriate ioctl on
// fd to issue a WireGuard data I/O.
func ioctlWGDataIO(fd int) func(*wgh.WGDataIO) error {
return func(data *wgh.WGDataIO) error {
return ioctl(fd, wgh.SIOCGWG, unsafe.Pointer(data))
}
}
// ioctl is a raw wrapper for the ioctl system call.
func ioctl(fd int, req uint, arg unsafe.Pointer) error {
//lint:ignore SA1019 temporarily permitted until we switch to a libc wrapper
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if errno != 0 {
return os.NewSyscallError("ioctl", errno)
}
return nil
}
func panicf(format string, a ...interface{}) {
panic(fmt.Sprintf(format, a...))
}
@@ -0,0 +1,6 @@
// Package wgopenbsd provides internal access to OpenBSD's WireGuard
// ioctl interface.
//
// This package is internal-only and not meant for end users to consume.
// Please use package wgctrl (an abstraction over this package) instead.
package wgopenbsd
@@ -0,0 +1,82 @@
//go:build openbsd && 386
// +build openbsd,386
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go
package wgh
const (
SizeofIfgreq = 0x10
)
type Ifgroupreq struct {
Name [16]byte
Len uint32
Pad1 [0]byte
Groups *Ifgreq
Pad2 [12]byte
}
type Ifgreq struct {
Ifgrqu [16]byte
}
type Timespec struct {
Sec int64
Nsec int32
}
type WGAIPIO struct {
Af uint8
Cidr int32
Addr [16]byte
}
type WGDataIO struct {
Name [16]byte
Size uint32
Interface *WGInterfaceIO
}
type WGInterfaceIO struct {
Flags uint8
Port uint16
Rtable int32
Public [32]byte
Private [32]byte
Peers_count uint32
}
type WGPeerIO struct {
Flags int32
Protocol_version int32
Public [32]byte
Psk [32]byte
Pka uint16
Pad_cgo_0 [2]byte
Endpoint [28]byte
Txbytes uint64
Rxbytes uint64
Last_handshake Timespec
Aips_count uint32
}
const (
SIOCGWG = 0xc01869d3
WG_INTERFACE_HAS_PUBLIC = 0x1
WG_INTERFACE_HAS_PRIVATE = 0x2
WG_INTERFACE_HAS_PORT = 0x4
WG_INTERFACE_HAS_RTABLE = 0x8
WG_INTERFACE_REPLACE_PEERS = 0x10
WG_PEER_HAS_PUBLIC = 0x1
WG_PEER_HAS_PSK = 0x2
WG_PEER_HAS_PKA = 0x4
WG_PEER_HAS_ENDPOINT = 0x8
SizeofWGAIPIO = 0x18
SizeofWGInterfaceIO = 0x4c
SizeofWGPeerIO = 0x88
)
@@ -0,0 +1,82 @@
//go:build openbsd && amd64
// +build openbsd,amd64
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs.go
package wgh
const (
SizeofIfgreq = 0x10
)
type Ifgroupreq struct {
Name [16]byte
Len uint32
Pad1 [4]byte
Groups *Ifgreq
Pad2 [8]byte
}
type Ifgreq struct {
Ifgrqu [16]byte
}
type Timespec struct {
Sec int64
Nsec int64
}
type WGAIPIO struct {
Af uint8
Cidr int32
Addr [16]byte
}
type WGDataIO struct {
Name [16]byte
Size uint64
Interface *WGInterfaceIO
}
type WGInterfaceIO struct {
Flags uint8
Port uint16
Rtable int32
Public [32]byte
Private [32]byte
Peers_count uint64
}
type WGPeerIO struct {
Flags int32
Protocol_version int32
Public [32]byte
Psk [32]byte
Pka uint16
Pad_cgo_0 [2]byte
Endpoint [28]byte
Txbytes uint64
Rxbytes uint64
Last_handshake Timespec
Aips_count uint64
}
const (
SIOCGWG = 0xc02069d3
WG_INTERFACE_HAS_PUBLIC = 0x1
WG_INTERFACE_HAS_PRIVATE = 0x2
WG_INTERFACE_HAS_PORT = 0x4
WG_INTERFACE_HAS_RTABLE = 0x8
WG_INTERFACE_REPLACE_PEERS = 0x10
WG_PEER_HAS_PUBLIC = 0x1
WG_PEER_HAS_PSK = 0x2
WG_PEER_HAS_PKA = 0x4
WG_PEER_HAS_ENDPOINT = 0x8
SizeofWGAIPIO = 0x18
SizeofWGInterfaceIO = 0x50
SizeofWGPeerIO = 0x90
)

Some files were not shown because too many files have changed in this diff Show More