blob: f20d3b0de6e5cdc5b379e75db031eadd1162e3a4 [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>
Harald Welte00a96732019-03-11 17:18:02 +010028#include <signal.h>
Harald Welte77911b02018-08-14 23:47:30 +020029#include <unistd.h>
Harald Welte707c85a2019-03-09 12:56:35 +010030#include <errno.h>
Harald Welte77911b02018-08-14 23:47:30 +020031
32#include <pthread.h>
33
34#include <wintypes.h>
35#include <winscard.h>
36#include <pcsclite.h>
37
Harald Welted6dfb8c2018-08-16 14:46:53 +020038#include <sys/socket.h>
39#include <netdb.h>
40
Harald Welte12534e72018-08-15 23:37:29 +020041#include <osmocom/core/socket.h>
Harald Welte77911b02018-08-14 23:47:30 +020042#include <osmocom/core/linuxlist.h>
Harald Weltef94b9ee2018-09-25 15:04:21 +020043#include <osmocom/core/logging.h>
44#include <osmocom/core/application.h>
Harald Welte77911b02018-08-14 23:47:30 +020045
46#include <osmocom/gsm/ipa.h>
47#include <osmocom/gsm/protocol/ipaccess.h>
48
Kévin Redonff5db6e2018-10-11 17:16:18 +020049#include <asn_application.h>
Harald Welte77911b02018-08-14 23:47:30 +020050#include <osmocom/rspro/RsproPDU.h>
51
52#include "bankd.h"
Harald Welte3cded632019-03-09 12:59:41 +010053#include "rspro_client_fsm.h"
Harald Welte61d98e92019-03-03 15:43:07 +010054#include "debug.h"
Harald Welte796a7492018-09-23 19:31:28 +020055#include "rspro_util.h"
Harald Welte77911b02018-08-14 23:47:30 +020056
Harald Welte00a96732019-03-11 17:18:02 +010057/* signal indicates to worker thread that its map has been deleted */
58#define SIGMAPDEL SIGRTMIN+1
59static void handle_sig_mapdel(int sig);
60
Harald Welte77911b02018-08-14 23:47:30 +020061__thread void *talloc_asn1_ctx;
Harald Weltef4b16f12019-03-09 20:58:17 +010062struct bankd *g_bankd;
Harald Welte77911b02018-08-14 23:47:30 +020063
64static void *worker_main(void *arg);
65
66/***********************************************************************
67* bankd core / main thread
68***********************************************************************/
69
Harald Welte43ab79f2018-10-03 23:34:21 +020070int asn_debug;
71
Harald Welte77911b02018-08-14 23:47:30 +020072static void bankd_init(struct bankd *bankd)
73{
Harald Weltef94b9ee2018-09-25 15:04:21 +020074 void *g_tall_ctx = talloc_named_const(NULL, 0, "global");
75 osmo_init_logging2(g_tall_ctx, &log_info);
76
Harald Welte43ab79f2018-10-03 23:34:21 +020077 asn_debug = 0;
78
Harald Welte77911b02018-08-14 23:47:30 +020079 /* intialize members of 'bankd' */
Harald Weltecbd18962019-03-03 19:02:38 +010080 bankd->slotmaps = slotmap_init(bankd);
Harald Welte77911b02018-08-14 23:47:30 +020081 INIT_LLIST_HEAD(&bankd->workers);
82 pthread_mutex_init(&bankd->workers_mutex, NULL);
Harald Welte45c948c2018-09-23 19:26:52 +020083
Harald Weltea0f39502019-03-09 20:59:34 +010084 /* set some defaults, overridden by commandline/config */
85 bankd->cfg.bank_id = 1;
86 bankd->cfg.num_slots = 8;
87
Harald Weltef1dd1622018-09-24 14:54:23 +020088 bankd->comp_id.type = ComponentType_remsimBankd;
89 OSMO_STRLCPY_ARRAY(bankd->comp_id.name, "fixme-name");
90 OSMO_STRLCPY_ARRAY(bankd->comp_id.software, "remsim-bankd");
91 OSMO_STRLCPY_ARRAY(bankd->comp_id.sw_version, PACKAGE_VERSION);
92 /* FIXME: other members of app_comp_id */
93
Harald Welte45c948c2018-09-23 19:26:52 +020094 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
95 * read once during bankd initialization, when the worker threads haven't
96 * started yet */
97 INIT_LLIST_HEAD(&bankd->pcsc_slot_names);
98 OSMO_ASSERT(bankd_pcsc_read_slotnames(bankd, "bankd_pcsc_slots.csv") == 0);
Harald Welte77911b02018-08-14 23:47:30 +020099}
100
101/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +0200102static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +0200103{
104 struct bankd_worker *worker;
105 int rc;
106
107 worker = talloc_zero(bankd, struct bankd_worker);
108 if (!worker)
109 return NULL;
110
111 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +0200112 worker->num = i;
Harald Welte77911b02018-08-14 23:47:30 +0200113
114 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
115
116 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
117 if (rc != 0) {
118 talloc_free(worker);
119 return NULL;
120 }
121
122 pthread_mutex_lock(&bankd->workers_mutex);
123 llist_add_tail(&worker->list, &bankd->workers);
124 pthread_mutex_unlock(&bankd->workers_mutex);
125
126 return worker;
127}
128
129static bool terminate = false;
130
Harald Welte454f5e22019-03-09 21:38:34 +0100131static void rspro2bank_slot(struct bank_slot *out, const BankSlot_t *in)
132{
133 out->bank_id = in->bankId;
134 out->slot_nr = in->slotNr;
135}
136
137static void rspro2client_slot(struct client_slot *out, const ClientSlot_t *in)
138{
139 out->client_id = in->clientId;
140 out->slot_nr = in->slotNr;
141}
142
Harald Welte707c85a2019-03-09 12:56:35 +0100143/* handle incoming messages from server */
144static int bankd_srvc_handle_rx(struct rspro_server_conn *srvc, const RsproPDU_t *pdu)
145{
Harald Welte454f5e22019-03-09 21:38:34 +0100146 const CreateMappingReq_t *creq = NULL;
147 const RemoveMappingReq_t *rreq = NULL;
148 struct slot_mapping *map;
149 struct bank_slot bs;
150 struct client_slot cs;
151 RsproPDU_t *resp;
152
153 LOGPFSM(srvc->fi, "Rx RSPRO %s\n", rspro_msgt_name(pdu));
Harald Welte707c85a2019-03-09 12:56:35 +0100154
155 switch (pdu->msg.present) {
156 case RsproPDUchoice_PR_connectBankRes:
157 /* Store 'identity' of server in srvc->peer_comp_id */
158 rspro_comp_id_retrieve(&srvc->peer_comp_id, &pdu->msg.choice.connectBankRes.identity);
159 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_CLIENT_CONN_RES, (void *) pdu);
160 break;
Harald Welte454f5e22019-03-09 21:38:34 +0100161 case RsproPDUchoice_PR_createMappingReq:
162 creq = &pdu->msg.choice.createMappingReq;
163 if (creq->bank.bankId != g_bankd->cfg.bank_id)
164 resp = rspro_gen_CreateMappingRes(ResultCode_illegalBankId);
165 else if (creq->bank.slotNr >= g_bankd->cfg.num_slots)
166 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
167 else {
168 rspro2bank_slot(&bs, &creq->bank);
169 rspro2client_slot(&cs, &creq->client);
170 /* Add a new mapping */
171 map = slotmap_add(g_bankd->slotmaps, &bs, &cs);
172 if (!map)
173 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
174 else
175 resp = rspro_gen_CreateMappingRes(ResultCode_ok);
176 }
177 server_conn_send_rspro(srvc, resp);
178 break;
179 case RsproPDUchoice_PR_removeMappingReq:
180 rreq = &pdu->msg.choice.removeMappingReq;
181 if (rreq->bank.bankId != g_bankd->cfg.bank_id)
182 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalBankId);
183 else if (rreq->bank.slotNr >= g_bankd->cfg.num_slots)
184 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalSlotId);
185 else {
186 rspro2bank_slot(&bs, &rreq->bank);
187 /* Remove a mapping */
188 map = slotmap_by_bank(g_bankd->slotmaps, &bs);
189 if (!map)
190 resp = rspro_gen_RemoveMappingRes(ResultCode_unknownSlotmap);
191 else {
Harald Welte454f5e22019-03-09 21:38:34 +0100192 slotmap_del(g_bankd->slotmaps, map);
193 resp = rspro_gen_RemoveMappingRes(ResultCode_ok);
Harald Welte00a96732019-03-11 17:18:02 +0100194
195 /* kill/reset the respective worker, if any! */
196 struct bankd_worker *worker;
197 pthread_mutex_lock(&g_bankd->workers_mutex);
198 llist_for_each_entry(worker, &g_bankd->workers, list) {
199 if (bs.bank_id == worker->slot.bank_id &&
200 bs.slot_nr == worker->slot.slot_nr) {
201 pthread_kill(worker->thread, SIGMAPDEL);
202 break;
203 }
204 }
205 pthread_mutex_unlock(&g_bankd->workers_mutex);
Harald Welte454f5e22019-03-09 21:38:34 +0100206 }
207 }
Harald Welte942f1ff2019-03-09 21:49:08 +0100208 server_conn_send_rspro(srvc, resp);
Harald Welte454f5e22019-03-09 21:38:34 +0100209 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100210 default:
211 fprintf(stderr, "Unknown/Unsupported RSPRO PDU type: %u\n", pdu->msg.present);
212 return -1;
213 }
214
215 return 0;
216}
217
Harald Welte00a96732019-03-11 17:18:02 +0100218
Harald Welte707c85a2019-03-09 12:56:35 +0100219void handle_options(int argc, char **argv)
220{
221}
222
Harald Welte77911b02018-08-14 23:47:30 +0200223int main(int argc, char **argv)
224{
Harald Weltef4b16f12019-03-09 20:58:17 +0100225 struct rspro_server_conn *srvc;
Harald Welte77911b02018-08-14 23:47:30 +0200226 int i, rc;
227
Harald Weltef4b16f12019-03-09 20:58:17 +0100228 g_bankd = talloc_zero(NULL, struct bankd);
229 OSMO_ASSERT(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200230
Harald Weltef4b16f12019-03-09 20:58:17 +0100231 bankd_init(g_bankd);
232
233 srvc = &g_bankd->srvc;
Harald Welte707c85a2019-03-09 12:56:35 +0100234 srvc->server_host = "localhost";
235 srvc->server_port = 9998;
236 srvc->handle_rx = bankd_srvc_handle_rx;
237 srvc->own_comp_id.type = ComponentType_remsimBankd;
238 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.name, "fixme-name");
239 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.software, "remsim-bankd");
240 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.sw_version, PACKAGE_VERSION);
241
242 handle_options(argc, argv);
243
Harald Welte00a96732019-03-11 17:18:02 +0100244 signal(SIGMAPDEL, handle_sig_mapdel);
245
Harald Welte707c85a2019-03-09 12:56:35 +0100246 /* Connection towards remsim-server */
Harald Weltef4b16f12019-03-09 20:58:17 +0100247 rc = server_conn_fsm_alloc(g_bankd, srvc);
Harald Welte707c85a2019-03-09 12:56:35 +0100248 if (rc < 0) {
249 fprintf(stderr, "Unable to create Server conn FSM: %s\n", strerror(errno));
250 exit(1);
251 }
252
253 /* create listening socket for inbound client connections */
Harald Welte12534e72018-08-15 23:37:29 +0200254 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 9999, OSMO_SOCK_F_BIND);
255 if (rc < 0)
256 exit(1);
Harald Weltef4b16f12019-03-09 20:58:17 +0100257 g_bankd->accept_fd = rc;
Harald Welte12534e72018-08-15 23:37:29 +0200258
Harald Weltea0f39502019-03-09 20:59:34 +0100259 /* create worker threads: One per reader/slot! */
260 for (i = 0; i < g_bankd->cfg.num_slots; i++) {
Harald Welte77911b02018-08-14 23:47:30 +0200261 struct bankd_worker *w;
Harald Weltef4b16f12019-03-09 20:58:17 +0100262 w = bankd_create_worker(g_bankd, i);
Harald Welte77911b02018-08-14 23:47:30 +0200263 if (!w)
264 exit(21);
265 }
266
267 while (1) {
268 if (terminate)
269 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100270 osmo_select_main(0);
Harald Welte77911b02018-08-14 23:47:30 +0200271 }
272
Harald Weltef4b16f12019-03-09 20:58:17 +0100273 talloc_free(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200274 exit(0);
275}
276
277
278
279/***********************************************************************
280 * bankd worker thread
281 ***********************************************************************/
282
Harald Welte00a96732019-03-11 17:18:02 +0100283static __thread struct bankd_worker *g_worker;
284
Harald Welte8d858292018-08-15 23:36:46 +0200285struct value_string worker_state_names[] = {
286 { BW_ST_INIT, "INIT" },
287 { BW_ST_ACCEPTING, "ACCEPTING" },
288 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
289 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200290 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200291 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
292 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
Harald Welte00a96732019-03-11 17:18:02 +0100293 { BW_ST_CONN_CLIENT_UNMAPPED, "CONN_CLIENT_UNMAPPED" },
Harald Welte8d858292018-08-15 23:36:46 +0200294 { 0, NULL }
295};
296
Harald Welteceb3e682018-08-16 14:47:11 +0200297#define LOGW(w, fmt, args...) \
298 printf("[%03u %s] %s:%u " fmt, (w)->num, get_value_string(worker_state_names, (w)->state), \
299 __FILE__, __LINE__, ## args)
300
Harald Welteaf614732018-08-17 22:10:05 +0200301#define PCSC_ERROR(w, rv, text) \
302if (rv != SCARD_S_SUCCESS) { \
303 LOGW((w), text ": %s (0x%lX)\n", pcsc_stringify_error(rv), rv); \
304 goto end; \
305} else { \
Harald Welte7b41d9c2018-10-03 23:15:10 +0200306 LOGW((w), ": OK\n"); \
Harald Welteaf614732018-08-17 22:10:05 +0200307}
308
Harald Welte8d858292018-08-15 23:36:46 +0200309static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
310{
311 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
312 worker->state = new_state;
Harald Welte150d6d62018-10-03 23:07:47 +0200313 worker->timeout = 0;
314}
315
316static void worker_set_state_timeout(struct bankd_worker *worker, enum bankd_worker_state new_state,
317 unsigned int timeout_secs)
318{
319 LOGW(worker, "Changing state to %s (timeout=%u)\n",
320 get_value_string(worker_state_names, new_state), timeout_secs);
321 worker->state = new_state;
322 worker->timeout = timeout_secs;
Harald Welte8d858292018-08-15 23:36:46 +0200323}
Harald Welte77911b02018-08-14 23:47:30 +0200324
Harald Welte00a96732019-03-11 17:18:02 +0100325/* signal handler for receiving SIGMAPDEL from main thread */
326static void handle_sig_mapdel(int sig)
327{
328 LOGW(g_worker, "SIGMAPDEL received: Main thread informs us our map is gone\n");
329 OSMO_ASSERT(sig == SIGMAPDEL);
330 worker_set_state(g_worker, BW_ST_CONN_CLIENT_UNMAPPED);
331}
332
Harald Welte77911b02018-08-14 23:47:30 +0200333static void worker_cleanup(void *arg)
334{
335 struct bankd_worker *worker = (struct bankd_worker *) arg;
336 struct bankd *bankd = worker->bankd;
337
338 /* FIXME: should we still do this? in the thread ?!? */
339 pthread_mutex_lock(&bankd->workers_mutex);
340 llist_del(&worker->list);
341 talloc_free(worker); /* FIXME: is this safe? */
342 pthread_mutex_unlock(&bankd->workers_mutex);
343}
344
345
Harald Welteaf614732018-08-17 22:10:05 +0200346static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200347{
Harald Welteaf614732018-08-17 22:10:05 +0200348 long rc;
Harald Welte77911b02018-08-14 23:47:30 +0200349
Harald Welte150d6d62018-10-03 23:07:47 +0200350 OSMO_ASSERT(worker->state == BW_ST_CONN_CLIENT_MAPPED);
351
Harald Welte694df832018-10-03 22:47:52 +0200352 if (!worker->reader.name) {
353 /* resolve PC/SC reader name from slot_id -> name map */
354 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
355 if (!worker->reader.name) {
356 LOGW(worker, "No PC/SC reader name configured for %u/%u, fix your config\n",
357 worker->slot.bank_id, worker->slot.slot_nr);
358 rc = -1;
359 goto end;
360 }
361 }
Harald Welte45c948c2018-09-23 19:26:52 +0200362 OSMO_ASSERT(worker->reader.name);
363
Harald Welte694df832018-10-03 22:47:52 +0200364 if (!worker->reader.pcsc.hContext) {
365 LOGW(worker, "Attempting to open PC/SC context\n");
366 /* The PC/SC context must be created inside the thread where we'll later use it */
367 rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &worker->reader.pcsc.hContext);
368 PCSC_ERROR(worker, rc, "SCardEstablishContext")
369 }
Harald Welte45c948c2018-09-23 19:26:52 +0200370
Harald Welte694df832018-10-03 22:47:52 +0200371 if (!worker->reader.pcsc.hCard) {
372 LOGW(worker, "Attempting to open card/slot '%s'\n", worker->reader.name);
373 DWORD dwActiveProtocol;
374 rc = SCardConnect(worker->reader.pcsc.hContext, worker->reader.name, SCARD_SHARE_SHARED,
375 SCARD_PROTOCOL_T0, &worker->reader.pcsc.hCard, &dwActiveProtocol);
376 PCSC_ERROR(worker, rc, "SCardConnect")
377 }
Harald Welte77911b02018-08-14 23:47:30 +0200378
Harald Welte57593f02018-09-23 19:30:31 +0200379 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
Harald Welte150d6d62018-10-03 23:07:47 +0200380 /* FIXME: notify client about this state change */
Harald Welte57593f02018-09-23 19:30:31 +0200381
Harald Welteaf614732018-08-17 22:10:05 +0200382 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200383end:
Harald Welteaf614732018-08-17 22:10:05 +0200384 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200385}
Harald Welte77911b02018-08-14 23:47:30 +0200386
387
Harald Welte00a96732019-03-11 17:18:02 +0100388static int blocking_ipa_read(struct bankd_worker *worker, uint8_t *buf, unsigned int buf_size)
Harald Welte77911b02018-08-14 23:47:30 +0200389{
390 struct ipaccess_head *hh;
391 uint16_t len;
392 int needed, rc;
393
394 if (buf_size < sizeof(*hh))
395 return -1;
396
397 hh = (struct ipaccess_head *) buf;
398
Harald Welte00a96732019-03-11 17:18:02 +0100399 /* we use 'recv' and not 'read' below, as 'recv' will always fail with -EINTR
400 * in case of a signal being received */
401
402restart_hdr:
403 /* 1) blocking recv from the socket (IPA header) */
404 rc = recv(worker->client.fd, buf, sizeof(*hh), 0);
405 if (rc == -1 && errno == EINTR) {
406 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
407 return -23;
408 goto restart_hdr;
409 } else if (rc < 0)
410 return rc;
411 else if (rc < sizeof(*hh))
Harald Welte77911b02018-08-14 23:47:30 +0200412 return -2;
413
414 len = ntohs(hh->len);
415 needed = len; //- sizeof(*hh);
416
Harald Welte00a96732019-03-11 17:18:02 +0100417restart_body:
418 /* 2) blocking recv from the socket (payload) */
419 rc = recv(worker->client.fd, buf+sizeof(*hh), needed, 0);
420 if (rc == -1 && errno == EINTR) {
421 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
422 return -23;
423 goto restart_body;
424 } else if (rc < 0)
425 return rc;
426 else if (rc < needed)
Harald Welte77911b02018-08-14 23:47:30 +0200427 return -3;
428
429 return len;
430}
431
Harald Welte796a7492018-09-23 19:31:28 +0200432static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
433{
434 struct msgb *msg = rspro_enc_msg(pdu);
435 int rc;
436
437 if (!msg) {
438 LOGW(worker, "error encoding RSPRO\n");
439 return -1;
440 }
441
Harald Weltefd471192018-09-24 14:51:14 +0200442 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200443 /* prepend the header */
444 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200445 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200446
447 /* actually send it through the socket */
448 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
449 if (rc == msgb_length(msg))
450 rc = 0;
451 else {
452 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
453 rc = -1;
454 }
455
456 msgb_free(msg);
457
458 return rc;
459}
460
Harald Welte150d6d62018-10-03 23:07:47 +0200461/* attempt to obtain slot-map */
462static int worker_try_slotmap(struct bankd_worker *worker)
463{
Harald Weltecbd18962019-03-03 19:02:38 +0100464 struct slot_mapping *slmap;
Harald Welte150d6d62018-10-03 23:07:47 +0200465
Harald Weltecbd18962019-03-03 19:02:38 +0100466 slmap = slotmap_by_client(worker->bankd->slotmaps, &worker->client.clslot);
Harald Welte150d6d62018-10-03 23:07:47 +0200467 if (!slmap) {
468 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
469 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
470 /* check in 10s if the map has been installed meanwhile by main thread */
471 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_WAIT_MAP, 10);
472 return -1;
473 } else {
474 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
475 slmap->client.client_id, slmap->client.slot_nr,
476 slmap->bank.bank_id, slmap->bank.slot_nr);
477 worker->slot = slmap->bank;
478 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_MAPPED, 10);
479 return worker_open_card(worker);
480 }
481}
482
483
Harald Weltecce2aad2018-08-16 14:44:37 +0200484static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
485{
Harald Welteaf614732018-08-17 22:10:05 +0200486 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
Harald Welte458e01b2019-03-10 11:14:43 +0100487 RsproPDU_t *resp = NULL;
Harald Welte3e689872018-09-24 14:52:56 +0200488 e_ResultCode res;
Harald Welte458e01b2019-03-10 11:14:43 +0100489 int rc;
Harald Welteaf614732018-08-17 22:10:05 +0200490
Harald Weltecce2aad2018-08-16 14:44:37 +0200491 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
492
Harald Weltecce2aad2018-08-16 14:44:37 +0200493 LOGW(worker, "connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
494 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
495 /* FIXME: store somewhere? */
496
497 if (worker->state != BW_ST_CONN_WAIT_ID) {
498 LOGW(worker, "Unexpected connectClientReq\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100499 rc = -102;
500 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200501 }
502
Harald Welte371d0262018-08-16 15:23:58 +0200503 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200504 LOGW(worker, "missing clientID, aborting\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100505 res = ResultCode_illegalClientId;
506 rc = -103;
507 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200508 }
Harald Welte371d0262018-08-16 15:23:58 +0200509 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
510 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200511 worker_set_state(worker, BW_ST_CONN_CLIENT);
512
Harald Welte150d6d62018-10-03 23:07:47 +0200513 if (worker_try_slotmap(worker) >= 0)
514 res = ResultCode_ok;
515 else
Harald Welte3e689872018-09-24 14:52:56 +0200516 res = ResultCode_cardNotPresent;
Harald Weltecce2aad2018-08-16 14:44:37 +0200517
Harald Welte3e689872018-09-24 14:52:56 +0200518 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
519 return worker_send_rspro(worker, resp);
Harald Welte458e01b2019-03-10 11:14:43 +0100520
521respond_and_err:
522 if (res) {
523 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
524 worker_send_rspro(worker, resp);
525 }
526 return rc;
Harald Weltecce2aad2018-08-16 14:44:37 +0200527}
528
Harald Welte796a7492018-09-23 19:31:28 +0200529static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
530{
531 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
532 const SCARD_IO_REQUEST *pioSendPci = SCARD_PCI_T0;
533 SCARD_IO_REQUEST pioRecvPci;
534 uint8_t rx_buf[1024];
535 DWORD rx_buf_len = sizeof(rx_buf);
536 RsproPDU_t *pdu_resp;
537 long rc;
538
539 LOGW(worker, "tpduModemToCard(%s)\n", osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
540
541 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
542 LOGW(worker, "Unexpected tpduModemToCaard\n");
543 return -104;
544 }
545
546 /* FIXME: Validate that toBankSlot / fromClientSlot match our expectations */
547
548 rc = SCardTransmit(worker->reader.pcsc.hCard,
549 pioSendPci, mdm2sim->data.buf, mdm2sim->data.size,
550 &pioRecvPci, rx_buf, &rx_buf_len);
551 PCSC_ERROR(worker, rc, "SCardTransmit");
552
553 /* encode response PDU and send it */
554 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
555 rx_buf, rx_buf_len);
556 worker_send_rspro(worker, pdu_resp);
557
558 return 0;
559end:
560 return rc;
561}
562
Harald Welte77911b02018-08-14 23:47:30 +0200563/* handle one incoming RSPRO message from a client inside a worker thread */
564static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
565{
Harald Weltecce2aad2018-08-16 14:44:37 +0200566 int rc = -100;
567
Harald Welte77911b02018-08-14 23:47:30 +0200568 switch (pdu->msg.present) {
569 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200570 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200571 break;
572 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200573 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200574 break;
575 case RsproPDUchoice_PR_clientSlotStatusInd:
576 /* FIXME */
577 break;
578 default:
Harald Weltecce2aad2018-08-16 14:44:37 +0200579 rc = -101;
580 break;
Harald Welte77911b02018-08-14 23:47:30 +0200581 }
582
Harald Weltecce2aad2018-08-16 14:44:37 +0200583 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200584}
585
Harald Welte694df832018-10-03 22:47:52 +0200586static int wait_for_fd_or_timeout(int fd, unsigned int timeout_secs)
587{
588 struct timeval tout = { timeout_secs, 0 };
589 fd_set readset;
590
591 FD_ZERO(&readset);
592 FD_SET(fd, &readset);
593 return select(fd + 1, &readset, NULL, NULL, timeout_secs ? &tout : NULL);
594}
595
Harald Welte77911b02018-08-14 23:47:30 +0200596/* body of the main transceive loop */
597static int worker_transceive_loop(struct bankd_worker *worker)
598{
599 struct ipaccess_head *hh;
600 struct ipaccess_head_ext *hh_ext;
601 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
602 asn_dec_rval_t rval;
603 int data_len, rc;
Harald Welte9ebbacc2018-09-24 17:43:39 +0200604 RsproPDU_t *pdu = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200605
Harald Welte00a96732019-03-11 17:18:02 +0100606restart_wait:
Harald Welte694df832018-10-03 22:47:52 +0200607 rc = wait_for_fd_or_timeout(worker->client.fd, worker->timeout);
Harald Welte00a96732019-03-11 17:18:02 +0100608 if (rc == -1 && errno == EINTR) {
609 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
610 return -23;
611 goto restart_wait;
612 } else if (rc < 0)
613 return rc;
614 else if (rc == 0) {
Harald Welte694df832018-10-03 22:47:52 +0200615 /* TIMEOUT case */
Harald Welte150d6d62018-10-03 23:07:47 +0200616 switch (worker->state) {
617 case BW_ST_CONN_CLIENT_WAIT_MAP:
618 /* re-check if mapping exists meanwhile? */
619 worker_try_slotmap(worker);
620 break;
621 case BW_ST_CONN_CLIENT_MAPPED:
622 /* re-check if reader/card can be opened meanwhile? */
623 worker_open_card(worker);
624 break;
625 default:
626 OSMO_ASSERT(0);
627 }
628 /* return early, so we do another select rather than the blocking read below */
Harald Welte694df832018-10-03 22:47:52 +0200629 return 0;
630 };
631
Harald Welte77911b02018-08-14 23:47:30 +0200632 /* 1) blocking read of entire IPA message from the socket */
Harald Welte00a96732019-03-11 17:18:02 +0100633 rc = blocking_ipa_read(worker, buf, sizeof(buf));
Harald Welte77911b02018-08-14 23:47:30 +0200634 if (rc < 0)
635 return rc;
636 data_len = rc;
637
638 hh = (struct ipaccess_head *) buf;
Harald Welte5a3613a2018-10-11 12:56:21 +0200639 if (hh->proto != IPAC_PROTO_OSMO && hh->proto != IPAC_PROTO_IPACCESS) {
Harald Weltee1176cf2018-09-24 14:54:58 +0200640 LOGW(worker, "Received unsupported IPA protocol != OSMO: 0x%02x\n", hh->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200641 return -4;
Harald Weltee1176cf2018-09-24 14:54:58 +0200642 }
Harald Welte77911b02018-08-14 23:47:30 +0200643
Harald Welte5a3613a2018-10-11 12:56:21 +0200644 if (hh->proto == IPAC_PROTO_IPACCESS) {
645 LOGW(worker, "IPA CCM not implemented yet\n");
646 return 0;
647 }
648
Harald Welte77911b02018-08-14 23:47:30 +0200649 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
Harald Weltee1176cf2018-09-24 14:54:58 +0200650 if (data_len < sizeof(*hh_ext)) {
651 LOGW(worker, "Received short message\n");
Harald Welte77911b02018-08-14 23:47:30 +0200652 return -5;
Harald Weltee1176cf2018-09-24 14:54:58 +0200653 }
Harald Welte77911b02018-08-14 23:47:30 +0200654 data_len -= sizeof(*hh_ext);
Harald Weltee1176cf2018-09-24 14:54:58 +0200655 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO) {
656 LOGW(worker, "Received unsupported IPA EXT protocol != RSPRO: 0x%02x\n", hh_ext->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200657 return -6;
Harald Weltee1176cf2018-09-24 14:54:58 +0200658 }
Harald Welte77911b02018-08-14 23:47:30 +0200659
660 /* 2) ASN1 BER decode of the message */
661 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
Harald Weltee1176cf2018-09-24 14:54:58 +0200662 if (rval.code != RC_OK) {
663 LOGW(worker, "Error during BER decode of RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200664 return -7;
Harald Weltee1176cf2018-09-24 14:54:58 +0200665 }
Harald Welte77911b02018-08-14 23:47:30 +0200666
667 /* 3) handling of the message, possibly resulting in PCSC commands */
668 rc = worker_handle_rspro(worker, pdu);
669 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Weltee1176cf2018-09-24 14:54:58 +0200670 if (rc < 0) {
671 LOGW(worker, "Error handling RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200672 return rc;
Harald Weltee1176cf2018-09-24 14:54:58 +0200673 }
Harald Welte77911b02018-08-14 23:47:30 +0200674
675 /* everything OK if we reach here */
676 return 0;
677}
678
Harald Welted6dfb8c2018-08-16 14:46:53 +0200679/* obtain an ascii representation of the client IP/port */
680static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
681{
682 char hostbuf[32], portbuf[32];
683 int rc;
684
685 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
686 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
687 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
688 if (rc != 0) {
689 out[0] = '\0';
690 return -1;
691 }
692 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
693 return 0;
694}
695
Harald Welte77911b02018-08-14 23:47:30 +0200696/* worker thread main function */
697static void *worker_main(void *arg)
698{
Harald Welte77911b02018-08-14 23:47:30 +0200699 void *top_ctx;
700 int rc;
Harald Welte31c9eca2018-10-03 21:03:34 +0200701 char worker_name[32];
702
Harald Welte00a96732019-03-11 17:18:02 +0100703 g_worker = (struct bankd_worker *) arg;
704
Harald Welte31c9eca2018-10-03 21:03:34 +0200705 /* set the thread name */
Harald Welte00a96732019-03-11 17:18:02 +0100706 snprintf(worker_name, sizeof(worker_name), "bankd-worker(%u)", g_worker->num);
Harald Welte31c9eca2018-10-03 21:03:34 +0200707 pthread_setname_np(pthread_self(), worker_name);
Harald Welte77911b02018-08-14 23:47:30 +0200708
Harald Welte00a96732019-03-11 17:18:02 +0100709 worker_set_state(g_worker, BW_ST_INIT);
Harald Welte8d858292018-08-15 23:36:46 +0200710
Harald Welte77911b02018-08-14 23:47:30 +0200711 /* not permitted in multithreaded environment */
712 talloc_disable_null_tracking();
713 top_ctx = talloc_named_const(NULL, 0, "top");
714 talloc_asn1_ctx = talloc_named_const(top_ctx, 0, "asn1");
715
716 /* push cleanup helper */
Harald Welte00a96732019-03-11 17:18:02 +0100717 pthread_cleanup_push(&worker_cleanup, g_worker);
Harald Welte77911b02018-08-14 23:47:30 +0200718
719 /* we continuously perform the same loop here, recycling the worker thread
720 * once the client connection is gone or we have some trouble with the card/reader */
721 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +0200722 char buf[128];
723
Harald Welte00a96732019-03-11 17:18:02 +0100724 g_worker->client.peer_addr_len = sizeof(g_worker->client.peer_addr);
Harald Welte77911b02018-08-14 23:47:30 +0200725
Harald Welte00a96732019-03-11 17:18:02 +0100726 worker_set_state(g_worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +0200727 /* first wait for an incoming TCP connection */
Harald Welte00a96732019-03-11 17:18:02 +0100728 rc = accept(g_worker->bankd->accept_fd, (struct sockaddr *) &g_worker->client.peer_addr,
729 &g_worker->client.peer_addr_len);
Harald Welte77911b02018-08-14 23:47:30 +0200730 if (rc < 0) {
731 continue;
732 }
Harald Welte00a96732019-03-11 17:18:02 +0100733 g_worker->client.fd = rc;
734 worker_client_addrstr(buf, sizeof(buf), g_worker);
735 LOGW(g_worker, "Accepted connection from %s\n", buf);
736 worker_set_state(g_worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +0200737
738 /* run the main worker transceive loop body until there was some error */
739 while (1) {
Harald Welte00a96732019-03-11 17:18:02 +0100740 rc = worker_transceive_loop(g_worker);
Harald Welte77911b02018-08-14 23:47:30 +0200741 if (rc < 0)
742 break;
743 }
744
Harald Welte00a96732019-03-11 17:18:02 +0100745 LOGW(g_worker, "Error %d occurred: Cleaning up state\n", rc);
Harald Welted6dfb8c2018-08-16 14:46:53 +0200746
Harald Welte77911b02018-08-14 23:47:30 +0200747 /* clean-up: reset to sane state */
Harald Welte00a96732019-03-11 17:18:02 +0100748 if (g_worker->reader.pcsc.hCard) {
749 SCardDisconnect(g_worker->reader.pcsc.hCard, SCARD_UNPOWER_CARD);
750 g_worker->reader.pcsc.hCard = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200751 }
Harald Welte00a96732019-03-11 17:18:02 +0100752 if (g_worker->reader.pcsc.hContext) {
753 SCardReleaseContext(g_worker->reader.pcsc.hContext);
754 g_worker->reader.pcsc.hContext = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200755 }
Harald Welte00a96732019-03-11 17:18:02 +0100756 if (g_worker->reader.name)
757 g_worker->reader.name = NULL;
758 if (g_worker->client.fd >= 0)
759 close(g_worker->client.fd);
760 memset(&g_worker->client.peer_addr, 0, sizeof(g_worker->client.peer_addr));
761 g_worker->client.fd = -1;
762 g_worker->client.clslot.client_id = g_worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200763 }
764
765 pthread_cleanup_pop(1);
766 talloc_free(top_ctx);
767 pthread_exit(NULL);
768}