blob: 2e7caf1e94252dd190d36cd5e4e48c3b473700fd [file] [log] [blame]
Neels Hofmeyrad868e22019-11-20 02:36:45 +01001/* Copyright 2019 by sysmocom s.f.m.c. GmbH <info@sysmocom.de>
2 *
3 * All Rights Reserved
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19#include <errno.h>
20#include <inttypes.h>
21
22#include <osmocom/core/logging.h>
23#include <osmocom/gsm/gsm23003.h>
24
25#include <osmocom/gsupclient/gsup_req.h>
26
27/*! Create a new osmo_gsup_req record, decode GSUP and add to a provided list of requests.
28 *
29 * Rationales:
30 *
31 * - osmo_gsup_req makes it easy to handle GSUP requests asynchronously. Before this, a GSUP message struct would be
32 * valid only within a read callback function, and would not survive asynchronous handling, because the struct often
33 * points directly into the received msgb. An osmo_gsup_req takes ownership of the msgb and ensures that the data
34 * remains valid, so that it can easily be queued for later handling.
35 * - osmo_gsup_req unifies the composition of response messages to ensure that all IEs that identify it to belong to
36 * the initial request are preserved / derived, like the source_name, destination_name, session_id, etc (see
37 * osmo_gsup_make_response() for details).
38 * - Deallocation of an osmo_gsup_req is implicit upon sending a response. The idea is that msgb memory leaks are a
39 * recurring source of bugs. By enforcing a request-response relation with implicit deallocation, osmo_gsup_req aims
40 * to help avoid most such memory leaks implicitly.
41 *
42 * The typical GSUP message sequence is:
43 * -> rx request,
44 * <- tx response.
45 *
46 * With osmo_gsup_req we can easily expand to:
47 * -> rx request,
48 * ... wait asynchronously,
49 * <- tx response.
50 *
51 * Only few GSUP conversations go beyond a 1:1 request-response match. But some have a session (e.g. USSD) or more
52 * negotiation may happen before the initial request is completed (e.g. Update Location with interleaved Insert
53 * Subscriber Data), so osmo_gsup_req also allows passing non-final responses.
54 * The final_response flag allows for:
55 * -> rx request,
56 * ... wait async,
57 * <- tx intermediate message to same peer (final_response = false, req remains open),
58 * ... wait async,
59 * -> rx intermediate response,
60 * ... wait async,
61 * <- tx final response (final_response = true, req is deallocated).
62 *
63 * This function takes ownership of the msgb, which will, on success, be owned by the returned osmo_gsup_req instance
64 * until osmo_gsup_req_free(). If a decoding error occurs, send an error response immediately, and return NULL.
65 *
66 * The original CNI entity that sent the message is found in req->source_name. If the message was passed on by an
67 * intermediate CNI peer, then req->via_proxy is set to the immediate peer, and it is the responsibility of the caller
68 * to add req->source_name to the GSUP routes that are serviced by req->via_proxy (usually not relevant for clients with
69 * a single GSUP conn).
70 * Examples:
71 *
72 * "msc" ---> here
73 * source_name = "msc"
74 * via_proxy = <empty>
75 *
76 * "msc" ---> "proxy-HLR" ---> here (e.g. home HLR)
77 * source_name = "msc"
78 * via_proxy = "proxy-HLR"
79 *
80 * "msc" ---> "proxy-HLR" ---> "home-HLR" ---> here (e.g. EUSE)
81 * source_name = "msc"
82 * via_proxy = "home-HLR"
83 *
84 * An osmo_gsup_req must be concluded (and deallocated) by calling one of the osmo_gsup_req_respond* functions.
85 *
86 * Note: osmo_gsup_req API makes use of OTC_SELECT to allocate volatile buffers for logging. Use of
87 * osmo_select_main_ctx() is mandatory when using osmo_gsup_req.
88 *
89 * \param[in] ctx Talloc context for allocation of the new request.
90 * \param[in] from_peer The IPA unit name of the immediate GSUP peer from which this msgb was received.
91 * \param[in] msg The message buffer containing the received GSUP message, where msgb_l2() shall point to the GSUP
92 * message start. The caller no longer owns the msgb when it is passed to this function: on error, the
93 * msgb is freed immediately, and on success, the msgb is owned by the returned osmo_gsup_req.
94 * \param[in] send_response_cb User specific method to send a GSUP response message, invoked upon
95 * osmo_gsup_req_respond*() functions. Typically this invokes encoding and transmitting the
96 * GSUP message over a network socket. See for example gsup_server_send_req_response().
97 * \param[inout] cb_data Context data to be used freely by the caller.
98 * \param[inout] add_to_list List to which to append this request, or NULL for no list.
99 * \return a newly allocated osmo_gsup_req, or NULL on error. If NULL is returned, an error response has already been
100 * dispatched to the send_response_cb.
101 */
Neels Hofmeyrc79bcde2019-12-04 01:04:32 +0100102struct osmo_gsup_req *osmo_gsup_req_new(void *ctx, const struct osmo_cni_peer_id *from_peer, struct msgb *msg,
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100103 osmo_gsup_req_send_response_t send_response_cb, void *cb_data,
104 struct llist_head *add_to_list)
105{
106 static unsigned int next_req_nr = 1;
107 struct osmo_gsup_req *req;
108 int rc;
109
Neels Hofmeyrdfe6f412020-05-04 17:31:15 +0200110 if (!from_peer) {
111 LOGP(DLGSUP, LOGL_ERROR, "Rx GSUP from NULL peer is not allowed\n");
112 msgb_free(msg);
113 return NULL;
114 }
115
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100116 if (!msgb_l2(msg) || !msgb_l2len(msg)) {
117 LOGP(DLGSUP, LOGL_ERROR, "Rx GSUP from %s: missing or empty L2 data\n",
Neels Hofmeyrc79bcde2019-12-04 01:04:32 +0100118 osmo_cni_peer_id_to_str(from_peer));
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100119 msgb_free(msg);
120 return NULL;
121 }
122
123 req = talloc_zero(ctx, struct osmo_gsup_req);
124 OSMO_ASSERT(req);
125 /* Note: req->gsup is declared const, so that the incoming message cannot be modified by handlers. */
126 req->nr = next_req_nr++;
127 req->msg = msg;
128 req->send_response_cb = send_response_cb;
129 req->cb_data = cb_data;
Neels Hofmeyrdfe6f412020-05-04 17:31:15 +0200130 req->source_name = *from_peer;
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100131 rc = osmo_gsup_decode(msgb_l2(req->msg), msgb_l2len(req->msg), (struct osmo_gsup_message*)&req->gsup);
132 if (rc < 0) {
Neels Hofmeyrc79bcde2019-12-04 01:04:32 +0100133 LOGP(DLGSUP, LOGL_ERROR, "Rx GSUP from %s: cannot decode (rc=%d)\n", osmo_cni_peer_id_to_str(from_peer), rc);
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100134 osmo_gsup_req_free(req);
135 return NULL;
136 }
137
138 LOG_GSUP_REQ(req, LOGL_DEBUG, "new request: {%s}\n", osmo_gsup_message_to_str_c(OTC_SELECT, &req->gsup));
139
140 if (req->gsup.source_name_len) {
Neels Hofmeyrc79bcde2019-12-04 01:04:32 +0100141 if (osmo_cni_peer_id_set(&req->source_name, OSMO_CNI_PEER_ID_IPA_NAME,
142 req->gsup.source_name, req->gsup.source_name_len)) {
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100143 LOGP(DLGSUP, LOGL_ERROR,
144 "Rx GSUP from %s: failed to decode source_name, message is not routable\n",
Neels Hofmeyrc79bcde2019-12-04 01:04:32 +0100145 osmo_cni_peer_id_to_str(from_peer));
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100146 osmo_gsup_req_respond_msgt(req, OSMO_GSUP_MSGT_ROUTING_ERROR, true);
147 return NULL;
148 }
149
150 /* The source of the GSUP message is not the immediate GSUP peer; the peer is our proxy for that source.
151 */
Neels Hofmeyrc79bcde2019-12-04 01:04:32 +0100152 if (osmo_cni_peer_id_cmp(&req->source_name, from_peer))
Neels Hofmeyrad868e22019-11-20 02:36:45 +0100153 req->via_proxy = *from_peer;
154 }
155
156 if (!osmo_imsi_str_valid(req->gsup.imsi)) {
157 osmo_gsup_req_respond_err(req, GMM_CAUSE_INV_MAND_INFO, "invalid IMSI: %s",
158 osmo_quote_str(req->gsup.imsi, -1));
159 return NULL;
160 }
161
162 if (add_to_list)
163 llist_add_tail(&req->entry, add_to_list);
164 return req;
165}
166
167/*! Free an osmo_gsup_req and its msgb -- this is usually implicit in osmo_gsup_req_resond_*(), it should not be
168 * necessary to call this directly. */
169void osmo_gsup_req_free(struct osmo_gsup_req *req)
170{
171 LOG_GSUP_REQ(req, LOGL_DEBUG, "free\n");
172 if (req->msg)
173 msgb_free(req->msg);
174 if (req->entry.prev)
175 llist_del(&req->entry);
176 talloc_free(req);
177}
178
179/*! Send a response to a GSUP request.
180 *
181 * Ensure that the response message contains all GSUP IEs that identify it as a response for the request req, by calling
182 * osmo_gsup_make_response().
183 *
184 * The final complete response message is passed to req->send_response_cb() to take care of the transmission.
185 *
186 * \param req Request as previously initialized by osmo_gsup_req_new().
187 * \param response Buffer to compose the response, possibly with some pre-configured IEs.
188 * Any missing IEs are added via osmo_gsup_make_response().
189 * Must not be NULL. Does not need to remain valid memory beyond the function call,
190 * i.e. this can just be a local variable in the calling function.
191 * \param error True when the response message indicates an error response (error message type).
192 * \param final_response True when the request is concluded by this response, which deallocates the req.
193 * False when the request should remain open after this response.
194 * For most plain request->response GSUP messages, this should be True.
195 * \param file Source file for logging as in __FILE__, added by osmo_gsup_req_respond() macro.
196 * \param line Source line for logging as in __LINE__, added by osmo_gsup_req_respond() macro.
197 */
198int _osmo_gsup_req_respond(struct osmo_gsup_req *req, struct osmo_gsup_message *response,
199 bool error, bool final_response, const char *file, int line)
200{
201 int rc;
202
203 rc = osmo_gsup_make_response(response, &req->gsup, error, final_response);
204 if (rc) {
205 LOG_GSUP_REQ_SRC(req, LOGL_ERROR, file, line, "Invalid response (rc=%d): {%s}\n",
206 rc, osmo_gsup_message_to_str_c(OTC_SELECT, response));
207 rc = -EINVAL;
208 goto exit_cleanup;
209 }
210
211 if (!req->send_response_cb) {
212 LOG_GSUP_REQ_SRC(req, LOGL_ERROR, file, line, "No send_response_cb set, cannot send: {%s}\n",
213 osmo_gsup_message_to_str_c(OTC_SELECT, response));
214 rc = -EINVAL;
215 goto exit_cleanup;
216 }
217
218 LOG_GSUP_REQ_SRC(req, LOGL_DEBUG, file, line, "Tx response: {%s}\n",
219 osmo_gsup_message_to_str_c(OTC_SELECT, response));
220 req->send_response_cb(req, response);
221
222exit_cleanup:
223 if (final_response)
224 osmo_gsup_req_free(req);
225 return rc;
226}
227
228/*! Shorthand for _osmo_gsup_req_respond() with no additional IEs and a fixed message type.
229 * Set the message type in a local osmo_gsup_message and feed it to _osmo_gsup_req_respond().
230 * That will ensure to add all IEs that identify it as a response to req.
231 *
232 * \param req Request as previously initialized by osmo_gsup_req_new().
233 * \param message_type The GSUP message type discriminator to respond with.
234 * \param final_response True when the request is concluded by this response, which deallocates the req.
235 * False when the request should remain open after this response.
236 * For most plain request->response GSUP messages, this should be True.
237 * \param file Source file for logging as in __FILE__, added by osmo_gsup_req_respond_msgt() macro.
238 * \param line Source line for logging as in __LINE__, added by osmo_gsup_req_respond_msgt() macro.
239 */
240int _osmo_gsup_req_respond_msgt(struct osmo_gsup_req *req, enum osmo_gsup_message_type message_type,
241 bool final_response, const char *file, int line)
242{
243 struct osmo_gsup_message response = {
244 .message_type = message_type,
245 };
246 return _osmo_gsup_req_respond(req, &response, OSMO_GSUP_IS_MSGT_ERROR(message_type), final_response,
247 file, line);
248}
249
250/*! Shorthand for _osmo_gsup_req_respond() with an error cause IEs and using the req's matched error message type.
251 * Set the error cause in a local osmo_gsup_message and feed it to _osmo_gsup_req_respond().
252 * That will ensure to add all IEs that identify it as a response to req.
253 *
254 * Responding with an error always implies a final response: req is implicitly deallocated.
255 *
256 * \param req Request as previously initialized by osmo_gsup_req_new().
257 * \param cause The error cause to include in a OSMO_GSUP_CAUSE_IE.
258 * \param file Source file for logging as in __FILE__, added by osmo_gsup_req_respond_err() macro.
259 * \param line Source line for logging as in __LINE__, added by osmo_gsup_req_respond_err() macro.
260 */
261void _osmo_gsup_req_respond_err(struct osmo_gsup_req *req, enum gsm48_gmm_cause cause,
262 const char *file, int line)
263{
264 struct osmo_gsup_message response = {
265 .cause = cause,
266 };
267
268 /* No need to answer if we couldn't parse an ERROR message type, only REQUESTs need an error reply. */
269 if (!OSMO_GSUP_IS_MSGT_REQUEST(req->gsup.message_type)) {
270 osmo_gsup_req_free(req);
271 return;
272 }
273
274 osmo_gsup_req_respond(req, &response, true, true);
275}
276
277/*! This function is implicitly called by the osmo_gsup_req API, if at all possible rather use osmo_gsup_req_respond().
278 * This function is non-static mostly to allow unit testing.
279 *
280 * Set fields, if still unset, that need to be copied from a received message over to its response message, to ensure
281 * the response can be routed back to the requesting peer even via GSUP proxies.
282 *
283 * Note: after calling this function, fields in the reply may reference the same memory as rx and are not deep-copied,
284 * as is the usual way we are handling decoded GSUP messages.
285 *
286 * These fields are set in the reply message, iff they are still unset:
287 * - Set reply->message_type to the rx's matching RESULT code (or ERROR code if error == true).
288 * - IMSI,
289 * - Set reply->destination_name to rx->source_name (for proxy routing),
290 * - sm_rp_mr (for SMS),
291 * - session_id (for SS/USSD),
292 * - if rx->session_state is not NONE, set tx->session_state depending on the final_response argument:
293 * If false, set to OSMO_GSUP_SESSION_STATE_CONTINUE, else OSMO_GSUP_SESSION_STATE_END.
294 *
295 * If values in reply are already set, they will not be overwritten. The return code is an optional way of finding out
296 * whether all values that were already set in 'reply' are indeed matching the 'rx' values that would have been set.
297 *
298 * \param[in] rx Received GSUP message that is being replied to.
299 * \param[inout] reply The message that should be the response to rx, either empty or with some values already set up.
300 * \return 0 if the resulting message is a valid response for rx, nonzero otherwise. A nonzero rc has no effect on the
301 * values set in the reply message: all unset fields are first updated, and then the rc is determined.
302 * The rc is intended to merely warn if the reply message already contained data that is incompatible with rx,
303 * e.g. a mismatching IMSI.
304 */
305int osmo_gsup_make_response(struct osmo_gsup_message *reply,
306 const struct osmo_gsup_message *rx, bool error, bool final_response)
307{
308 int rc = 0;
309
310 if (!reply->message_type) {
311 if (error)
312 reply->message_type = OSMO_GSUP_TO_MSGT_ERROR(rx->message_type);
313 else
314 reply->message_type = OSMO_GSUP_TO_MSGT_RESULT(rx->message_type);
315 }
316
317 if (*reply->imsi == '\0')
318 OSMO_STRLCPY_ARRAY(reply->imsi, rx->imsi);
319
320 if (reply->message_class == OSMO_GSUP_MESSAGE_CLASS_UNSET)
321 reply->message_class = rx->message_class;
322
323 if (!reply->destination_name || !reply->destination_name_len) {
324 reply->destination_name = rx->source_name;
325 reply->destination_name_len = rx->source_name_len;
326 }
327
328 /* RP-Message-Reference is mandatory for SM Service */
329 if (!reply->sm_rp_mr)
330 reply->sm_rp_mr = rx->sm_rp_mr;
331
332 /* For SS/USSD, it's important to keep both session state and ID IEs */
333 if (!reply->session_id)
334 reply->session_id = rx->session_id;
335 if (rx->session_state != OSMO_GSUP_SESSION_STATE_NONE
336 && reply->session_state == OSMO_GSUP_SESSION_STATE_NONE) {
337 if (final_response || rx->session_state == OSMO_GSUP_SESSION_STATE_END)
338 reply->session_state = OSMO_GSUP_SESSION_STATE_END;
339 else
340 reply->session_state = OSMO_GSUP_SESSION_STATE_CONTINUE;
341 }
342
343 if (strcmp(reply->imsi, rx->imsi))
344 rc |= 1 << 0;
345 if (reply->message_class != rx->message_class)
346 rc |= 1 << 1;
347 if (rx->sm_rp_mr && (!reply->sm_rp_mr || *rx->sm_rp_mr != *reply->sm_rp_mr))
348 rc |= 1 << 2;
349 if (reply->session_id != rx->session_id)
350 rc |= 1 << 3;
351 return rc;
352}
353
354/*! Print the most important value of a GSUP message to a string buffer in human readable form.
355 * \param[out] buf The buffer to write to.
356 * \param[out] buflen sizeof(buf).
357 * \param[in] msg GSUP message to print.
358 */
359size_t osmo_gsup_message_to_str_buf(char *buf, size_t buflen, const struct osmo_gsup_message *msg)
360{
361 struct osmo_strbuf sb = { .buf = buf, .len = buflen };
362 if (!msg) {
363 OSMO_STRBUF_PRINTF(sb, "NULL");
364 return sb.chars_needed;
365 }
366
367 if (msg->message_class)
368 OSMO_STRBUF_PRINTF(sb, "%s ", osmo_gsup_message_class_name(msg->message_class));
369
370 OSMO_STRBUF_PRINTF(sb, "%s:", osmo_gsup_message_type_name(msg->message_type));
371
372 OSMO_STRBUF_PRINTF(sb, " imsi=");
373 OSMO_STRBUF_APPEND(sb, osmo_quote_cstr_buf, msg->imsi, strnlen(msg->imsi, sizeof(msg->imsi)));
374
375 if (msg->cause)
376 OSMO_STRBUF_PRINTF(sb, " cause=%s", get_value_string(gsm48_gmm_cause_names, msg->cause));
377
378 switch (msg->cn_domain) {
379 case OSMO_GSUP_CN_DOMAIN_CS:
380 OSMO_STRBUF_PRINTF(sb, " cn_domain=CS");
381 break;
382 case OSMO_GSUP_CN_DOMAIN_PS:
383 OSMO_STRBUF_PRINTF(sb, " cn_domain=PS");
384 break;
385 default:
386 if (msg->cn_domain)
387 OSMO_STRBUF_PRINTF(sb, " cn_domain=?(%d)", msg->cn_domain);
388 break;
389 }
390
391 if (msg->source_name_len) {
392 OSMO_STRBUF_PRINTF(sb, " source_name=");
393 OSMO_STRBUF_APPEND(sb, osmo_quote_cstr_buf, (char*)msg->source_name, msg->source_name_len);
394 }
395
396 if (msg->destination_name_len) {
397 OSMO_STRBUF_PRINTF(sb, " destination_name=");
398 OSMO_STRBUF_APPEND(sb, osmo_quote_cstr_buf, (char*)msg->destination_name, msg->destination_name_len);
399 }
400
401 if (msg->session_id)
402 OSMO_STRBUF_PRINTF(sb, " session_id=%" PRIu32, msg->session_id);
403 if (msg->session_state)
404 OSMO_STRBUF_PRINTF(sb, " session_state=%s", osmo_gsup_session_state_name(msg->session_state));
405
406 if (msg->sm_rp_mr)
407 OSMO_STRBUF_PRINTF(sb, " sm_rp_mr=%" PRIu8, *msg->sm_rp_mr);
408
409 return sb.chars_needed;
410}
411
412/*! Same as osmo_gsup_message_to_str_buf() but returns a talloc allocated string. */
413char *osmo_gsup_message_to_str_c(void *ctx, const struct osmo_gsup_message *msg)
414{
415 OSMO_NAME_C_IMPL(ctx, 64, "ERROR", osmo_gsup_message_to_str_buf, msg)
416}