1use crate::llm::actions::{
2 client_trait::{Client, ClientActionResult},
3 protocol_trait::Protocol,
4 ActionDefinition, ParameterDefinition,
5};
6use crate::protocol::{ConnectContext, EventType};
7use crate::server::smpp::{
8 actions::{action, parameter},
9 wire,
10};
11use crate::state::app_state::AppState;
12use anyhow::{bail, ensure, Result};
13use serde_json::{json, Value};
14use std::sync::LazyLock;
15
16#[derive(Default)]
17pub struct SmppClientProtocol;
18impl SmppClientProtocol {
19 pub fn new() -> Self {
20 Self
21 }
22}
23
24fn submit_action() -> ActionDefinition {
25 action(
26 "smpp_submit",
27 "Submit a short message; the SMSC's answer arrives as smpp_submit_result, and any receipt later as smpp_deliver.",
28 vec![
29 parameter("source_addr", "string", "Sender address, at most 20 characters", true),
30 parameter("destination_addr", "string", "Recipient address, at most 20 characters", true),
31 parameter("text", "string", "Message text; ASCII goes as the default alphabet, anything else as UCS-2", true),
32 parameter("registered_delivery", "boolean", "Ask the SMSC for a delivery receipt", false),
33 ],
34 json!({"type":"smpp_submit","source_addr":"NetGet","destination_addr":"15551234567","text":"Hello","registered_delivery":true}),
35 )
36}
37
38fn enquire_action() -> ActionDefinition {
39 action(
40 "smpp_enquire_link",
41 "Check the session is alive; the answer arrives as smpp_link_ok.",
42 vec![],
43 json!({"type":"smpp_enquire_link"}),
44 )
45}
46
47fn disconnect_action() -> ActionDefinition {
48 action(
49 "disconnect",
50 "Unbind from the SMSC and close the session",
51 vec![],
52 json!({"type":"disconnect"}),
53 )
54}
55
56fn actions() -> Vec<ActionDefinition> {
57 vec![submit_action(), enquire_action(), disconnect_action()]
58}
59
60pub static BOUND_EVENT: LazyLock<EventType> = LazyLock::new(|| {
61 EventType::new(
62 "smpp_bound",
63 "The SMSC accepted the bind.",
64 submit_action().example.clone(),
65 )
66 .with_parameters(vec![
67 parameter(
68 "smsc_system_id",
69 "string",
70 "The system_id the SMSC returned",
71 true,
72 ),
73 parameter(
74 "bind",
75 "string",
76 "transmitter, receiver or transceiver",
77 true,
78 ),
79 ])
80 .with_actions(actions())
81});
82
83pub static SUBMIT_RESULT_EVENT: LazyLock<EventType> = LazyLock::new(|| {
84 EventType::new(
85 "smpp_submit_result",
86 "The SMSC answered a submit_sm.",
87 enquire_action().example.clone(),
88 )
89 .with_parameters(vec![
90 parameter(
91 "destination_addr",
92 "string",
93 "The recipient that submit was for",
94 true,
95 ),
96 parameter(
97 "status",
98 "string",
99 "ESME_ROK, or the SMSC's error status name",
100 true,
101 ),
102 parameter(
103 "message_id",
104 "string",
105 "The SMSC's id for the message, when accepted",
106 false,
107 ),
108 ])
109 .with_actions(actions())
110});
111
112pub static DELIVER_EVENT: LazyLock<EventType> = LazyLock::new(|| {
113 EventType::new(
114 "smpp_deliver",
115 "The SMSC delivered a message or a delivery receipt; Rust has acknowledged it.",
116 submit_action().example.clone(),
117 )
118 .with_parameters(vec![
119 parameter("source_addr", "string", "The sender's address", true),
120 parameter("destination_addr", "string", "Recipient address", true),
121 parameter(
122 "text",
123 "string",
124 "The text, when its data_coding decodes",
125 false,
126 ),
127 parameter(
128 "data",
129 "string",
130 "The octets in hex, when they are binary",
131 false,
132 ),
133 parameter(
134 "is_receipt",
135 "boolean",
136 "Whether this is a delivery receipt (esm_class 0x04)",
137 true,
138 ),
139 parameter(
140 "receipt",
141 "object",
142 "For a receipt: its id, stat, err and dates",
143 false,
144 ),
145 ])
146 .with_actions(actions())
147});
148
149pub static LINK_OK_EVENT: LazyLock<EventType> = LazyLock::new(|| {
150 EventType::new(
151 "smpp_link_ok",
152 "The SMSC answered enquire_link.",
153 enquire_action().example.clone(),
154 )
155 .with_parameters(vec![parameter(
156 "status",
157 "string",
158 "The enquire_link_resp status name",
159 true,
160 )])
161 .with_actions(actions())
162});
163
164pub fn check(v: &Value) -> Result<()> {
165 match v["type"].as_str() {
166 Some("smpp_submit") => {
167 for key in ["source_addr", "destination_addr"] {
168 let a = v[key]
169 .as_str()
170 .ok_or_else(|| anyhow::anyhow!("{key} must be a string"))?;
171 ensure!(
172 a.len() <= 20 && a.is_ascii(),
173 "{key} is at most 20 ASCII characters"
174 );
175 }
176 let text = v["text"]
177 .as_str()
178 .ok_or_else(|| anyhow::anyhow!("text must be a string"))?;
179 ensure!(
180 wire::encode_text(text).1.len() <= wire::MAX_PAYLOAD,
181 "text exceeds 64 KiB"
182 );
183 ensure!(
184 v.get("registered_delivery").is_none_or(Value::is_boolean),
185 "registered_delivery must be a boolean"
186 );
187 }
188 Some("smpp_enquire_link") => {}
189 _ => bail!("Unknown SMPP client action"),
190 }
191 Ok(())
192}
193
194impl Protocol for SmppClientProtocol {
195 fn protocol_name(&self) -> &'static str {
196 "SMPP"
197 }
198 fn stack_name(&self) -> &'static str {
199 "ETH>IP>TCP>SMPP"
200 }
201 fn keywords(&self) -> Vec<&'static str> {
202 vec!["smpp", "sms", "esme", "submit_sm"]
203 }
204 fn description(&self) -> &'static str {
205 "SMPP 3.4 ESME: binds to an SMSC, submits messages, receives receipts and mobile-originated messages"
206 }
207 fn get_async_actions(&self, _: &AppState) -> Vec<ActionDefinition> {
208 actions()
209 }
210 fn get_sync_actions(&self) -> Vec<ActionDefinition> {
211 vec![]
212 }
213 fn get_event_types(&self) -> Vec<EventType> {
214 vec![
215 BOUND_EVENT.clone(),
216 SUBMIT_RESULT_EVENT.clone(),
217 DELIVER_EVENT.clone(),
218 LINK_OK_EVENT.clone(),
219 ]
220 }
221 fn get_startup_parameters(&self) -> Vec<ParameterDefinition> {
222 vec![
223 ParameterDefinition {
224 name: "system_id".into(),
225 type_hint: "string".into(),
226 description: "system_id to bind as, at most 15 characters".into(),
227 required: true,
228 example: json!("esme1"),
229 default: None,
230 },
231 ParameterDefinition {
232 name: "password".into(),
233 type_hint: "string".into(),
234 description: "Bind password, at most 8 characters".into(),
235 required: false,
236 example: json!("secret"),
237 default: None,
238 },
239 ParameterDefinition {
240 name: "system_type".into(),
241 type_hint: "string".into(),
242 description: "system_type to announce, usually empty".into(),
243 required: false,
244 example: json!(""),
245 default: None,
246 },
247 ParameterDefinition {
248 name: "bind".into(),
249 type_hint: "string".into(),
250 description: "transceiver (send and receive), transmitter (send only) or receiver (receive only)".into(),
251 required: false,
252 example: json!("transmitter"),
253 default: Some(json!(super::DEFAULT_BIND)),
254 },
255 ]
256 }
257 fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
258 use crate::protocol::metadata::*;
259 ProtocolMetadataV2::builder()
260 .state(DevelopmentState::Experimental)
261 .privilege_requirement(PrivilegeRequirement::None)
262 .well_known_port(2775)
263 .implementation("SMPP 3.4 over Tokio TCP: bind_transmitter/receiver/transceiver, submit_sm (message_payload past 254 octets), enquire_link, deliver_sm answered in Rust and decoded including Appendix B receipts, unbind")
264 .llm_control("What to submit and to whom, and what to do with each result, receipt and incoming message")
265 .e2e_testing("tests/client/smpp: NetGet's own SMSC; fiorix/go-smpp's smpptest server (Go) as the independent peer")
266 .notes("Plain TCP, no TLS. A refused bind fails the connection with the SMSC's status. Submits may be pipelined; each result is matched by sequence number. PDUs are capped at 64 KiB of payload; each request has a 30 s deadline.")
267 .max_inbound_bytes(wire::MAX_PDU)
268 .build()
269 }
270 fn example_prompt(&self) -> &'static str {
271 "Bind to the SMSC at 127.0.0.1:2775 as esme1/secret and send Hello to 15551234567 with a receipt"
272 }
273 fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
274 let llm = json!({"type":"open_client","protocol":"smpp","remote_addr":"127.0.0.1:2775","instruction":"Send Hello to 15551234567 and report the receipt","startup_params":{"system_id":"esme1","password":"secret"}});
275 let mut static_example = llm.clone();
276 static_example["event_handlers"] = json!([
277 {"event_pattern":"smpp_bound","handler":{"type":"static","actions":[{"type":"smpp_submit","source_addr":"NetGet","destination_addr":"15551234567","text":"Hello","registered_delivery":true}]}},
278 {"event_pattern":"smpp_deliver","handler":{"type":"static","actions":[{"type":"disconnect"}]}}
279 ]);
280 let mut scripted = static_example.clone();
281 scripted["event_handlers"][1]["handler"] = json!({"type":"script","language":"python","code":"import json,sys\ne=json.load(sys.stdin)['event']\nprint(json.dumps({'actions':[{'type':'disconnect'}] if e['is_receipt'] else []}))"});
282 crate::llm::actions::StartupExamples::new(llm, scripted, static_example)
283 }
284 fn group_name(&self) -> &'static str {
285 "Application"
286 }
287}
288
289impl Client for SmppClientProtocol {
290 fn connect(
291 &self,
292 ctx: ConnectContext,
293 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<std::net::SocketAddr>> + Send>>
294 {
295 Box::pin(super::connect(ctx))
296 }
297 fn execute_action(&self, v: Value) -> Result<ClientActionResult> {
298 if v["type"] == "disconnect" {
299 return Ok(ClientActionResult::Disconnect);
300 }
301 check(&v)?;
302 Ok(ClientActionResult::Custom {
303 name: v["type"].as_str().unwrap_or_default().to_string(),
304 data: v,
305 })
306 }
307}