blob: 36f96258bc90a1b1f55089641df231d8b0a2396c [file] [log] [blame]
Harald Welte3dcdd202019-03-09 13:06:46 +01001/* (C) 2018-2019 by Harald Welte <laforge@gnumonks.org>
2 *
3 * All Rights Reserved
4 *
5 * SPDX-License-Identifier: GPL-2.0+
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 */
22
Harald Welte31c9eca2018-10-03 21:03:34 +020023#define _GNU_SOURCE
24
Harald Welte77911b02018-08-14 23:47:30 +020025#include <stdio.h>
26#include <stdlib.h>
27#include <stdint.h>
28#include <unistd.h>
Harald Welte707c85a2019-03-09 12:56:35 +010029#include <errno.h>
Harald Welte77911b02018-08-14 23:47:30 +020030
31#include <pthread.h>
32
33#include <wintypes.h>
34#include <winscard.h>
35#include <pcsclite.h>
36
Harald Welted6dfb8c2018-08-16 14:46:53 +020037#include <sys/socket.h>
38#include <netdb.h>
39
Harald Welte12534e72018-08-15 23:37:29 +020040#include <osmocom/core/socket.h>
Harald Welte77911b02018-08-14 23:47:30 +020041#include <osmocom/core/linuxlist.h>
Harald Weltef94b9ee2018-09-25 15:04:21 +020042#include <osmocom/core/logging.h>
43#include <osmocom/core/application.h>
Harald Welte77911b02018-08-14 23:47:30 +020044
45#include <osmocom/gsm/ipa.h>
46#include <osmocom/gsm/protocol/ipaccess.h>
47
Kévin Redonff5db6e2018-10-11 17:16:18 +020048#include <asn_application.h>
Harald Welte77911b02018-08-14 23:47:30 +020049#include <osmocom/rspro/RsproPDU.h>
50
51#include "bankd.h"
Harald Welte3cded632019-03-09 12:59:41 +010052#include "rspro_client_fsm.h"
Harald Welte61d98e92019-03-03 15:43:07 +010053#include "debug.h"
Harald Welte796a7492018-09-23 19:31:28 +020054#include "rspro_util.h"
Harald Welte77911b02018-08-14 23:47:30 +020055
56__thread void *talloc_asn1_ctx;
Harald Weltef4b16f12019-03-09 20:58:17 +010057struct bankd *g_bankd;
Harald Welte77911b02018-08-14 23:47:30 +020058
59static void *worker_main(void *arg);
60
61/***********************************************************************
62* bankd core / main thread
63***********************************************************************/
64
Harald Welte43ab79f2018-10-03 23:34:21 +020065int asn_debug;
66
Harald Welte77911b02018-08-14 23:47:30 +020067static void bankd_init(struct bankd *bankd)
68{
Harald Weltef94b9ee2018-09-25 15:04:21 +020069 void *g_tall_ctx = talloc_named_const(NULL, 0, "global");
70 osmo_init_logging2(g_tall_ctx, &log_info);
71
Harald Welte43ab79f2018-10-03 23:34:21 +020072 asn_debug = 0;
73
Harald Welte77911b02018-08-14 23:47:30 +020074 /* intialize members of 'bankd' */
Harald Weltecbd18962019-03-03 19:02:38 +010075 bankd->slotmaps = slotmap_init(bankd);
Harald Welte77911b02018-08-14 23:47:30 +020076 INIT_LLIST_HEAD(&bankd->workers);
77 pthread_mutex_init(&bankd->workers_mutex, NULL);
Harald Welte45c948c2018-09-23 19:26:52 +020078
Harald Weltea0f39502019-03-09 20:59:34 +010079 /* set some defaults, overridden by commandline/config */
80 bankd->cfg.bank_id = 1;
81 bankd->cfg.num_slots = 8;
82
Harald Weltef1dd1622018-09-24 14:54:23 +020083 bankd->comp_id.type = ComponentType_remsimBankd;
84 OSMO_STRLCPY_ARRAY(bankd->comp_id.name, "fixme-name");
85 OSMO_STRLCPY_ARRAY(bankd->comp_id.software, "remsim-bankd");
86 OSMO_STRLCPY_ARRAY(bankd->comp_id.sw_version, PACKAGE_VERSION);
87 /* FIXME: other members of app_comp_id */
88
Harald Welte45c948c2018-09-23 19:26:52 +020089 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
90 * read once during bankd initialization, when the worker threads haven't
91 * started yet */
92 INIT_LLIST_HEAD(&bankd->pcsc_slot_names);
93 OSMO_ASSERT(bankd_pcsc_read_slotnames(bankd, "bankd_pcsc_slots.csv") == 0);
Harald Welte77911b02018-08-14 23:47:30 +020094}
95
96/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +020097static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +020098{
99 struct bankd_worker *worker;
100 int rc;
101
102 worker = talloc_zero(bankd, struct bankd_worker);
103 if (!worker)
104 return NULL;
105
106 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +0200107 worker->num = i;
Harald Welte77911b02018-08-14 23:47:30 +0200108
109 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
110
111 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
112 if (rc != 0) {
113 talloc_free(worker);
114 return NULL;
115 }
116
117 pthread_mutex_lock(&bankd->workers_mutex);
118 llist_add_tail(&worker->list, &bankd->workers);
119 pthread_mutex_unlock(&bankd->workers_mutex);
120
121 return worker;
122}
123
124static bool terminate = false;
125
Harald Welte454f5e22019-03-09 21:38:34 +0100126static void rspro2bank_slot(struct bank_slot *out, const BankSlot_t *in)
127{
128 out->bank_id = in->bankId;
129 out->slot_nr = in->slotNr;
130}
131
132static void rspro2client_slot(struct client_slot *out, const ClientSlot_t *in)
133{
134 out->client_id = in->clientId;
135 out->slot_nr = in->slotNr;
136}
137
Harald Welte707c85a2019-03-09 12:56:35 +0100138/* handle incoming messages from server */
139static int bankd_srvc_handle_rx(struct rspro_server_conn *srvc, const RsproPDU_t *pdu)
140{
Harald Welte454f5e22019-03-09 21:38:34 +0100141 const CreateMappingReq_t *creq = NULL;
142 const RemoveMappingReq_t *rreq = NULL;
143 struct slot_mapping *map;
144 struct bank_slot bs;
145 struct client_slot cs;
146 RsproPDU_t *resp;
147
148 LOGPFSM(srvc->fi, "Rx RSPRO %s\n", rspro_msgt_name(pdu));
Harald Welte707c85a2019-03-09 12:56:35 +0100149
150 switch (pdu->msg.present) {
151 case RsproPDUchoice_PR_connectBankRes:
152 /* Store 'identity' of server in srvc->peer_comp_id */
153 rspro_comp_id_retrieve(&srvc->peer_comp_id, &pdu->msg.choice.connectBankRes.identity);
154 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_CLIENT_CONN_RES, (void *) pdu);
155 break;
Harald Welte454f5e22019-03-09 21:38:34 +0100156 case RsproPDUchoice_PR_createMappingReq:
157 creq = &pdu->msg.choice.createMappingReq;
158 if (creq->bank.bankId != g_bankd->cfg.bank_id)
159 resp = rspro_gen_CreateMappingRes(ResultCode_illegalBankId);
160 else if (creq->bank.slotNr >= g_bankd->cfg.num_slots)
161 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
162 else {
163 rspro2bank_slot(&bs, &creq->bank);
164 rspro2client_slot(&cs, &creq->client);
165 /* Add a new mapping */
166 map = slotmap_add(g_bankd->slotmaps, &bs, &cs);
167 if (!map)
168 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
169 else
170 resp = rspro_gen_CreateMappingRes(ResultCode_ok);
171 }
172 server_conn_send_rspro(srvc, resp);
173 break;
174 case RsproPDUchoice_PR_removeMappingReq:
175 rreq = &pdu->msg.choice.removeMappingReq;
176 if (rreq->bank.bankId != g_bankd->cfg.bank_id)
177 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalBankId);
178 else if (rreq->bank.slotNr >= g_bankd->cfg.num_slots)
179 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalSlotId);
180 else {
181 rspro2bank_slot(&bs, &rreq->bank);
182 /* Remove a mapping */
183 map = slotmap_by_bank(g_bankd->slotmaps, &bs);
184 if (!map)
185 resp = rspro_gen_RemoveMappingRes(ResultCode_unknownSlotmap);
186 else {
187 /* FIXME: kill/reset the respective worker, if any! */
188 slotmap_del(g_bankd->slotmaps, map);
189 resp = rspro_gen_RemoveMappingRes(ResultCode_ok);
190 }
191 }
Harald Welte942f1ff2019-03-09 21:49:08 +0100192 server_conn_send_rspro(srvc, resp);
Harald Welte454f5e22019-03-09 21:38:34 +0100193 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100194 default:
195 fprintf(stderr, "Unknown/Unsupported RSPRO PDU type: %u\n", pdu->msg.present);
196 return -1;
197 }
198
199 return 0;
200}
201
202void handle_options(int argc, char **argv)
203{
204}
205
Harald Welte77911b02018-08-14 23:47:30 +0200206int main(int argc, char **argv)
207{
Harald Weltef4b16f12019-03-09 20:58:17 +0100208 struct rspro_server_conn *srvc;
Harald Welte77911b02018-08-14 23:47:30 +0200209 int i, rc;
210
Harald Weltef4b16f12019-03-09 20:58:17 +0100211 g_bankd = talloc_zero(NULL, struct bankd);
212 OSMO_ASSERT(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200213
Harald Weltef4b16f12019-03-09 20:58:17 +0100214 bankd_init(g_bankd);
215
216 srvc = &g_bankd->srvc;
Harald Welte707c85a2019-03-09 12:56:35 +0100217 srvc->server_host = "localhost";
218 srvc->server_port = 9998;
219 srvc->handle_rx = bankd_srvc_handle_rx;
220 srvc->own_comp_id.type = ComponentType_remsimBankd;
221 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.name, "fixme-name");
222 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.software, "remsim-bankd");
223 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.sw_version, PACKAGE_VERSION);
224
225 handle_options(argc, argv);
226
227 /* Connection towards remsim-server */
Harald Weltef4b16f12019-03-09 20:58:17 +0100228 rc = server_conn_fsm_alloc(g_bankd, srvc);
Harald Welte707c85a2019-03-09 12:56:35 +0100229 if (rc < 0) {
230 fprintf(stderr, "Unable to create Server conn FSM: %s\n", strerror(errno));
231 exit(1);
232 }
233
234 /* create listening socket for inbound client connections */
Harald Welte12534e72018-08-15 23:37:29 +0200235 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 9999, OSMO_SOCK_F_BIND);
236 if (rc < 0)
237 exit(1);
Harald Weltef4b16f12019-03-09 20:58:17 +0100238 g_bankd->accept_fd = rc;
Harald Welte12534e72018-08-15 23:37:29 +0200239
Harald Weltea0f39502019-03-09 20:59:34 +0100240 /* create worker threads: One per reader/slot! */
241 for (i = 0; i < g_bankd->cfg.num_slots; i++) {
Harald Welte77911b02018-08-14 23:47:30 +0200242 struct bankd_worker *w;
Harald Weltef4b16f12019-03-09 20:58:17 +0100243 w = bankd_create_worker(g_bankd, i);
Harald Welte77911b02018-08-14 23:47:30 +0200244 if (!w)
245 exit(21);
246 }
247
248 while (1) {
249 if (terminate)
250 break;
Harald Welte8f893ff2018-10-03 23:21:10 +0200251 /* FIXME: Connect to remsim-server from the main thread, register with
252 * it and await + process any slot mapping or other configuration commands.
253 * Ensure to re-connect as needed. */
Harald Welte7f684a02018-08-16 14:43:50 +0200254 sleep(1);
Harald Welte707c85a2019-03-09 12:56:35 +0100255 osmo_select_main(0);
Harald Welte77911b02018-08-14 23:47:30 +0200256 }
257
Harald Weltef4b16f12019-03-09 20:58:17 +0100258 talloc_free(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200259 exit(0);
260}
261
262
263
264/***********************************************************************
265 * bankd worker thread
266 ***********************************************************************/
267
Harald Welte8d858292018-08-15 23:36:46 +0200268struct value_string worker_state_names[] = {
269 { BW_ST_INIT, "INIT" },
270 { BW_ST_ACCEPTING, "ACCEPTING" },
271 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
272 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200273 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200274 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
275 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
276 { 0, NULL }
277};
278
Harald Welteceb3e682018-08-16 14:47:11 +0200279#define LOGW(w, fmt, args...) \
280 printf("[%03u %s] %s:%u " fmt, (w)->num, get_value_string(worker_state_names, (w)->state), \
281 __FILE__, __LINE__, ## args)
282
Harald Welteaf614732018-08-17 22:10:05 +0200283#define PCSC_ERROR(w, rv, text) \
284if (rv != SCARD_S_SUCCESS) { \
285 LOGW((w), text ": %s (0x%lX)\n", pcsc_stringify_error(rv), rv); \
286 goto end; \
287} else { \
Harald Welte7b41d9c2018-10-03 23:15:10 +0200288 LOGW((w), ": OK\n"); \
Harald Welteaf614732018-08-17 22:10:05 +0200289}
290
Harald Welte8d858292018-08-15 23:36:46 +0200291static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
292{
293 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
294 worker->state = new_state;
Harald Welte150d6d62018-10-03 23:07:47 +0200295 worker->timeout = 0;
296}
297
298static void worker_set_state_timeout(struct bankd_worker *worker, enum bankd_worker_state new_state,
299 unsigned int timeout_secs)
300{
301 LOGW(worker, "Changing state to %s (timeout=%u)\n",
302 get_value_string(worker_state_names, new_state), timeout_secs);
303 worker->state = new_state;
304 worker->timeout = timeout_secs;
Harald Welte8d858292018-08-15 23:36:46 +0200305}
Harald Welte77911b02018-08-14 23:47:30 +0200306
307static void worker_cleanup(void *arg)
308{
309 struct bankd_worker *worker = (struct bankd_worker *) arg;
310 struct bankd *bankd = worker->bankd;
311
312 /* FIXME: should we still do this? in the thread ?!? */
313 pthread_mutex_lock(&bankd->workers_mutex);
314 llist_del(&worker->list);
315 talloc_free(worker); /* FIXME: is this safe? */
316 pthread_mutex_unlock(&bankd->workers_mutex);
317}
318
319
Harald Welteaf614732018-08-17 22:10:05 +0200320static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200321{
Harald Welteaf614732018-08-17 22:10:05 +0200322 long rc;
Harald Welte77911b02018-08-14 23:47:30 +0200323
Harald Welte150d6d62018-10-03 23:07:47 +0200324 OSMO_ASSERT(worker->state == BW_ST_CONN_CLIENT_MAPPED);
325
Harald Welte694df832018-10-03 22:47:52 +0200326 if (!worker->reader.name) {
327 /* resolve PC/SC reader name from slot_id -> name map */
328 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
329 if (!worker->reader.name) {
330 LOGW(worker, "No PC/SC reader name configured for %u/%u, fix your config\n",
331 worker->slot.bank_id, worker->slot.slot_nr);
332 rc = -1;
333 goto end;
334 }
335 }
Harald Welte45c948c2018-09-23 19:26:52 +0200336 OSMO_ASSERT(worker->reader.name);
337
Harald Welte694df832018-10-03 22:47:52 +0200338 if (!worker->reader.pcsc.hContext) {
339 LOGW(worker, "Attempting to open PC/SC context\n");
340 /* The PC/SC context must be created inside the thread where we'll later use it */
341 rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &worker->reader.pcsc.hContext);
342 PCSC_ERROR(worker, rc, "SCardEstablishContext")
343 }
Harald Welte45c948c2018-09-23 19:26:52 +0200344
Harald Welte694df832018-10-03 22:47:52 +0200345 if (!worker->reader.pcsc.hCard) {
346 LOGW(worker, "Attempting to open card/slot '%s'\n", worker->reader.name);
347 DWORD dwActiveProtocol;
348 rc = SCardConnect(worker->reader.pcsc.hContext, worker->reader.name, SCARD_SHARE_SHARED,
349 SCARD_PROTOCOL_T0, &worker->reader.pcsc.hCard, &dwActiveProtocol);
350 PCSC_ERROR(worker, rc, "SCardConnect")
351 }
Harald Welte77911b02018-08-14 23:47:30 +0200352
Harald Welte57593f02018-09-23 19:30:31 +0200353 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
Harald Welte150d6d62018-10-03 23:07:47 +0200354 /* FIXME: notify client about this state change */
Harald Welte57593f02018-09-23 19:30:31 +0200355
Harald Welteaf614732018-08-17 22:10:05 +0200356 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200357end:
Harald Welteaf614732018-08-17 22:10:05 +0200358 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200359}
Harald Welte77911b02018-08-14 23:47:30 +0200360
361
362static int blocking_ipa_read(int fd, uint8_t *buf, unsigned int buf_size)
363{
364 struct ipaccess_head *hh;
365 uint16_t len;
366 int needed, rc;
367
368 if (buf_size < sizeof(*hh))
369 return -1;
370
371 hh = (struct ipaccess_head *) buf;
372
373 /* 1) blocking read from the socket (IPA header) */
374 rc = read(fd, buf, sizeof(*hh));
375 if (rc < sizeof(*hh))
376 return -2;
377
378 len = ntohs(hh->len);
379 needed = len; //- sizeof(*hh);
380
381 /* 2) blocking read from the socket (payload) */
382 rc = read(fd, buf+sizeof(*hh), needed);
383 if (rc < needed)
384 return -3;
385
386 return len;
387}
388
Harald Welte796a7492018-09-23 19:31:28 +0200389static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
390{
391 struct msgb *msg = rspro_enc_msg(pdu);
392 int rc;
393
394 if (!msg) {
395 LOGW(worker, "error encoding RSPRO\n");
396 return -1;
397 }
398
Harald Weltefd471192018-09-24 14:51:14 +0200399 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200400 /* prepend the header */
401 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200402 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200403
404 /* actually send it through the socket */
405 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
406 if (rc == msgb_length(msg))
407 rc = 0;
408 else {
409 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
410 rc = -1;
411 }
412
413 msgb_free(msg);
414
415 return rc;
416}
417
Harald Welte150d6d62018-10-03 23:07:47 +0200418/* attempt to obtain slot-map */
419static int worker_try_slotmap(struct bankd_worker *worker)
420{
Harald Weltecbd18962019-03-03 19:02:38 +0100421 struct slot_mapping *slmap;
Harald Welte150d6d62018-10-03 23:07:47 +0200422
Harald Weltecbd18962019-03-03 19:02:38 +0100423 slmap = slotmap_by_client(worker->bankd->slotmaps, &worker->client.clslot);
Harald Welte150d6d62018-10-03 23:07:47 +0200424 if (!slmap) {
425 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
426 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
427 /* check in 10s if the map has been installed meanwhile by main thread */
428 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_WAIT_MAP, 10);
429 return -1;
430 } else {
431 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
432 slmap->client.client_id, slmap->client.slot_nr,
433 slmap->bank.bank_id, slmap->bank.slot_nr);
434 worker->slot = slmap->bank;
435 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_MAPPED, 10);
436 return worker_open_card(worker);
437 }
438}
439
440
Harald Weltecce2aad2018-08-16 14:44:37 +0200441static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
442{
Harald Welteaf614732018-08-17 22:10:05 +0200443 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
Harald Welte458e01b2019-03-10 11:14:43 +0100444 RsproPDU_t *resp = NULL;
Harald Welte3e689872018-09-24 14:52:56 +0200445 e_ResultCode res;
Harald Welte458e01b2019-03-10 11:14:43 +0100446 int rc;
Harald Welteaf614732018-08-17 22:10:05 +0200447
Harald Weltecce2aad2018-08-16 14:44:37 +0200448 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
449
Harald Weltecce2aad2018-08-16 14:44:37 +0200450 LOGW(worker, "connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
451 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
452 /* FIXME: store somewhere? */
453
454 if (worker->state != BW_ST_CONN_WAIT_ID) {
455 LOGW(worker, "Unexpected connectClientReq\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100456 rc = -102;
457 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200458 }
459
Harald Welte371d0262018-08-16 15:23:58 +0200460 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200461 LOGW(worker, "missing clientID, aborting\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100462 res = ResultCode_illegalClientId;
463 rc = -103;
464 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200465 }
Harald Welte371d0262018-08-16 15:23:58 +0200466 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
467 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200468 worker_set_state(worker, BW_ST_CONN_CLIENT);
469
Harald Welte150d6d62018-10-03 23:07:47 +0200470 if (worker_try_slotmap(worker) >= 0)
471 res = ResultCode_ok;
472 else
Harald Welte3e689872018-09-24 14:52:56 +0200473 res = ResultCode_cardNotPresent;
Harald Weltecce2aad2018-08-16 14:44:37 +0200474
Harald Welte3e689872018-09-24 14:52:56 +0200475 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
476 return worker_send_rspro(worker, resp);
Harald Welte458e01b2019-03-10 11:14:43 +0100477
478respond_and_err:
479 if (res) {
480 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
481 worker_send_rspro(worker, resp);
482 }
483 return rc;
Harald Weltecce2aad2018-08-16 14:44:37 +0200484}
485
Harald Welte796a7492018-09-23 19:31:28 +0200486static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
487{
488 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
489 const SCARD_IO_REQUEST *pioSendPci = SCARD_PCI_T0;
490 SCARD_IO_REQUEST pioRecvPci;
491 uint8_t rx_buf[1024];
492 DWORD rx_buf_len = sizeof(rx_buf);
493 RsproPDU_t *pdu_resp;
494 long rc;
495
496 LOGW(worker, "tpduModemToCard(%s)\n", osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
497
498 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
499 LOGW(worker, "Unexpected tpduModemToCaard\n");
500 return -104;
501 }
502
503 /* FIXME: Validate that toBankSlot / fromClientSlot match our expectations */
504
505 rc = SCardTransmit(worker->reader.pcsc.hCard,
506 pioSendPci, mdm2sim->data.buf, mdm2sim->data.size,
507 &pioRecvPci, rx_buf, &rx_buf_len);
508 PCSC_ERROR(worker, rc, "SCardTransmit");
509
510 /* encode response PDU and send it */
511 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
512 rx_buf, rx_buf_len);
513 worker_send_rspro(worker, pdu_resp);
514
515 return 0;
516end:
517 return rc;
518}
519
Harald Welte77911b02018-08-14 23:47:30 +0200520/* handle one incoming RSPRO message from a client inside a worker thread */
521static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
522{
Harald Weltecce2aad2018-08-16 14:44:37 +0200523 int rc = -100;
524
Harald Welte77911b02018-08-14 23:47:30 +0200525 switch (pdu->msg.present) {
526 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200527 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200528 break;
529 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200530 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200531 break;
532 case RsproPDUchoice_PR_clientSlotStatusInd:
533 /* FIXME */
534 break;
535 default:
Harald Weltecce2aad2018-08-16 14:44:37 +0200536 rc = -101;
537 break;
Harald Welte77911b02018-08-14 23:47:30 +0200538 }
539
Harald Weltecce2aad2018-08-16 14:44:37 +0200540 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200541}
542
Harald Welte694df832018-10-03 22:47:52 +0200543static int wait_for_fd_or_timeout(int fd, unsigned int timeout_secs)
544{
545 struct timeval tout = { timeout_secs, 0 };
546 fd_set readset;
547
548 FD_ZERO(&readset);
549 FD_SET(fd, &readset);
550 return select(fd + 1, &readset, NULL, NULL, timeout_secs ? &tout : NULL);
551}
552
Harald Welte77911b02018-08-14 23:47:30 +0200553/* body of the main transceive loop */
554static int worker_transceive_loop(struct bankd_worker *worker)
555{
556 struct ipaccess_head *hh;
557 struct ipaccess_head_ext *hh_ext;
558 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
559 asn_dec_rval_t rval;
560 int data_len, rc;
Harald Welte9ebbacc2018-09-24 17:43:39 +0200561 RsproPDU_t *pdu = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200562
Harald Welte694df832018-10-03 22:47:52 +0200563 rc = wait_for_fd_or_timeout(worker->client.fd, worker->timeout);
564 if (rc == 0) {
565 /* TIMEOUT case */
Harald Welte150d6d62018-10-03 23:07:47 +0200566 switch (worker->state) {
567 case BW_ST_CONN_CLIENT_WAIT_MAP:
568 /* re-check if mapping exists meanwhile? */
569 worker_try_slotmap(worker);
570 break;
571 case BW_ST_CONN_CLIENT_MAPPED:
572 /* re-check if reader/card can be opened meanwhile? */
573 worker_open_card(worker);
574 break;
575 default:
576 OSMO_ASSERT(0);
577 }
578 /* return early, so we do another select rather than the blocking read below */
Harald Welte694df832018-10-03 22:47:52 +0200579 return 0;
580 };
581
Harald Welte77911b02018-08-14 23:47:30 +0200582 /* 1) blocking read of entire IPA message from the socket */
583 rc = blocking_ipa_read(worker->client.fd, buf, sizeof(buf));
584 if (rc < 0)
585 return rc;
586 data_len = rc;
587
588 hh = (struct ipaccess_head *) buf;
Harald Welte5a3613a2018-10-11 12:56:21 +0200589 if (hh->proto != IPAC_PROTO_OSMO && hh->proto != IPAC_PROTO_IPACCESS) {
Harald Weltee1176cf2018-09-24 14:54:58 +0200590 LOGW(worker, "Received unsupported IPA protocol != OSMO: 0x%02x\n", hh->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200591 return -4;
Harald Weltee1176cf2018-09-24 14:54:58 +0200592 }
Harald Welte77911b02018-08-14 23:47:30 +0200593
Harald Welte5a3613a2018-10-11 12:56:21 +0200594 if (hh->proto == IPAC_PROTO_IPACCESS) {
595 LOGW(worker, "IPA CCM not implemented yet\n");
596 return 0;
597 }
598
Harald Welte77911b02018-08-14 23:47:30 +0200599 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
Harald Weltee1176cf2018-09-24 14:54:58 +0200600 if (data_len < sizeof(*hh_ext)) {
601 LOGW(worker, "Received short message\n");
Harald Welte77911b02018-08-14 23:47:30 +0200602 return -5;
Harald Weltee1176cf2018-09-24 14:54:58 +0200603 }
Harald Welte77911b02018-08-14 23:47:30 +0200604 data_len -= sizeof(*hh_ext);
Harald Weltee1176cf2018-09-24 14:54:58 +0200605 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO) {
606 LOGW(worker, "Received unsupported IPA EXT protocol != RSPRO: 0x%02x\n", hh_ext->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200607 return -6;
Harald Weltee1176cf2018-09-24 14:54:58 +0200608 }
Harald Welte77911b02018-08-14 23:47:30 +0200609
610 /* 2) ASN1 BER decode of the message */
611 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
Harald Weltee1176cf2018-09-24 14:54:58 +0200612 if (rval.code != RC_OK) {
613 LOGW(worker, "Error during BER decode of RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200614 return -7;
Harald Weltee1176cf2018-09-24 14:54:58 +0200615 }
Harald Welte77911b02018-08-14 23:47:30 +0200616
617 /* 3) handling of the message, possibly resulting in PCSC commands */
618 rc = worker_handle_rspro(worker, pdu);
619 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Weltee1176cf2018-09-24 14:54:58 +0200620 if (rc < 0) {
621 LOGW(worker, "Error handling RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200622 return rc;
Harald Weltee1176cf2018-09-24 14:54:58 +0200623 }
Harald Welte77911b02018-08-14 23:47:30 +0200624
625 /* everything OK if we reach here */
626 return 0;
627}
628
Harald Welted6dfb8c2018-08-16 14:46:53 +0200629/* obtain an ascii representation of the client IP/port */
630static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
631{
632 char hostbuf[32], portbuf[32];
633 int rc;
634
635 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
636 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
637 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
638 if (rc != 0) {
639 out[0] = '\0';
640 return -1;
641 }
642 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
643 return 0;
644}
645
Harald Welte77911b02018-08-14 23:47:30 +0200646/* worker thread main function */
647static void *worker_main(void *arg)
648{
649 struct bankd_worker *worker = (struct bankd_worker *) arg;
650 void *top_ctx;
651 int rc;
Harald Welte31c9eca2018-10-03 21:03:34 +0200652 char worker_name[32];
653
654 /* set the thread name */
655 snprintf(worker_name, sizeof(worker_name), "bankd-worker(%u)", worker->num);
656 pthread_setname_np(pthread_self(), worker_name);
Harald Welte77911b02018-08-14 23:47:30 +0200657
Harald Welte8d858292018-08-15 23:36:46 +0200658 worker_set_state(worker, BW_ST_INIT);
659
Harald Welte77911b02018-08-14 23:47:30 +0200660 /* not permitted in multithreaded environment */
661 talloc_disable_null_tracking();
662 top_ctx = talloc_named_const(NULL, 0, "top");
663 talloc_asn1_ctx = talloc_named_const(top_ctx, 0, "asn1");
664
665 /* push cleanup helper */
666 pthread_cleanup_push(&worker_cleanup, worker);
667
668 /* we continuously perform the same loop here, recycling the worker thread
669 * once the client connection is gone or we have some trouble with the card/reader */
670 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +0200671 char buf[128];
672
Harald Welte77911b02018-08-14 23:47:30 +0200673 worker->client.peer_addr_len = sizeof(worker->client.peer_addr);
674
Harald Welte8d858292018-08-15 23:36:46 +0200675 worker_set_state(worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +0200676 /* first wait for an incoming TCP connection */
677 rc = accept(worker->bankd->accept_fd, (struct sockaddr *) &worker->client.peer_addr,
678 &worker->client.peer_addr_len);
679 if (rc < 0) {
680 continue;
681 }
682 worker->client.fd = rc;
Harald Welted6dfb8c2018-08-16 14:46:53 +0200683 worker_client_addrstr(buf, sizeof(buf), worker);
684 LOGW(worker, "Accepted connection from %s\n", buf);
Harald Welte8d858292018-08-15 23:36:46 +0200685 worker_set_state(worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +0200686
687 /* run the main worker transceive loop body until there was some error */
688 while (1) {
689 rc = worker_transceive_loop(worker);
690 if (rc < 0)
691 break;
692 }
693
Harald Welted6dfb8c2018-08-16 14:46:53 +0200694 LOGW(worker, "Error %d occurred: Cleaning up state\n", rc);
695
Harald Welte77911b02018-08-14 23:47:30 +0200696 /* clean-up: reset to sane state */
697 if (worker->reader.pcsc.hCard) {
698 SCardDisconnect(worker->reader.pcsc.hCard, SCARD_UNPOWER_CARD);
699 worker->reader.pcsc.hCard = 0;
700 }
701 if (worker->reader.pcsc.hContext) {
702 SCardReleaseContext(worker->reader.pcsc.hContext);
703 worker->reader.pcsc.hContext = 0;
704 }
Harald Welte694df832018-10-03 22:47:52 +0200705 if (worker->reader.name)
706 worker->reader.name = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200707 if (worker->client.fd >= 0)
708 close(worker->client.fd);
Harald Welte415e8f62018-08-16 14:47:38 +0200709 memset(&worker->client.peer_addr, 0, sizeof(worker->client.peer_addr));
Harald Welte77911b02018-08-14 23:47:30 +0200710 worker->client.fd = -1;
Harald Welte371d0262018-08-16 15:23:58 +0200711 worker->client.clslot.client_id = worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200712 }
713
714 pthread_cleanup_pop(1);
715 talloc_free(top_ctx);
716 pthread_exit(NULL);
717}