blob: 3a65629ab0aee46e9632d7ff6534dd64f6c3e217 [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
Harald Welte25075972019-03-11 17:33:17 +010059
60static void handle_sig_usr1(int sig);
Harald Welte00a96732019-03-11 17:18:02 +010061static void handle_sig_mapdel(int sig);
62
Harald Welte77911b02018-08-14 23:47:30 +020063__thread void *talloc_asn1_ctx;
Harald Weltef4b16f12019-03-09 20:58:17 +010064struct bankd *g_bankd;
Harald Welte25075972019-03-11 17:33:17 +010065static void *g_tall_ctx;
Harald Welte77911b02018-08-14 23:47:30 +020066
67static void *worker_main(void *arg);
68
69/***********************************************************************
70* bankd core / main thread
71***********************************************************************/
72
Harald Welte43ab79f2018-10-03 23:34:21 +020073int asn_debug;
74
Harald Welte77911b02018-08-14 23:47:30 +020075static void bankd_init(struct bankd *bankd)
76{
Harald Welte25075972019-03-11 17:33:17 +010077 g_tall_ctx = talloc_named_const(NULL, 0, "global");
Harald Weltef94b9ee2018-09-25 15:04:21 +020078 osmo_init_logging2(g_tall_ctx, &log_info);
79
Harald Welte43ab79f2018-10-03 23:34:21 +020080 asn_debug = 0;
81
Harald Welte77911b02018-08-14 23:47:30 +020082 /* intialize members of 'bankd' */
Harald Weltecbd18962019-03-03 19:02:38 +010083 bankd->slotmaps = slotmap_init(bankd);
Harald Welte77911b02018-08-14 23:47:30 +020084 INIT_LLIST_HEAD(&bankd->workers);
85 pthread_mutex_init(&bankd->workers_mutex, NULL);
Harald Welte45c948c2018-09-23 19:26:52 +020086
Harald Weltea0f39502019-03-09 20:59:34 +010087 /* set some defaults, overridden by commandline/config */
88 bankd->cfg.bank_id = 1;
89 bankd->cfg.num_slots = 8;
90
Harald Weltef1dd1622018-09-24 14:54:23 +020091 bankd->comp_id.type = ComponentType_remsimBankd;
92 OSMO_STRLCPY_ARRAY(bankd->comp_id.name, "fixme-name");
93 OSMO_STRLCPY_ARRAY(bankd->comp_id.software, "remsim-bankd");
94 OSMO_STRLCPY_ARRAY(bankd->comp_id.sw_version, PACKAGE_VERSION);
95 /* FIXME: other members of app_comp_id */
96
Harald Welte45c948c2018-09-23 19:26:52 +020097 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
98 * read once during bankd initialization, when the worker threads haven't
99 * started yet */
100 INIT_LLIST_HEAD(&bankd->pcsc_slot_names);
101 OSMO_ASSERT(bankd_pcsc_read_slotnames(bankd, "bankd_pcsc_slots.csv") == 0);
Harald Welte77911b02018-08-14 23:47:30 +0200102}
103
104/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +0200105static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +0200106{
107 struct bankd_worker *worker;
108 int rc;
109
110 worker = talloc_zero(bankd, struct bankd_worker);
111 if (!worker)
112 return NULL;
113
114 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +0200115 worker->num = i;
Harald Welte77911b02018-08-14 23:47:30 +0200116
117 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
118
119 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
120 if (rc != 0) {
121 talloc_free(worker);
122 return NULL;
123 }
124
125 pthread_mutex_lock(&bankd->workers_mutex);
126 llist_add_tail(&worker->list, &bankd->workers);
127 pthread_mutex_unlock(&bankd->workers_mutex);
128
129 return worker;
130}
131
132static bool terminate = false;
133
Harald Welte707c85a2019-03-09 12:56:35 +0100134/* handle incoming messages from server */
135static int bankd_srvc_handle_rx(struct rspro_server_conn *srvc, const RsproPDU_t *pdu)
136{
Harald Welte454f5e22019-03-09 21:38:34 +0100137 const CreateMappingReq_t *creq = NULL;
138 const RemoveMappingReq_t *rreq = NULL;
139 struct slot_mapping *map;
140 struct bank_slot bs;
141 struct client_slot cs;
142 RsproPDU_t *resp;
143
144 LOGPFSM(srvc->fi, "Rx RSPRO %s\n", rspro_msgt_name(pdu));
Harald Welte707c85a2019-03-09 12:56:35 +0100145
146 switch (pdu->msg.present) {
147 case RsproPDUchoice_PR_connectBankRes:
148 /* Store 'identity' of server in srvc->peer_comp_id */
149 rspro_comp_id_retrieve(&srvc->peer_comp_id, &pdu->msg.choice.connectBankRes.identity);
150 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_CLIENT_CONN_RES, (void *) pdu);
151 break;
Harald Welte454f5e22019-03-09 21:38:34 +0100152 case RsproPDUchoice_PR_createMappingReq:
153 creq = &pdu->msg.choice.createMappingReq;
154 if (creq->bank.bankId != g_bankd->cfg.bank_id)
155 resp = rspro_gen_CreateMappingRes(ResultCode_illegalBankId);
156 else if (creq->bank.slotNr >= g_bankd->cfg.num_slots)
157 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
158 else {
159 rspro2bank_slot(&bs, &creq->bank);
160 rspro2client_slot(&cs, &creq->client);
161 /* Add a new mapping */
162 map = slotmap_add(g_bankd->slotmaps, &bs, &cs);
163 if (!map)
164 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
165 else
166 resp = rspro_gen_CreateMappingRes(ResultCode_ok);
167 }
168 server_conn_send_rspro(srvc, resp);
169 break;
170 case RsproPDUchoice_PR_removeMappingReq:
171 rreq = &pdu->msg.choice.removeMappingReq;
172 if (rreq->bank.bankId != g_bankd->cfg.bank_id)
173 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalBankId);
174 else if (rreq->bank.slotNr >= g_bankd->cfg.num_slots)
175 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalSlotId);
176 else {
177 rspro2bank_slot(&bs, &rreq->bank);
178 /* Remove a mapping */
179 map = slotmap_by_bank(g_bankd->slotmaps, &bs);
180 if (!map)
181 resp = rspro_gen_RemoveMappingRes(ResultCode_unknownSlotmap);
182 else {
Harald Welte454f5e22019-03-09 21:38:34 +0100183 slotmap_del(g_bankd->slotmaps, map);
184 resp = rspro_gen_RemoveMappingRes(ResultCode_ok);
Harald Welte00a96732019-03-11 17:18:02 +0100185
186 /* kill/reset the respective worker, if any! */
187 struct bankd_worker *worker;
188 pthread_mutex_lock(&g_bankd->workers_mutex);
189 llist_for_each_entry(worker, &g_bankd->workers, list) {
190 if (bs.bank_id == worker->slot.bank_id &&
191 bs.slot_nr == worker->slot.slot_nr) {
192 pthread_kill(worker->thread, SIGMAPDEL);
193 break;
194 }
195 }
196 pthread_mutex_unlock(&g_bankd->workers_mutex);
Harald Welte454f5e22019-03-09 21:38:34 +0100197 }
198 }
Harald Welte942f1ff2019-03-09 21:49:08 +0100199 server_conn_send_rspro(srvc, resp);
Harald Welte454f5e22019-03-09 21:38:34 +0100200 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100201 default:
Harald Welteeb971b52019-03-27 22:41:45 +0100202 LOGPFSML(srvc->fi, LOGL_ERROR, "Unknown/Unsupported RSPRO PDU type: %u\n",
203 pdu->msg.present);
Harald Welte707c85a2019-03-09 12:56:35 +0100204 return -1;
205 }
206
207 return 0;
208}
209
Harald Welte00a96732019-03-11 17:18:02 +0100210
Harald Welte707c85a2019-03-09 12:56:35 +0100211void handle_options(int argc, char **argv)
212{
213}
214
Harald Welte77911b02018-08-14 23:47:30 +0200215int main(int argc, char **argv)
216{
Harald Weltef4b16f12019-03-09 20:58:17 +0100217 struct rspro_server_conn *srvc;
Harald Welte77911b02018-08-14 23:47:30 +0200218 int i, rc;
219
Harald Weltef4b16f12019-03-09 20:58:17 +0100220 g_bankd = talloc_zero(NULL, struct bankd);
221 OSMO_ASSERT(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200222
Harald Weltef4b16f12019-03-09 20:58:17 +0100223 bankd_init(g_bankd);
224
225 srvc = &g_bankd->srvc;
Harald Welte707c85a2019-03-09 12:56:35 +0100226 srvc->server_host = "localhost";
227 srvc->server_port = 9998;
228 srvc->handle_rx = bankd_srvc_handle_rx;
229 srvc->own_comp_id.type = ComponentType_remsimBankd;
230 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.name, "fixme-name");
231 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.software, "remsim-bankd");
232 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.sw_version, PACKAGE_VERSION);
233
234 handle_options(argc, argv);
235
Harald Welte25075972019-03-11 17:33:17 +0100236 g_bankd->main = pthread_self();
Harald Welte00a96732019-03-11 17:18:02 +0100237 signal(SIGMAPDEL, handle_sig_mapdel);
Harald Welte25075972019-03-11 17:33:17 +0100238 signal(SIGUSR1, handle_sig_usr1);
Harald Welte00a96732019-03-11 17:18:02 +0100239
Harald Welte707c85a2019-03-09 12:56:35 +0100240 /* Connection towards remsim-server */
Harald Weltef4b16f12019-03-09 20:58:17 +0100241 rc = server_conn_fsm_alloc(g_bankd, srvc);
Harald Welte707c85a2019-03-09 12:56:35 +0100242 if (rc < 0) {
243 fprintf(stderr, "Unable to create Server conn FSM: %s\n", strerror(errno));
244 exit(1);
245 }
246
247 /* create listening socket for inbound client connections */
Harald Welte12534e72018-08-15 23:37:29 +0200248 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 9999, OSMO_SOCK_F_BIND);
249 if (rc < 0)
250 exit(1);
Harald Weltef4b16f12019-03-09 20:58:17 +0100251 g_bankd->accept_fd = rc;
Harald Welte12534e72018-08-15 23:37:29 +0200252
Harald Weltea0f39502019-03-09 20:59:34 +0100253 /* create worker threads: One per reader/slot! */
254 for (i = 0; i < g_bankd->cfg.num_slots; i++) {
Harald Welte77911b02018-08-14 23:47:30 +0200255 struct bankd_worker *w;
Harald Weltef4b16f12019-03-09 20:58:17 +0100256 w = bankd_create_worker(g_bankd, i);
Harald Welte77911b02018-08-14 23:47:30 +0200257 if (!w)
258 exit(21);
259 }
260
261 while (1) {
262 if (terminate)
263 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100264 osmo_select_main(0);
Harald Welte77911b02018-08-14 23:47:30 +0200265 }
266
Harald Weltef4b16f12019-03-09 20:58:17 +0100267 talloc_free(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200268 exit(0);
269}
270
271
272
273/***********************************************************************
274 * bankd worker thread
275 ***********************************************************************/
276
Harald Welte00a96732019-03-11 17:18:02 +0100277static __thread struct bankd_worker *g_worker;
278
Harald Welte8d858292018-08-15 23:36:46 +0200279struct value_string worker_state_names[] = {
280 { BW_ST_INIT, "INIT" },
281 { BW_ST_ACCEPTING, "ACCEPTING" },
282 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
283 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200284 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200285 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
286 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
Harald Welte00a96732019-03-11 17:18:02 +0100287 { BW_ST_CONN_CLIENT_UNMAPPED, "CONN_CLIENT_UNMAPPED" },
Harald Welte8d858292018-08-15 23:36:46 +0200288 { 0, NULL }
289};
290
Harald Welteceb3e682018-08-16 14:47:11 +0200291#define LOGW(w, fmt, args...) \
292 printf("[%03u %s] %s:%u " fmt, (w)->num, get_value_string(worker_state_names, (w)->state), \
293 __FILE__, __LINE__, ## args)
294
Harald Welteaf614732018-08-17 22:10:05 +0200295#define PCSC_ERROR(w, rv, text) \
296if (rv != SCARD_S_SUCCESS) { \
297 LOGW((w), text ": %s (0x%lX)\n", pcsc_stringify_error(rv), rv); \
298 goto end; \
299} else { \
Harald Welte7b41d9c2018-10-03 23:15:10 +0200300 LOGW((w), ": OK\n"); \
Harald Welteaf614732018-08-17 22:10:05 +0200301}
302
Harald Welte8d858292018-08-15 23:36:46 +0200303static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
304{
305 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
306 worker->state = new_state;
Harald Welte150d6d62018-10-03 23:07:47 +0200307 worker->timeout = 0;
308}
309
310static void worker_set_state_timeout(struct bankd_worker *worker, enum bankd_worker_state new_state,
311 unsigned int timeout_secs)
312{
313 LOGW(worker, "Changing state to %s (timeout=%u)\n",
314 get_value_string(worker_state_names, new_state), timeout_secs);
315 worker->state = new_state;
316 worker->timeout = timeout_secs;
Harald Welte8d858292018-08-15 23:36:46 +0200317}
Harald Welte77911b02018-08-14 23:47:30 +0200318
Harald Welte00a96732019-03-11 17:18:02 +0100319/* signal handler for receiving SIGMAPDEL from main thread */
320static void handle_sig_mapdel(int sig)
321{
322 LOGW(g_worker, "SIGMAPDEL received: Main thread informs us our map is gone\n");
323 OSMO_ASSERT(sig == SIGMAPDEL);
324 worker_set_state(g_worker, BW_ST_CONN_CLIENT_UNMAPPED);
325}
326
Harald Welte25075972019-03-11 17:33:17 +0100327static void handle_sig_usr1(int sig)
328{
329 OSMO_ASSERT(sig == SIGUSR1);
330
331 if (pthread_equal(g_bankd->main, pthread_self())) {
332 struct bankd_worker *worker;
333 /* main thread */
334 fprintf(stderr, "=== Talloc Report of main thread:\n");
335 talloc_report(g_tall_ctx, stderr);
336
337 /* iterate over worker threads and ask them to dump their talloc state */
338 pthread_mutex_lock(&g_bankd->workers_mutex);
339 llist_for_each_entry(worker, &g_bankd->workers, list) {
340 pthread_kill(worker->thread, SIGUSR1);
341 }
342 pthread_mutex_unlock(&g_bankd->workers_mutex);
343 } else {
344 /* worker thread */
345 fprintf(stderr, "=== Talloc Report of %s\n", g_worker->name);
346 talloc_report(g_worker->tall_ctx, stderr);
347 }
348}
349
Harald Welte77911b02018-08-14 23:47:30 +0200350static void worker_cleanup(void *arg)
351{
352 struct bankd_worker *worker = (struct bankd_worker *) arg;
353 struct bankd *bankd = worker->bankd;
354
355 /* FIXME: should we still do this? in the thread ?!? */
356 pthread_mutex_lock(&bankd->workers_mutex);
357 llist_del(&worker->list);
358 talloc_free(worker); /* FIXME: is this safe? */
359 pthread_mutex_unlock(&bankd->workers_mutex);
360}
361
362
Harald Welteaf614732018-08-17 22:10:05 +0200363static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200364{
Harald Welteaf614732018-08-17 22:10:05 +0200365 long rc;
Harald Welte77911b02018-08-14 23:47:30 +0200366
Harald Welte150d6d62018-10-03 23:07:47 +0200367 OSMO_ASSERT(worker->state == BW_ST_CONN_CLIENT_MAPPED);
368
Harald Welte694df832018-10-03 22:47:52 +0200369 if (!worker->reader.name) {
370 /* resolve PC/SC reader name from slot_id -> name map */
371 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
372 if (!worker->reader.name) {
373 LOGW(worker, "No PC/SC reader name configured for %u/%u, fix your config\n",
374 worker->slot.bank_id, worker->slot.slot_nr);
375 rc = -1;
376 goto end;
377 }
378 }
Harald Welte45c948c2018-09-23 19:26:52 +0200379 OSMO_ASSERT(worker->reader.name);
380
Harald Welte694df832018-10-03 22:47:52 +0200381 if (!worker->reader.pcsc.hContext) {
382 LOGW(worker, "Attempting to open PC/SC context\n");
383 /* The PC/SC context must be created inside the thread where we'll later use it */
384 rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &worker->reader.pcsc.hContext);
385 PCSC_ERROR(worker, rc, "SCardEstablishContext")
386 }
Harald Welte45c948c2018-09-23 19:26:52 +0200387
Harald Welte694df832018-10-03 22:47:52 +0200388 if (!worker->reader.pcsc.hCard) {
389 LOGW(worker, "Attempting to open card/slot '%s'\n", worker->reader.name);
390 DWORD dwActiveProtocol;
391 rc = SCardConnect(worker->reader.pcsc.hContext, worker->reader.name, SCARD_SHARE_SHARED,
392 SCARD_PROTOCOL_T0, &worker->reader.pcsc.hCard, &dwActiveProtocol);
393 PCSC_ERROR(worker, rc, "SCardConnect")
394 }
Harald Welte77911b02018-08-14 23:47:30 +0200395
Harald Welte57593f02018-09-23 19:30:31 +0200396 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
Harald Welte150d6d62018-10-03 23:07:47 +0200397 /* FIXME: notify client about this state change */
Harald Welte57593f02018-09-23 19:30:31 +0200398
Harald Welteaf614732018-08-17 22:10:05 +0200399 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200400end:
Harald Welteaf614732018-08-17 22:10:05 +0200401 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200402}
Harald Welte77911b02018-08-14 23:47:30 +0200403
404
Harald Welte00a96732019-03-11 17:18:02 +0100405static int blocking_ipa_read(struct bankd_worker *worker, uint8_t *buf, unsigned int buf_size)
Harald Welte77911b02018-08-14 23:47:30 +0200406{
407 struct ipaccess_head *hh;
408 uint16_t len;
409 int needed, rc;
410
411 if (buf_size < sizeof(*hh))
412 return -1;
413
414 hh = (struct ipaccess_head *) buf;
415
Harald Welte00a96732019-03-11 17:18:02 +0100416 /* we use 'recv' and not 'read' below, as 'recv' will always fail with -EINTR
417 * in case of a signal being received */
418
419restart_hdr:
420 /* 1) blocking recv from the socket (IPA header) */
421 rc = recv(worker->client.fd, buf, sizeof(*hh), 0);
422 if (rc == -1 && errno == EINTR) {
423 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
424 return -23;
425 goto restart_hdr;
426 } else if (rc < 0)
427 return rc;
428 else if (rc < sizeof(*hh))
Harald Welte77911b02018-08-14 23:47:30 +0200429 return -2;
430
431 len = ntohs(hh->len);
432 needed = len; //- sizeof(*hh);
433
Harald Welte00a96732019-03-11 17:18:02 +0100434restart_body:
435 /* 2) blocking recv from the socket (payload) */
436 rc = recv(worker->client.fd, buf+sizeof(*hh), needed, 0);
437 if (rc == -1 && errno == EINTR) {
438 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
439 return -23;
440 goto restart_body;
441 } else if (rc < 0)
442 return rc;
443 else if (rc < needed)
Harald Welte77911b02018-08-14 23:47:30 +0200444 return -3;
445
446 return len;
447}
448
Harald Welte796a7492018-09-23 19:31:28 +0200449static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
450{
451 struct msgb *msg = rspro_enc_msg(pdu);
452 int rc;
453
454 if (!msg) {
455 LOGW(worker, "error encoding RSPRO\n");
456 return -1;
457 }
458
Harald Weltefd471192018-09-24 14:51:14 +0200459 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200460 /* prepend the header */
461 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200462 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200463
464 /* actually send it through the socket */
465 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
466 if (rc == msgb_length(msg))
467 rc = 0;
468 else {
469 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
470 rc = -1;
471 }
472
473 msgb_free(msg);
474
475 return rc;
476}
477
Harald Welte150d6d62018-10-03 23:07:47 +0200478/* attempt to obtain slot-map */
479static int worker_try_slotmap(struct bankd_worker *worker)
480{
Harald Weltecbd18962019-03-03 19:02:38 +0100481 struct slot_mapping *slmap;
Harald Welte150d6d62018-10-03 23:07:47 +0200482
Harald Weltecbd18962019-03-03 19:02:38 +0100483 slmap = slotmap_by_client(worker->bankd->slotmaps, &worker->client.clslot);
Harald Welte150d6d62018-10-03 23:07:47 +0200484 if (!slmap) {
485 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
486 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
487 /* check in 10s if the map has been installed meanwhile by main thread */
488 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_WAIT_MAP, 10);
489 return -1;
490 } else {
491 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
492 slmap->client.client_id, slmap->client.slot_nr,
493 slmap->bank.bank_id, slmap->bank.slot_nr);
494 worker->slot = slmap->bank;
495 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_MAPPED, 10);
496 return worker_open_card(worker);
497 }
498}
499
500
Harald Weltecce2aad2018-08-16 14:44:37 +0200501static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
502{
Harald Welteaf614732018-08-17 22:10:05 +0200503 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
Harald Welte458e01b2019-03-10 11:14:43 +0100504 RsproPDU_t *resp = NULL;
Harald Welte3e689872018-09-24 14:52:56 +0200505 e_ResultCode res;
Harald Welte458e01b2019-03-10 11:14:43 +0100506 int rc;
Harald Welteaf614732018-08-17 22:10:05 +0200507
Harald Weltecce2aad2018-08-16 14:44:37 +0200508 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
509
Harald Weltecce2aad2018-08-16 14:44:37 +0200510 LOGW(worker, "connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
511 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
512 /* FIXME: store somewhere? */
513
514 if (worker->state != BW_ST_CONN_WAIT_ID) {
515 LOGW(worker, "Unexpected connectClientReq\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100516 rc = -102;
517 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200518 }
519
Harald Welte371d0262018-08-16 15:23:58 +0200520 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200521 LOGW(worker, "missing clientID, aborting\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100522 res = ResultCode_illegalClientId;
523 rc = -103;
524 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200525 }
Harald Welte371d0262018-08-16 15:23:58 +0200526 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
527 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200528 worker_set_state(worker, BW_ST_CONN_CLIENT);
529
Harald Welte150d6d62018-10-03 23:07:47 +0200530 if (worker_try_slotmap(worker) >= 0)
531 res = ResultCode_ok;
532 else
Harald Welte3e689872018-09-24 14:52:56 +0200533 res = ResultCode_cardNotPresent;
Harald Weltecce2aad2018-08-16 14:44:37 +0200534
Harald Welte3e689872018-09-24 14:52:56 +0200535 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
536 return worker_send_rspro(worker, resp);
Harald Welte458e01b2019-03-10 11:14:43 +0100537
538respond_and_err:
539 if (res) {
540 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
541 worker_send_rspro(worker, resp);
542 }
543 return rc;
Harald Weltecce2aad2018-08-16 14:44:37 +0200544}
545
Harald Welte796a7492018-09-23 19:31:28 +0200546static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
547{
548 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
549 const SCARD_IO_REQUEST *pioSendPci = SCARD_PCI_T0;
550 SCARD_IO_REQUEST pioRecvPci;
551 uint8_t rx_buf[1024];
552 DWORD rx_buf_len = sizeof(rx_buf);
553 RsproPDU_t *pdu_resp;
Harald Weltee1d32892019-03-27 20:47:42 +0100554 struct client_slot clslot;
555 struct bank_slot bslot;
Harald Welte796a7492018-09-23 19:31:28 +0200556 long rc;
557
558 LOGW(worker, "tpduModemToCard(%s)\n", osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
559
560 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
561 LOGW(worker, "Unexpected tpduModemToCaard\n");
562 return -104;
563 }
564
Harald Weltee1d32892019-03-27 20:47:42 +0100565 /* Validate that toBankSlot / fromClientSlot match our expectations */
566 rspro2client_slot(&clslot, &mdm2sim->fromClientSlot);
567 rspro2bank_slot(&bslot, &mdm2sim->toBankSlot);
568 if (!bank_slot_equals(&worker->slot, &bslot)) {
569 LOGW(worker, "Unexpected BankSlot %u:%u in tpduModemToCard\n",
570 bslot.bank_id, bslot.slot_nr);
571 return -105;
572 }
573 if (!client_slot_equals(&worker->client.clslot, &clslot)) {
574 LOGW(worker, "Unexpected ClientSlot %u:%u in tpduModemToCard\n",
575 clslot.client_id, clslot.slot_nr);
576 return -106;
577 }
Harald Welte796a7492018-09-23 19:31:28 +0200578
579 rc = SCardTransmit(worker->reader.pcsc.hCard,
580 pioSendPci, mdm2sim->data.buf, mdm2sim->data.size,
581 &pioRecvPci, rx_buf, &rx_buf_len);
582 PCSC_ERROR(worker, rc, "SCardTransmit");
583
584 /* encode response PDU and send it */
585 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
586 rx_buf, rx_buf_len);
587 worker_send_rspro(worker, pdu_resp);
588
589 return 0;
590end:
591 return rc;
592}
593
Harald Welte77911b02018-08-14 23:47:30 +0200594/* handle one incoming RSPRO message from a client inside a worker thread */
595static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
596{
Harald Weltecce2aad2018-08-16 14:44:37 +0200597 int rc = -100;
598
Harald Welte77911b02018-08-14 23:47:30 +0200599 switch (pdu->msg.present) {
600 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200601 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200602 break;
603 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200604 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200605 break;
606 case RsproPDUchoice_PR_clientSlotStatusInd:
607 /* FIXME */
608 break;
609 default:
Harald Weltecce2aad2018-08-16 14:44:37 +0200610 rc = -101;
611 break;
Harald Welte77911b02018-08-14 23:47:30 +0200612 }
613
Harald Weltecce2aad2018-08-16 14:44:37 +0200614 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200615}
616
Harald Welte694df832018-10-03 22:47:52 +0200617static int wait_for_fd_or_timeout(int fd, unsigned int timeout_secs)
618{
619 struct timeval tout = { timeout_secs, 0 };
620 fd_set readset;
621
622 FD_ZERO(&readset);
623 FD_SET(fd, &readset);
624 return select(fd + 1, &readset, NULL, NULL, timeout_secs ? &tout : NULL);
625}
626
Harald Welte77911b02018-08-14 23:47:30 +0200627/* body of the main transceive loop */
628static int worker_transceive_loop(struct bankd_worker *worker)
629{
630 struct ipaccess_head *hh;
631 struct ipaccess_head_ext *hh_ext;
632 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
633 asn_dec_rval_t rval;
634 int data_len, rc;
Harald Welte9ebbacc2018-09-24 17:43:39 +0200635 RsproPDU_t *pdu = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200636
Harald Welte00a96732019-03-11 17:18:02 +0100637restart_wait:
Harald Welte694df832018-10-03 22:47:52 +0200638 rc = wait_for_fd_or_timeout(worker->client.fd, worker->timeout);
Harald Welte00a96732019-03-11 17:18:02 +0100639 if (rc == -1 && errno == EINTR) {
640 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
641 return -23;
642 goto restart_wait;
643 } else if (rc < 0)
644 return rc;
645 else if (rc == 0) {
Harald Welte694df832018-10-03 22:47:52 +0200646 /* TIMEOUT case */
Harald Welte150d6d62018-10-03 23:07:47 +0200647 switch (worker->state) {
648 case BW_ST_CONN_CLIENT_WAIT_MAP:
649 /* re-check if mapping exists meanwhile? */
650 worker_try_slotmap(worker);
651 break;
652 case BW_ST_CONN_CLIENT_MAPPED:
653 /* re-check if reader/card can be opened meanwhile? */
654 worker_open_card(worker);
655 break;
656 default:
657 OSMO_ASSERT(0);
658 }
659 /* return early, so we do another select rather than the blocking read below */
Harald Welte694df832018-10-03 22:47:52 +0200660 return 0;
661 };
662
Harald Welte77911b02018-08-14 23:47:30 +0200663 /* 1) blocking read of entire IPA message from the socket */
Harald Welte00a96732019-03-11 17:18:02 +0100664 rc = blocking_ipa_read(worker, buf, sizeof(buf));
Harald Welte77911b02018-08-14 23:47:30 +0200665 if (rc < 0)
666 return rc;
667 data_len = rc;
668
669 hh = (struct ipaccess_head *) buf;
Harald Welte5a3613a2018-10-11 12:56:21 +0200670 if (hh->proto != IPAC_PROTO_OSMO && hh->proto != IPAC_PROTO_IPACCESS) {
Harald Weltee1176cf2018-09-24 14:54:58 +0200671 LOGW(worker, "Received unsupported IPA protocol != OSMO: 0x%02x\n", hh->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200672 return -4;
Harald Weltee1176cf2018-09-24 14:54:58 +0200673 }
Harald Welte77911b02018-08-14 23:47:30 +0200674
Harald Welte5a3613a2018-10-11 12:56:21 +0200675 if (hh->proto == IPAC_PROTO_IPACCESS) {
Harald Welte19f881a2019-03-11 18:39:13 +0100676 switch (hh->data[0]) {
677 case IPAC_MSGT_PING:
678 return ipa_ccm_send_pong(worker->client.fd);
679 default:
680 LOGW(worker, "IPA CCM 0x%02x not implemented yet\n", hh->data[0]);
681 break;
682 }
Harald Welte5a3613a2018-10-11 12:56:21 +0200683 return 0;
684 }
685
Harald Welte77911b02018-08-14 23:47:30 +0200686 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
Harald Weltee1176cf2018-09-24 14:54:58 +0200687 if (data_len < sizeof(*hh_ext)) {
688 LOGW(worker, "Received short message\n");
Harald Welte77911b02018-08-14 23:47:30 +0200689 return -5;
Harald Weltee1176cf2018-09-24 14:54:58 +0200690 }
Harald Welte77911b02018-08-14 23:47:30 +0200691 data_len -= sizeof(*hh_ext);
Harald Weltee1176cf2018-09-24 14:54:58 +0200692 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO) {
693 LOGW(worker, "Received unsupported IPA EXT protocol != RSPRO: 0x%02x\n", hh_ext->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200694 return -6;
Harald Weltee1176cf2018-09-24 14:54:58 +0200695 }
Harald Welte77911b02018-08-14 23:47:30 +0200696
697 /* 2) ASN1 BER decode of the message */
698 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
Harald Weltee1176cf2018-09-24 14:54:58 +0200699 if (rval.code != RC_OK) {
700 LOGW(worker, "Error during BER decode of RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200701 return -7;
Harald Weltee1176cf2018-09-24 14:54:58 +0200702 }
Harald Welte77911b02018-08-14 23:47:30 +0200703
704 /* 3) handling of the message, possibly resulting in PCSC commands */
705 rc = worker_handle_rspro(worker, pdu);
706 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Weltee1176cf2018-09-24 14:54:58 +0200707 if (rc < 0) {
708 LOGW(worker, "Error handling RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200709 return rc;
Harald Weltee1176cf2018-09-24 14:54:58 +0200710 }
Harald Welte77911b02018-08-14 23:47:30 +0200711
712 /* everything OK if we reach here */
713 return 0;
714}
715
Harald Welted6dfb8c2018-08-16 14:46:53 +0200716/* obtain an ascii representation of the client IP/port */
717static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
718{
719 char hostbuf[32], portbuf[32];
720 int rc;
721
722 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
723 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
724 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
725 if (rc != 0) {
726 out[0] = '\0';
727 return -1;
728 }
729 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
730 return 0;
731}
732
Harald Welte77911b02018-08-14 23:47:30 +0200733/* worker thread main function */
734static void *worker_main(void *arg)
735{
Harald Welte77911b02018-08-14 23:47:30 +0200736 void *top_ctx;
737 int rc;
Harald Welte31c9eca2018-10-03 21:03:34 +0200738
Harald Welte00a96732019-03-11 17:18:02 +0100739 g_worker = (struct bankd_worker *) arg;
740
Harald Welte00a96732019-03-11 17:18:02 +0100741 worker_set_state(g_worker, BW_ST_INIT);
Harald Welte8d858292018-08-15 23:36:46 +0200742
Harald Welte77911b02018-08-14 23:47:30 +0200743 /* not permitted in multithreaded environment */
744 talloc_disable_null_tracking();
Harald Welte25075972019-03-11 17:33:17 +0100745 g_worker->tall_ctx = talloc_named_const(NULL, 0, "top");
746 talloc_asn1_ctx = talloc_named_const(g_worker->tall_ctx, 0, "asn1");
Harald Welte77911b02018-08-14 23:47:30 +0200747
Harald Welte286a2be2019-03-11 17:36:58 +0100748 /* set the thread name */
749 g_worker->name = talloc_asprintf(g_worker->tall_ctx, "bankd-worker(%u)", g_worker->num);
750 pthread_setname_np(pthread_self(), g_worker->name);
751
Harald Welte77911b02018-08-14 23:47:30 +0200752 /* push cleanup helper */
Harald Welte00a96732019-03-11 17:18:02 +0100753 pthread_cleanup_push(&worker_cleanup, g_worker);
Harald Welte77911b02018-08-14 23:47:30 +0200754
755 /* we continuously perform the same loop here, recycling the worker thread
756 * once the client connection is gone or we have some trouble with the card/reader */
757 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +0200758 char buf[128];
759
Harald Welte00a96732019-03-11 17:18:02 +0100760 g_worker->client.peer_addr_len = sizeof(g_worker->client.peer_addr);
Harald Welte77911b02018-08-14 23:47:30 +0200761
Harald Welte00a96732019-03-11 17:18:02 +0100762 worker_set_state(g_worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +0200763 /* first wait for an incoming TCP connection */
Harald Welte00a96732019-03-11 17:18:02 +0100764 rc = accept(g_worker->bankd->accept_fd, (struct sockaddr *) &g_worker->client.peer_addr,
765 &g_worker->client.peer_addr_len);
Harald Welte77911b02018-08-14 23:47:30 +0200766 if (rc < 0) {
767 continue;
768 }
Harald Welte00a96732019-03-11 17:18:02 +0100769 g_worker->client.fd = rc;
770 worker_client_addrstr(buf, sizeof(buf), g_worker);
771 LOGW(g_worker, "Accepted connection from %s\n", buf);
772 worker_set_state(g_worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +0200773
774 /* run the main worker transceive loop body until there was some error */
775 while (1) {
Harald Welte00a96732019-03-11 17:18:02 +0100776 rc = worker_transceive_loop(g_worker);
Harald Welte77911b02018-08-14 23:47:30 +0200777 if (rc < 0)
778 break;
Harald Welte653d6a02019-03-11 18:38:44 +0100779 if (g_worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
780 break;
Harald Welte77911b02018-08-14 23:47:30 +0200781 }
782
Harald Welte00a96732019-03-11 17:18:02 +0100783 LOGW(g_worker, "Error %d occurred: Cleaning up state\n", rc);
Harald Welted6dfb8c2018-08-16 14:46:53 +0200784
Harald Welte77911b02018-08-14 23:47:30 +0200785 /* clean-up: reset to sane state */
Harald Welte00a96732019-03-11 17:18:02 +0100786 if (g_worker->reader.pcsc.hCard) {
787 SCardDisconnect(g_worker->reader.pcsc.hCard, SCARD_UNPOWER_CARD);
788 g_worker->reader.pcsc.hCard = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200789 }
Harald Welte00a96732019-03-11 17:18:02 +0100790 if (g_worker->reader.pcsc.hContext) {
791 SCardReleaseContext(g_worker->reader.pcsc.hContext);
792 g_worker->reader.pcsc.hContext = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200793 }
Harald Welte00a96732019-03-11 17:18:02 +0100794 if (g_worker->reader.name)
795 g_worker->reader.name = NULL;
796 if (g_worker->client.fd >= 0)
797 close(g_worker->client.fd);
798 memset(&g_worker->client.peer_addr, 0, sizeof(g_worker->client.peer_addr));
799 g_worker->client.fd = -1;
800 g_worker->client.clslot.client_id = g_worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200801 }
802
803 pthread_cleanup_pop(1);
804 talloc_free(top_ctx);
805 pthread_exit(NULL);
806}