blob: 13e2b88983577d1953235c63c063e9664f959c65 [file] [log] [blame]
Harald Welte31c9eca2018-10-03 21:03:34 +02001#define _GNU_SOURCE
2
Harald Welte77911b02018-08-14 23:47:30 +02003#include <stdio.h>
4#include <stdlib.h>
5#include <stdint.h>
6#include <unistd.h>
Harald Welte707c85a2019-03-09 12:56:35 +01007#include <errno.h>
Harald Welte77911b02018-08-14 23:47:30 +02008
9#include <pthread.h>
10
11#include <wintypes.h>
12#include <winscard.h>
13#include <pcsclite.h>
14
Harald Welted6dfb8c2018-08-16 14:46:53 +020015#include <sys/socket.h>
16#include <netdb.h>
17
Harald Welte12534e72018-08-15 23:37:29 +020018#include <osmocom/core/socket.h>
Harald Welte77911b02018-08-14 23:47:30 +020019#include <osmocom/core/linuxlist.h>
Harald Weltef94b9ee2018-09-25 15:04:21 +020020#include <osmocom/core/logging.h>
21#include <osmocom/core/application.h>
Harald Welte77911b02018-08-14 23:47:30 +020022
23#include <osmocom/gsm/ipa.h>
24#include <osmocom/gsm/protocol/ipaccess.h>
25
Kévin Redonff5db6e2018-10-11 17:16:18 +020026#include <asn_application.h>
Harald Welte77911b02018-08-14 23:47:30 +020027#include <osmocom/rspro/RsproPDU.h>
28
29#include "bankd.h"
Harald Welte707c85a2019-03-09 12:56:35 +010030#include "remsim_client_fsm.h"
Harald Welte61d98e92019-03-03 15:43:07 +010031#include "debug.h"
Harald Welte796a7492018-09-23 19:31:28 +020032#include "rspro_util.h"
Harald Welte77911b02018-08-14 23:47:30 +020033
34__thread void *talloc_asn1_ctx;
35
36static void *worker_main(void *arg);
37
38/***********************************************************************
39* bankd core / main thread
40***********************************************************************/
41
Harald Welte43ab79f2018-10-03 23:34:21 +020042int asn_debug;
43
Harald Welte77911b02018-08-14 23:47:30 +020044static void bankd_init(struct bankd *bankd)
45{
Harald Weltef94b9ee2018-09-25 15:04:21 +020046 void *g_tall_ctx = talloc_named_const(NULL, 0, "global");
47 osmo_init_logging2(g_tall_ctx, &log_info);
48
Harald Welte43ab79f2018-10-03 23:34:21 +020049 asn_debug = 0;
50
Harald Welte77911b02018-08-14 23:47:30 +020051 /* intialize members of 'bankd' */
Harald Weltecbd18962019-03-03 19:02:38 +010052 bankd->slotmaps = slotmap_init(bankd);
Harald Welte77911b02018-08-14 23:47:30 +020053 INIT_LLIST_HEAD(&bankd->workers);
54 pthread_mutex_init(&bankd->workers_mutex, NULL);
Harald Welte45c948c2018-09-23 19:26:52 +020055
Harald Weltef1dd1622018-09-24 14:54:23 +020056 bankd->comp_id.type = ComponentType_remsimBankd;
57 OSMO_STRLCPY_ARRAY(bankd->comp_id.name, "fixme-name");
58 OSMO_STRLCPY_ARRAY(bankd->comp_id.software, "remsim-bankd");
59 OSMO_STRLCPY_ARRAY(bankd->comp_id.sw_version, PACKAGE_VERSION);
60 /* FIXME: other members of app_comp_id */
61
Harald Welte45c948c2018-09-23 19:26:52 +020062 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
63 * read once during bankd initialization, when the worker threads haven't
64 * started yet */
65 INIT_LLIST_HEAD(&bankd->pcsc_slot_names);
66 OSMO_ASSERT(bankd_pcsc_read_slotnames(bankd, "bankd_pcsc_slots.csv") == 0);
Harald Weltee72e5732018-09-23 19:31:55 +020067
68 /* HACK HACK HACK */
69 {
70 struct bank_slot bs = { .bank_id = 1, };
71 struct client_slot cs = { .client_id = 23, };
72 int i;
73 for (i = 0; i < 5; i++) {
74 bs.slot_nr = cs.slot_nr = i;
Harald Weltecbd18962019-03-03 19:02:38 +010075 slotmap_add(bankd->slotmaps, &bs, &cs);
Harald Weltee72e5732018-09-23 19:31:55 +020076 }
77 }
Harald Welte77911b02018-08-14 23:47:30 +020078}
79
80/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +020081static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +020082{
83 struct bankd_worker *worker;
84 int rc;
85
86 worker = talloc_zero(bankd, struct bankd_worker);
87 if (!worker)
88 return NULL;
89
90 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +020091 worker->num = i;
Harald Welte77911b02018-08-14 23:47:30 +020092
93 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
94
95 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
96 if (rc != 0) {
97 talloc_free(worker);
98 return NULL;
99 }
100
101 pthread_mutex_lock(&bankd->workers_mutex);
102 llist_add_tail(&worker->list, &bankd->workers);
103 pthread_mutex_unlock(&bankd->workers_mutex);
104
105 return worker;
106}
107
108static bool terminate = false;
109
Harald Welte707c85a2019-03-09 12:56:35 +0100110/* handle incoming messages from server */
111static int bankd_srvc_handle_rx(struct rspro_server_conn *srvc, const RsproPDU_t *pdu)
112{
113 struct RsproPDU_t *resp;
114
115 switch (pdu->msg.present) {
116 case RsproPDUchoice_PR_connectBankRes:
117 /* Store 'identity' of server in srvc->peer_comp_id */
118 rspro_comp_id_retrieve(&srvc->peer_comp_id, &pdu->msg.choice.connectBankRes.identity);
119 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_CLIENT_CONN_RES, (void *) pdu);
120 break;
121 default:
122 fprintf(stderr, "Unknown/Unsupported RSPRO PDU type: %u\n", pdu->msg.present);
123 return -1;
124 }
125
126 return 0;
127}
128
129void handle_options(int argc, char **argv)
130{
131}
132
Harald Welte77911b02018-08-14 23:47:30 +0200133int main(int argc, char **argv)
134{
135 struct bankd *bankd = talloc_zero(NULL, struct bankd);
Harald Welte707c85a2019-03-09 12:56:35 +0100136 struct rspro_server_conn *srvc = &bankd->srvc;
Harald Welte77911b02018-08-14 23:47:30 +0200137 int i, rc;
138
139 OSMO_ASSERT(bankd);
140 bankd_init(bankd);
141
Harald Welte707c85a2019-03-09 12:56:35 +0100142 srvc->server_host = "localhost";
143 srvc->server_port = 9998;
144 srvc->handle_rx = bankd_srvc_handle_rx;
145 srvc->own_comp_id.type = ComponentType_remsimBankd;
146 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.name, "fixme-name");
147 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.software, "remsim-bankd");
148 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.sw_version, PACKAGE_VERSION);
149
150 handle_options(argc, argv);
151
152 /* Connection towards remsim-server */
153 rc = server_conn_fsm_alloc(bankd, srvc);
154 if (rc < 0) {
155 fprintf(stderr, "Unable to create Server conn FSM: %s\n", strerror(errno));
156 exit(1);
157 }
158
159 /* create listening socket for inbound client connections */
Harald Welte12534e72018-08-15 23:37:29 +0200160 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 9999, OSMO_SOCK_F_BIND);
161 if (rc < 0)
162 exit(1);
163 bankd->accept_fd = rc;
164
165 /* create worker threads. FIXME: one per reader/slot! */
Harald Welte77911b02018-08-14 23:47:30 +0200166 for (i = 0; i < 10; i++) {
167 struct bankd_worker *w;
Harald Welte8d858292018-08-15 23:36:46 +0200168 w = bankd_create_worker(bankd, i);
Harald Welte77911b02018-08-14 23:47:30 +0200169 if (!w)
170 exit(21);
171 }
172
173 while (1) {
174 if (terminate)
175 break;
Harald Welte8f893ff2018-10-03 23:21:10 +0200176 /* FIXME: Connect to remsim-server from the main thread, register with
177 * it and await + process any slot mapping or other configuration commands.
178 * Ensure to re-connect as needed. */
Harald Welte7f684a02018-08-16 14:43:50 +0200179 sleep(1);
Harald Welte707c85a2019-03-09 12:56:35 +0100180 osmo_select_main(0);
Harald Welte77911b02018-08-14 23:47:30 +0200181 }
182
183 talloc_free(bankd);
184 exit(0);
185}
186
187
188
189/***********************************************************************
190 * bankd worker thread
191 ***********************************************************************/
192
Harald Welte8d858292018-08-15 23:36:46 +0200193struct value_string worker_state_names[] = {
194 { BW_ST_INIT, "INIT" },
195 { BW_ST_ACCEPTING, "ACCEPTING" },
196 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
197 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200198 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200199 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
200 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
201 { 0, NULL }
202};
203
Harald Welteceb3e682018-08-16 14:47:11 +0200204#define LOGW(w, fmt, args...) \
205 printf("[%03u %s] %s:%u " fmt, (w)->num, get_value_string(worker_state_names, (w)->state), \
206 __FILE__, __LINE__, ## args)
207
Harald Welteaf614732018-08-17 22:10:05 +0200208#define PCSC_ERROR(w, rv, text) \
209if (rv != SCARD_S_SUCCESS) { \
210 LOGW((w), text ": %s (0x%lX)\n", pcsc_stringify_error(rv), rv); \
211 goto end; \
212} else { \
Harald Welte7b41d9c2018-10-03 23:15:10 +0200213 LOGW((w), ": OK\n"); \
Harald Welteaf614732018-08-17 22:10:05 +0200214}
215
Harald Welte8d858292018-08-15 23:36:46 +0200216static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
217{
218 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
219 worker->state = new_state;
Harald Welte150d6d62018-10-03 23:07:47 +0200220 worker->timeout = 0;
221}
222
223static void worker_set_state_timeout(struct bankd_worker *worker, enum bankd_worker_state new_state,
224 unsigned int timeout_secs)
225{
226 LOGW(worker, "Changing state to %s (timeout=%u)\n",
227 get_value_string(worker_state_names, new_state), timeout_secs);
228 worker->state = new_state;
229 worker->timeout = timeout_secs;
Harald Welte8d858292018-08-15 23:36:46 +0200230}
Harald Welte77911b02018-08-14 23:47:30 +0200231
232static void worker_cleanup(void *arg)
233{
234 struct bankd_worker *worker = (struct bankd_worker *) arg;
235 struct bankd *bankd = worker->bankd;
236
237 /* FIXME: should we still do this? in the thread ?!? */
238 pthread_mutex_lock(&bankd->workers_mutex);
239 llist_del(&worker->list);
240 talloc_free(worker); /* FIXME: is this safe? */
241 pthread_mutex_unlock(&bankd->workers_mutex);
242}
243
244
Harald Welteaf614732018-08-17 22:10:05 +0200245static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200246{
Harald Welteaf614732018-08-17 22:10:05 +0200247 long rc;
Harald Welte77911b02018-08-14 23:47:30 +0200248
Harald Welte150d6d62018-10-03 23:07:47 +0200249 OSMO_ASSERT(worker->state == BW_ST_CONN_CLIENT_MAPPED);
250
Harald Welte694df832018-10-03 22:47:52 +0200251 if (!worker->reader.name) {
252 /* resolve PC/SC reader name from slot_id -> name map */
253 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
254 if (!worker->reader.name) {
255 LOGW(worker, "No PC/SC reader name configured for %u/%u, fix your config\n",
256 worker->slot.bank_id, worker->slot.slot_nr);
257 rc = -1;
258 goto end;
259 }
260 }
Harald Welte45c948c2018-09-23 19:26:52 +0200261 OSMO_ASSERT(worker->reader.name);
262
Harald Welte694df832018-10-03 22:47:52 +0200263 if (!worker->reader.pcsc.hContext) {
264 LOGW(worker, "Attempting to open PC/SC context\n");
265 /* The PC/SC context must be created inside the thread where we'll later use it */
266 rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &worker->reader.pcsc.hContext);
267 PCSC_ERROR(worker, rc, "SCardEstablishContext")
268 }
Harald Welte45c948c2018-09-23 19:26:52 +0200269
Harald Welte694df832018-10-03 22:47:52 +0200270 if (!worker->reader.pcsc.hCard) {
271 LOGW(worker, "Attempting to open card/slot '%s'\n", worker->reader.name);
272 DWORD dwActiveProtocol;
273 rc = SCardConnect(worker->reader.pcsc.hContext, worker->reader.name, SCARD_SHARE_SHARED,
274 SCARD_PROTOCOL_T0, &worker->reader.pcsc.hCard, &dwActiveProtocol);
275 PCSC_ERROR(worker, rc, "SCardConnect")
276 }
Harald Welte77911b02018-08-14 23:47:30 +0200277
Harald Welte57593f02018-09-23 19:30:31 +0200278 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
Harald Welte150d6d62018-10-03 23:07:47 +0200279 /* FIXME: notify client about this state change */
Harald Welte57593f02018-09-23 19:30:31 +0200280
Harald Welteaf614732018-08-17 22:10:05 +0200281 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200282end:
Harald Welteaf614732018-08-17 22:10:05 +0200283 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200284}
Harald Welte77911b02018-08-14 23:47:30 +0200285
286
287static int blocking_ipa_read(int fd, uint8_t *buf, unsigned int buf_size)
288{
289 struct ipaccess_head *hh;
290 uint16_t len;
291 int needed, rc;
292
293 if (buf_size < sizeof(*hh))
294 return -1;
295
296 hh = (struct ipaccess_head *) buf;
297
298 /* 1) blocking read from the socket (IPA header) */
299 rc = read(fd, buf, sizeof(*hh));
300 if (rc < sizeof(*hh))
301 return -2;
302
303 len = ntohs(hh->len);
304 needed = len; //- sizeof(*hh);
305
306 /* 2) blocking read from the socket (payload) */
307 rc = read(fd, buf+sizeof(*hh), needed);
308 if (rc < needed)
309 return -3;
310
311 return len;
312}
313
Harald Welte796a7492018-09-23 19:31:28 +0200314static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
315{
316 struct msgb *msg = rspro_enc_msg(pdu);
317 int rc;
318
319 if (!msg) {
320 LOGW(worker, "error encoding RSPRO\n");
321 return -1;
322 }
323
Harald Weltefd471192018-09-24 14:51:14 +0200324 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200325 /* prepend the header */
326 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200327 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200328
329 /* actually send it through the socket */
330 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
331 if (rc == msgb_length(msg))
332 rc = 0;
333 else {
334 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
335 rc = -1;
336 }
337
338 msgb_free(msg);
339
340 return rc;
341}
342
Harald Welte150d6d62018-10-03 23:07:47 +0200343/* attempt to obtain slot-map */
344static int worker_try_slotmap(struct bankd_worker *worker)
345{
Harald Weltecbd18962019-03-03 19:02:38 +0100346 struct slot_mapping *slmap;
Harald Welte150d6d62018-10-03 23:07:47 +0200347
Harald Weltecbd18962019-03-03 19:02:38 +0100348 slmap = slotmap_by_client(worker->bankd->slotmaps, &worker->client.clslot);
Harald Welte150d6d62018-10-03 23:07:47 +0200349 if (!slmap) {
350 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
351 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
352 /* check in 10s if the map has been installed meanwhile by main thread */
353 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_WAIT_MAP, 10);
354 return -1;
355 } else {
356 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
357 slmap->client.client_id, slmap->client.slot_nr,
358 slmap->bank.bank_id, slmap->bank.slot_nr);
359 worker->slot = slmap->bank;
360 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_MAPPED, 10);
361 return worker_open_card(worker);
362 }
363}
364
365
Harald Weltecce2aad2018-08-16 14:44:37 +0200366static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
367{
Harald Welteaf614732018-08-17 22:10:05 +0200368 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
Harald Welte3e689872018-09-24 14:52:56 +0200369 e_ResultCode res;
370 RsproPDU_t *resp;
Harald Welteaf614732018-08-17 22:10:05 +0200371
Harald Weltecce2aad2018-08-16 14:44:37 +0200372 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
373
Harald Weltecce2aad2018-08-16 14:44:37 +0200374 LOGW(worker, "connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
375 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
376 /* FIXME: store somewhere? */
377
378 if (worker->state != BW_ST_CONN_WAIT_ID) {
379 LOGW(worker, "Unexpected connectClientReq\n");
380 return -102;
381 }
382
Harald Welte371d0262018-08-16 15:23:58 +0200383 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200384 LOGW(worker, "missing clientID, aborting\n");
385 return -103;
386 }
Harald Welte371d0262018-08-16 15:23:58 +0200387 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
388 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200389 worker_set_state(worker, BW_ST_CONN_CLIENT);
390
Harald Welte150d6d62018-10-03 23:07:47 +0200391 if (worker_try_slotmap(worker) >= 0)
392 res = ResultCode_ok;
393 else
Harald Welte3e689872018-09-24 14:52:56 +0200394 res = ResultCode_cardNotPresent;
Harald Weltecce2aad2018-08-16 14:44:37 +0200395
Harald Welte3e689872018-09-24 14:52:56 +0200396 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
397 return worker_send_rspro(worker, resp);
Harald Weltecce2aad2018-08-16 14:44:37 +0200398}
399
Harald Welte796a7492018-09-23 19:31:28 +0200400static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
401{
402 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
403 const SCARD_IO_REQUEST *pioSendPci = SCARD_PCI_T0;
404 SCARD_IO_REQUEST pioRecvPci;
405 uint8_t rx_buf[1024];
406 DWORD rx_buf_len = sizeof(rx_buf);
407 RsproPDU_t *pdu_resp;
408 long rc;
409
410 LOGW(worker, "tpduModemToCard(%s)\n", osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
411
412 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
413 LOGW(worker, "Unexpected tpduModemToCaard\n");
414 return -104;
415 }
416
417 /* FIXME: Validate that toBankSlot / fromClientSlot match our expectations */
418
419 rc = SCardTransmit(worker->reader.pcsc.hCard,
420 pioSendPci, mdm2sim->data.buf, mdm2sim->data.size,
421 &pioRecvPci, rx_buf, &rx_buf_len);
422 PCSC_ERROR(worker, rc, "SCardTransmit");
423
424 /* encode response PDU and send it */
425 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
426 rx_buf, rx_buf_len);
427 worker_send_rspro(worker, pdu_resp);
428
429 return 0;
430end:
431 return rc;
432}
433
Harald Welte77911b02018-08-14 23:47:30 +0200434/* handle one incoming RSPRO message from a client inside a worker thread */
435static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
436{
Harald Weltecce2aad2018-08-16 14:44:37 +0200437 int rc = -100;
438
Harald Welte77911b02018-08-14 23:47:30 +0200439 switch (pdu->msg.present) {
440 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200441 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200442 break;
443 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200444 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200445 break;
446 case RsproPDUchoice_PR_clientSlotStatusInd:
447 /* FIXME */
448 break;
449 default:
Harald Weltecce2aad2018-08-16 14:44:37 +0200450 rc = -101;
451 break;
Harald Welte77911b02018-08-14 23:47:30 +0200452 }
453
Harald Weltecce2aad2018-08-16 14:44:37 +0200454 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200455}
456
Harald Welte694df832018-10-03 22:47:52 +0200457static int wait_for_fd_or_timeout(int fd, unsigned int timeout_secs)
458{
459 struct timeval tout = { timeout_secs, 0 };
460 fd_set readset;
461
462 FD_ZERO(&readset);
463 FD_SET(fd, &readset);
464 return select(fd + 1, &readset, NULL, NULL, timeout_secs ? &tout : NULL);
465}
466
Harald Welte77911b02018-08-14 23:47:30 +0200467/* body of the main transceive loop */
468static int worker_transceive_loop(struct bankd_worker *worker)
469{
470 struct ipaccess_head *hh;
471 struct ipaccess_head_ext *hh_ext;
472 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
473 asn_dec_rval_t rval;
474 int data_len, rc;
Harald Welte9ebbacc2018-09-24 17:43:39 +0200475 RsproPDU_t *pdu = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200476
Harald Welte694df832018-10-03 22:47:52 +0200477 rc = wait_for_fd_or_timeout(worker->client.fd, worker->timeout);
478 if (rc == 0) {
479 /* TIMEOUT case */
Harald Welte150d6d62018-10-03 23:07:47 +0200480 switch (worker->state) {
481 case BW_ST_CONN_CLIENT_WAIT_MAP:
482 /* re-check if mapping exists meanwhile? */
483 worker_try_slotmap(worker);
484 break;
485 case BW_ST_CONN_CLIENT_MAPPED:
486 /* re-check if reader/card can be opened meanwhile? */
487 worker_open_card(worker);
488 break;
489 default:
490 OSMO_ASSERT(0);
491 }
492 /* return early, so we do another select rather than the blocking read below */
Harald Welte694df832018-10-03 22:47:52 +0200493 return 0;
494 };
495
Harald Welte77911b02018-08-14 23:47:30 +0200496 /* 1) blocking read of entire IPA message from the socket */
497 rc = blocking_ipa_read(worker->client.fd, buf, sizeof(buf));
498 if (rc < 0)
499 return rc;
500 data_len = rc;
501
502 hh = (struct ipaccess_head *) buf;
Harald Welte5a3613a2018-10-11 12:56:21 +0200503 if (hh->proto != IPAC_PROTO_OSMO && hh->proto != IPAC_PROTO_IPACCESS) {
Harald Weltee1176cf2018-09-24 14:54:58 +0200504 LOGW(worker, "Received unsupported IPA protocol != OSMO: 0x%02x\n", hh->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200505 return -4;
Harald Weltee1176cf2018-09-24 14:54:58 +0200506 }
Harald Welte77911b02018-08-14 23:47:30 +0200507
Harald Welte5a3613a2018-10-11 12:56:21 +0200508 if (hh->proto == IPAC_PROTO_IPACCESS) {
509 LOGW(worker, "IPA CCM not implemented yet\n");
510 return 0;
511 }
512
Harald Welte77911b02018-08-14 23:47:30 +0200513 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
Harald Weltee1176cf2018-09-24 14:54:58 +0200514 if (data_len < sizeof(*hh_ext)) {
515 LOGW(worker, "Received short message\n");
Harald Welte77911b02018-08-14 23:47:30 +0200516 return -5;
Harald Weltee1176cf2018-09-24 14:54:58 +0200517 }
Harald Welte77911b02018-08-14 23:47:30 +0200518 data_len -= sizeof(*hh_ext);
Harald Weltee1176cf2018-09-24 14:54:58 +0200519 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO) {
520 LOGW(worker, "Received unsupported IPA EXT protocol != RSPRO: 0x%02x\n", hh_ext->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200521 return -6;
Harald Weltee1176cf2018-09-24 14:54:58 +0200522 }
Harald Welte77911b02018-08-14 23:47:30 +0200523
524 /* 2) ASN1 BER decode of the message */
525 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
Harald Weltee1176cf2018-09-24 14:54:58 +0200526 if (rval.code != RC_OK) {
527 LOGW(worker, "Error during BER decode of RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200528 return -7;
Harald Weltee1176cf2018-09-24 14:54:58 +0200529 }
Harald Welte77911b02018-08-14 23:47:30 +0200530
531 /* 3) handling of the message, possibly resulting in PCSC commands */
532 rc = worker_handle_rspro(worker, pdu);
533 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Weltee1176cf2018-09-24 14:54:58 +0200534 if (rc < 0) {
535 LOGW(worker, "Error handling RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200536 return rc;
Harald Weltee1176cf2018-09-24 14:54:58 +0200537 }
Harald Welte77911b02018-08-14 23:47:30 +0200538
539 /* everything OK if we reach here */
540 return 0;
541}
542
Harald Welted6dfb8c2018-08-16 14:46:53 +0200543/* obtain an ascii representation of the client IP/port */
544static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
545{
546 char hostbuf[32], portbuf[32];
547 int rc;
548
549 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
550 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
551 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
552 if (rc != 0) {
553 out[0] = '\0';
554 return -1;
555 }
556 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
557 return 0;
558}
559
Harald Welte77911b02018-08-14 23:47:30 +0200560/* worker thread main function */
561static void *worker_main(void *arg)
562{
563 struct bankd_worker *worker = (struct bankd_worker *) arg;
564 void *top_ctx;
565 int rc;
Harald Welte31c9eca2018-10-03 21:03:34 +0200566 char worker_name[32];
567
568 /* set the thread name */
569 snprintf(worker_name, sizeof(worker_name), "bankd-worker(%u)", worker->num);
570 pthread_setname_np(pthread_self(), worker_name);
Harald Welte77911b02018-08-14 23:47:30 +0200571
Harald Welte8d858292018-08-15 23:36:46 +0200572 worker_set_state(worker, BW_ST_INIT);
573
Harald Welte77911b02018-08-14 23:47:30 +0200574 /* not permitted in multithreaded environment */
575 talloc_disable_null_tracking();
576 top_ctx = talloc_named_const(NULL, 0, "top");
577 talloc_asn1_ctx = talloc_named_const(top_ctx, 0, "asn1");
578
579 /* push cleanup helper */
580 pthread_cleanup_push(&worker_cleanup, worker);
581
582 /* we continuously perform the same loop here, recycling the worker thread
583 * once the client connection is gone or we have some trouble with the card/reader */
584 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +0200585 char buf[128];
586
Harald Welte77911b02018-08-14 23:47:30 +0200587 worker->client.peer_addr_len = sizeof(worker->client.peer_addr);
588
Harald Welte8d858292018-08-15 23:36:46 +0200589 worker_set_state(worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +0200590 /* first wait for an incoming TCP connection */
591 rc = accept(worker->bankd->accept_fd, (struct sockaddr *) &worker->client.peer_addr,
592 &worker->client.peer_addr_len);
593 if (rc < 0) {
594 continue;
595 }
596 worker->client.fd = rc;
Harald Welted6dfb8c2018-08-16 14:46:53 +0200597 worker_client_addrstr(buf, sizeof(buf), worker);
598 LOGW(worker, "Accepted connection from %s\n", buf);
Harald Welte8d858292018-08-15 23:36:46 +0200599 worker_set_state(worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +0200600
601 /* run the main worker transceive loop body until there was some error */
602 while (1) {
603 rc = worker_transceive_loop(worker);
604 if (rc < 0)
605 break;
606 }
607
Harald Welted6dfb8c2018-08-16 14:46:53 +0200608 LOGW(worker, "Error %d occurred: Cleaning up state\n", rc);
609
Harald Welte77911b02018-08-14 23:47:30 +0200610 /* clean-up: reset to sane state */
611 if (worker->reader.pcsc.hCard) {
612 SCardDisconnect(worker->reader.pcsc.hCard, SCARD_UNPOWER_CARD);
613 worker->reader.pcsc.hCard = 0;
614 }
615 if (worker->reader.pcsc.hContext) {
616 SCardReleaseContext(worker->reader.pcsc.hContext);
617 worker->reader.pcsc.hContext = 0;
618 }
Harald Welte694df832018-10-03 22:47:52 +0200619 if (worker->reader.name)
620 worker->reader.name = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200621 if (worker->client.fd >= 0)
622 close(worker->client.fd);
Harald Welte415e8f62018-08-16 14:47:38 +0200623 memset(&worker->client.peer_addr, 0, sizeof(worker->client.peer_addr));
Harald Welte77911b02018-08-14 23:47:30 +0200624 worker->client.fd = -1;
Harald Welte371d0262018-08-16 15:23:58 +0200625 worker->client.clslot.client_id = worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200626 }
627
628 pthread_cleanup_pop(1);
629 talloc_free(top_ctx);
630 pthread_exit(NULL);
631}