1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
//! Reply types and helpers.

use std::{collections::HashMap, io::stdout, net::IpAddr, path::PathBuf, process::exit};

use ipnetwork::IpNetwork;
use log::debug;
use macaddr::MacAddr6;
use semver::Version;
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub use crate::dns::Dns;
pub use crate::version::VersionReply;

/// Trait for a reply type to be handled by the [`reply()`] function.
///
/// This is mostly internal, but may be used if you want to output your own
/// reply types for some reason.
pub trait ReplyPayload<'de>: std::fmt::Debug + Serialize + Deserialize<'de> {
	/// The [`exit`] code to be set when replying with this type.
	///
	/// Defaults to 0 (success).
	fn code(&self) -> i32 {
		0
	}
}

/// The reply structure used when returning an error.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorReply<'msg> {
	/// The CNI version of the plugin input config.
	#[serde(deserialize_with = "crate::version::deserialize_version")]
	#[serde(serialize_with = "crate::version::serialize_version")]
	pub cni_version: Version,

	/// A code for the error.
	///
	/// Must match the exit code.
	///
	/// Codes 1-99 are reserved by the spec, codes 100+ may be used for plugins'
	/// own error codes. Code 0 is not to be used, as it is for successful exit.
	pub code: i32,

	/// A short message characterising the error.
	///
	/// This is generally a static non-interpolated string.
	pub msg: &'msg str,

	/// A longer message describing the error.
	pub details: String,
}

impl<'de> ReplyPayload<'de> for ErrorReply<'de> {
	/// Sets the exit status of the process to the code of the error reply.
	fn code(&self) -> i32 {
		self.code
	}
}

/// The reply structure used when returning a success.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SuccessReply {
	/// The CNI version of the plugin input config.
	#[serde(deserialize_with = "crate::version::deserialize_version")]
	#[serde(serialize_with = "crate::version::serialize_version")]
	pub cni_version: Version,

	/// The list of all interfaces created by this plugin.
	///
	/// If `prev_result` was included in the input config and had interfaces,
	/// they need to be carried on through into this list.
	#[serde(default)]
	pub interfaces: Vec<Interface>,

	/// The list of all IPs assigned by this plugin.
	///
	/// If `prev_result` was included in the input config and had IPs,
	/// they need to be carried on through into this list.
	#[serde(default)]
	pub ips: Vec<Ip>,

	/// The list of all routes created by this plugin.
	///
	/// If `prev_result` was included in the input config and had routes,
	/// they need to be carried on through into this list.
	#[serde(default)]
	pub routes: Vec<Route>,

	/// Final DNS configuration for the namespace.
	pub dns: Dns,

	/// Custom reply fields.
	#[serde(flatten)]
	pub specific: HashMap<String, Value>,
}

impl<'de> ReplyPayload<'de> for SuccessReply {}

impl SuccessReply {
	/// Cast into an abbreviated success reply if the interface list is empty.
	pub fn into_ipam(self) -> Option<IpamSuccessReply> {
		if self.interfaces.is_empty() {
			Some(IpamSuccessReply {
				cni_version: self.cni_version,
				ips: self.ips,
				routes: self.routes,
				dns: self.dns,
				specific: self.specific,
			})
		} else {
			None
		}
	}
}

/// The reply structure used when returning an abbreviated IPAM success.
///
/// It is identical to [`SuccessReply`] except for the lack of the `interfaces`
/// field.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IpamSuccessReply {
	/// The CNI version of the plugin input config.
	#[serde(deserialize_with = "crate::version::deserialize_version")]
	#[serde(serialize_with = "crate::version::serialize_version")]
	pub cni_version: Version,

	/// The list of all IPs assigned by this plugin.
	///
	/// If `prev_result` was included in the input config and had IPs,
	/// they need to be carried on through into this list.
	#[serde(default)]
	pub ips: Vec<Ip>,

	/// The list of all routes created by this plugin.
	///
	/// If `prev_result` was included in the input config and had routes,
	/// they need to be carried on through into this list.
	#[serde(default)]
	pub routes: Vec<Route>,

	/// Final DNS configuration for the namespace.
	#[serde(default)]
	pub dns: Dns,

	/// Custom reply fields.
	#[serde(flatten)]
	pub specific: HashMap<String, Value>,
}

impl<'de> ReplyPayload<'de> for IpamSuccessReply {}

/// Interface structure for success reply types.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Interface {
	/// The name of the interface.
	pub name: String,

	/// The hardware address of the interface (if applicable).
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub mac: Option<MacAddr6>,

	/// The path to the namespace the interface is in.
	///
	/// This should be the value passed by `CNI_NETNS`.
	///
	/// If the interface is on the host, this should be set to an empty string.
	pub sandbox: PathBuf,
}

/// IP structure for success reply types.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Ip {
	/// The IP address.
	pub address: IpNetwork,

	/// The default gateway for this subnet, if one exists.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub gateway: Option<IpAddr>,

	/// The interface this IP is for.
	///
	/// This must be the index into the `interfaces` list on the parent success
	/// reply structure. It should be `None` for IPAM success replies.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub interface: Option<usize>, // None for ipam
}

/// Route structure for success reply types.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Route {
	/// The destination of the route.
	pub dst: IpNetwork,

	/// The next hop address.
	///
	/// If unset, a value in `gateway` in the `ips` array may be used by the
	/// runtime, but this is not mandated and is left to its discretion.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub gw: Option<IpAddr>,
}

/// Output the reply as JSON on STDOUT and exit.
pub fn reply<'de, T>(result: T) -> !
where
	T: ReplyPayload<'de>,
{
	debug!("replying with {:#?}", result);
	serde_json::to_writer(stdout(), &result)
		.expect("Error writing result to stdout... chances are you won't get this either");

	exit(result.code());
}