blob: 3fd4d6bed995a7de8558c80022e2e2d7ad77d7b3 [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 *
Harald Welte3dcdd202019-03-09 13:06:46 +010017 */
18
Harald Welte31c9eca2018-10-03 21:03:34 +020019#define _GNU_SOURCE
20
Harald Welte77911b02018-08-14 23:47:30 +020021#include <stdio.h>
22#include <stdlib.h>
23#include <stdint.h>
Harald Welte00a96732019-03-11 17:18:02 +010024#include <signal.h>
Harald Welte77911b02018-08-14 23:47:30 +020025#include <unistd.h>
Harald Welte707c85a2019-03-09 12:56:35 +010026#include <errno.h>
Harald Welte5bae20b2019-04-01 09:36:42 +020027#include <getopt.h>
Harald Welte77911b02018-08-14 23:47:30 +020028
29#include <pthread.h>
30
Harald Welted6dfb8c2018-08-16 14:46:53 +020031#include <sys/socket.h>
32#include <netdb.h>
33
Harald Welte12534e72018-08-15 23:37:29 +020034#include <osmocom/core/socket.h>
Harald Welte77911b02018-08-14 23:47:30 +020035#include <osmocom/core/linuxlist.h>
Harald Weltef94b9ee2018-09-25 15:04:21 +020036#include <osmocom/core/logging.h>
37#include <osmocom/core/application.h>
Harald Welte73bbd542021-12-08 20:39:55 +010038#include <osmocom/core/fsm.h>
Harald Welte77911b02018-08-14 23:47:30 +020039
40#include <osmocom/gsm/ipa.h>
41#include <osmocom/gsm/protocol/ipaccess.h>
42
Kévin Redonff5db6e2018-10-11 17:16:18 +020043#include <asn_application.h>
Harald Welte77911b02018-08-14 23:47:30 +020044#include <osmocom/rspro/RsproPDU.h>
45
46#include "bankd.h"
Harald Welte3cded632019-03-09 12:59:41 +010047#include "rspro_client_fsm.h"
Harald Welte61d98e92019-03-03 15:43:07 +010048#include "debug.h"
Harald Welte796a7492018-09-23 19:31:28 +020049#include "rspro_util.h"
James Tavares31e8bd72022-11-14 17:19:10 -050050#include "gsmtap.h"
Harald Welte77911b02018-08-14 23:47:30 +020051
Harald Welte00a96732019-03-11 17:18:02 +010052/* signal indicates to worker thread that its map has been deleted */
53#define SIGMAPDEL SIGRTMIN+1
Harald Welte0fd77a52019-12-05 22:05:39 +010054#define SIGMAPADD SIGRTMIN+2
Harald Welte25075972019-03-11 17:33:17 +010055
56static void handle_sig_usr1(int sig);
Harald Welte00a96732019-03-11 17:18:02 +010057static void handle_sig_mapdel(int sig);
Harald Welte0fd77a52019-12-05 22:05:39 +010058static void handle_sig_mapadd(int sig);
Harald Welte00a96732019-03-11 17:18:02 +010059
Harald Welte77911b02018-08-14 23:47:30 +020060__thread void *talloc_asn1_ctx;
Harald Weltef4b16f12019-03-09 20:58:17 +010061struct bankd *g_bankd;
Harald Welte25075972019-03-11 17:33:17 +010062static void *g_tall_ctx;
Harald Welteeea631b2022-05-03 15:14:19 +020063static char g_hostname[256];
Harald Welte77911b02018-08-14 23:47:30 +020064
65static void *worker_main(void *arg);
66
67/***********************************************************************
68* bankd core / main thread
69***********************************************************************/
70
Harald Welte43ab79f2018-10-03 23:34:21 +020071int asn_debug;
72
Harald Welte77911b02018-08-14 23:47:30 +020073static void bankd_init(struct bankd *bankd)
74{
Harald Welte25075972019-03-11 17:33:17 +010075 g_tall_ctx = talloc_named_const(NULL, 0, "global");
Harald Weltef94b9ee2018-09-25 15:04:21 +020076 osmo_init_logging2(g_tall_ctx, &log_info);
Harald Welte73bbd542021-12-08 20:39:55 +010077 log_set_print_level(osmo_stderr_target, 1);
78 log_set_print_category(osmo_stderr_target, 1);
79 log_set_print_category_hex(osmo_stderr_target, 0);
80 osmo_fsm_log_addr(0);
Harald Weltea9d7ad12021-12-08 21:09:12 +010081 log_set_print_tid(osmo_stderr_target, 1);
82 log_enable_multithread();
Harald Weltef94b9ee2018-09-25 15:04:21 +020083
Harald Welte43ab79f2018-10-03 23:34:21 +020084 asn_debug = 0;
85
Harald Weltea9bb9a92022-05-03 15:28:02 +020086 /* initialize members of 'bankd' */
Harald Weltecbd18962019-03-03 19:02:38 +010087 bankd->slotmaps = slotmap_init(bankd);
Harald Welte77911b02018-08-14 23:47:30 +020088 INIT_LLIST_HEAD(&bankd->workers);
89 pthread_mutex_init(&bankd->workers_mutex, NULL);
Harald Welte45c948c2018-09-23 19:26:52 +020090
Harald Weltea0f39502019-03-09 20:59:34 +010091 /* set some defaults, overridden by commandline/config */
Harald Welte2513d812019-04-01 21:03:02 +020092 bankd->srvc.bankd.bank_id = 1;
93 bankd->srvc.bankd.num_slots = 8;
Harald Weltea0f39502019-03-09 20:59:34 +010094
Harald Weltef1dd1622018-09-24 14:54:23 +020095 bankd->comp_id.type = ComponentType_remsimBankd;
Harald Welteeea631b2022-05-03 15:14:19 +020096 OSMO_STRLCPY_ARRAY(bankd->comp_id.name, g_hostname);
Harald Weltef1dd1622018-09-24 14:54:23 +020097 OSMO_STRLCPY_ARRAY(bankd->comp_id.software, "remsim-bankd");
98 OSMO_STRLCPY_ARRAY(bankd->comp_id.sw_version, PACKAGE_VERSION);
99 /* FIXME: other members of app_comp_id */
100
Harald Welte45c948c2018-09-23 19:26:52 +0200101 INIT_LLIST_HEAD(&bankd->pcsc_slot_names);
Harald Welte628672b2022-07-13 15:20:13 +0200102
103 bankd->cfg.permit_shared_pcsc = false;
James Tavares31e8bd72022-11-14 17:19:10 -0500104 bankd->cfg.gsmtap_host = NULL;
105 bankd->cfg.gsmtap_slot = -1;
Harald Welte77911b02018-08-14 23:47:30 +0200106}
107
108/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +0200109static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +0200110{
111 struct bankd_worker *worker;
112 int rc;
113
114 worker = talloc_zero(bankd, struct bankd_worker);
115 if (!worker)
116 return NULL;
117
118 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +0200119 worker->num = i;
Harald Welte297d72e2019-03-28 18:42:35 +0100120 worker->ops = &pcsc_driver_ops;
James Tavaresf74d1da2022-11-14 00:21:12 -0500121 worker->last_vccPresent = true; /* allow cold reset should first indication be false */
122 worker->last_resetActive = false; /* allow warm reset should first indication be true */
Harald Welte77911b02018-08-14 23:47:30 +0200123
124 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
125
126 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
127 if (rc != 0) {
128 talloc_free(worker);
129 return NULL;
130 }
131
132 pthread_mutex_lock(&bankd->workers_mutex);
133 llist_add_tail(&worker->list, &bankd->workers);
134 pthread_mutex_unlock(&bankd->workers_mutex);
135
136 return worker;
137}
138
139static bool terminate = false;
140
Harald Weltea4967832019-12-05 22:04:57 +0100141/* deliver given signal 'sig' to the firts worker matching bs and cs (if given) */
142static void send_signal_to_worker(const struct bank_slot *bs, const struct client_slot *cs, int sig)
143{
144 struct bankd_worker *worker;
145 pthread_mutex_lock(&g_bankd->workers_mutex);
146 llist_for_each_entry(worker, &g_bankd->workers, list) {
147 if (bs && (bs->bank_id != worker->slot.bank_id || bs->slot_nr != worker->slot.slot_nr))
148 continue;
149 if (cs && (cs->client_id != worker->client.clslot.client_id ||
150 cs->slot_nr != worker->client.clslot.slot_nr))
151 continue;
152
153 pthread_kill(worker->thread, sig);
154 break;
155 }
156 pthread_mutex_unlock(&g_bankd->workers_mutex);
157}
158
Harald Weltec650a4d2019-12-04 15:02:27 +0100159/* Remove a mapping */
160static void bankd_srvc_remove_mapping(struct slot_mapping *map)
161{
162 struct bank_slot bs = map->bank;
163
164 slotmap_del(g_bankd->slotmaps, map);
165
166 /* kill/reset the respective worker, if any! */
Harald Weltea4967832019-12-05 22:04:57 +0100167 send_signal_to_worker(&bs, NULL, SIGMAPDEL);
Harald Weltec650a4d2019-12-04 15:02:27 +0100168}
169
Harald Welte707c85a2019-03-09 12:56:35 +0100170/* handle incoming messages from server */
171static int bankd_srvc_handle_rx(struct rspro_server_conn *srvc, const RsproPDU_t *pdu)
172{
Harald Welte454f5e22019-03-09 21:38:34 +0100173 const CreateMappingReq_t *creq = NULL;
174 const RemoveMappingReq_t *rreq = NULL;
Harald Weltef34fb792019-12-04 19:51:32 +0100175 struct bankd_worker *worker;
Harald Welte454f5e22019-03-09 21:38:34 +0100176 struct slot_mapping *map;
177 struct bank_slot bs;
178 struct client_slot cs;
179 RsproPDU_t *resp;
180
Harald Welte079c0682022-04-27 09:26:52 +0200181 LOGPFSML(srvc->fi, LOGL_DEBUG, "Rx RSPRO %s\n", rspro_msgt_name(pdu));
Harald Welte707c85a2019-03-09 12:56:35 +0100182
183 switch (pdu->msg.present) {
184 case RsproPDUchoice_PR_connectBankRes:
Harald Welte5ae0f312022-04-25 15:53:04 +0200185 if (pdu->msg.choice.connectBankRes.identity.type != ComponentType_remsimServer) {
186 LOGPFSML(srvc->fi, LOGL_ERROR, "Server connection to a ComponentType(%ld) != RemsimServer? "
187 "Check your IP/Port configuration\n",
188 pdu->msg.choice.connectBankRes.identity.type);
189 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_DISCONNECT, NULL);
190 return -1;
191 }
Harald Welte707c85a2019-03-09 12:56:35 +0100192 /* Store 'identity' of server in srvc->peer_comp_id */
193 rspro_comp_id_retrieve(&srvc->peer_comp_id, &pdu->msg.choice.connectBankRes.identity);
194 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_CLIENT_CONN_RES, (void *) pdu);
195 break;
Harald Welte454f5e22019-03-09 21:38:34 +0100196 case RsproPDUchoice_PR_createMappingReq:
197 creq = &pdu->msg.choice.createMappingReq;
Harald Welte2513d812019-04-01 21:03:02 +0200198 if (creq->bank.bankId != g_bankd->srvc.bankd.bank_id) {
Harald Welte94ba99b2019-03-27 22:42:11 +0100199 LOGPFSML(srvc->fi, LOGL_ERROR, "createMapping specifies invalid Bank ID %lu "
Harald Welte2513d812019-04-01 21:03:02 +0200200 "(we are %u)\n", creq->bank.bankId, g_bankd->srvc.bankd.bank_id);
Harald Welte454f5e22019-03-09 21:38:34 +0100201 resp = rspro_gen_CreateMappingRes(ResultCode_illegalBankId);
Harald Welte2513d812019-04-01 21:03:02 +0200202 } else if (creq->bank.slotNr >= g_bankd->srvc.bankd.num_slots) {
Harald Welte94ba99b2019-03-27 22:42:11 +0100203 LOGPFSML(srvc->fi, LOGL_ERROR, "createMapping specifies invalid Slot Nr %lu "
Harald Welte2513d812019-04-01 21:03:02 +0200204 "(we have %u)\n", creq->bank.slotNr, g_bankd->srvc.bankd.num_slots);
Harald Welte454f5e22019-03-09 21:38:34 +0100205 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
Harald Welte94ba99b2019-03-27 22:42:11 +0100206 } else {
Harald Welte454f5e22019-03-09 21:38:34 +0100207 rspro2bank_slot(&bs, &creq->bank);
208 rspro2client_slot(&cs, &creq->client);
Harald Weltee6fa46a2019-12-04 15:06:33 +0100209 /* check if map exists */
210 map = slotmap_by_bank(g_bankd->slotmaps, &bs);
211 if (map) {
212 if (client_slot_equals(&map->client, &cs)) {
213 LOGPFSML(srvc->fi, LOGL_ERROR, "ignoring identical slotmap\n");
214 resp = rspro_gen_CreateMappingRes(ResultCode_ok);
215 goto send_resp;
216 } else {
Harald Welte079c0682022-04-27 09:26:52 +0200217 LOGPFSML(srvc->fi, LOGL_NOTICE, "implicitly removing slotmap\n");
Harald Weltee6fa46a2019-12-04 15:06:33 +0100218 bankd_srvc_remove_mapping(map);
219 }
220 }
Harald Welte454f5e22019-03-09 21:38:34 +0100221 /* Add a new mapping */
222 map = slotmap_add(g_bankd->slotmaps, &bs, &cs);
Harald Welte94ba99b2019-03-27 22:42:11 +0100223 if (!map) {
224 LOGPFSML(srvc->fi, LOGL_ERROR, "could not create slotmap\n");
Harald Welte454f5e22019-03-09 21:38:34 +0100225 resp = rspro_gen_CreateMappingRes(ResultCode_illegalSlotId);
Harald Welte0fd77a52019-12-05 22:05:39 +0100226 } else {
227 send_signal_to_worker(NULL, &cs, SIGMAPADD);
Harald Welte454f5e22019-03-09 21:38:34 +0100228 resp = rspro_gen_CreateMappingRes(ResultCode_ok);
Harald Welte0fd77a52019-12-05 22:05:39 +0100229 }
Harald Welte454f5e22019-03-09 21:38:34 +0100230 }
Harald Weltee6fa46a2019-12-04 15:06:33 +0100231send_resp:
Harald Welte454f5e22019-03-09 21:38:34 +0100232 server_conn_send_rspro(srvc, resp);
233 break;
234 case RsproPDUchoice_PR_removeMappingReq:
235 rreq = &pdu->msg.choice.removeMappingReq;
Harald Welte2513d812019-04-01 21:03:02 +0200236 if (rreq->bank.bankId != g_bankd->srvc.bankd.bank_id) {
Harald Welte94ba99b2019-03-27 22:42:11 +0100237 LOGPFSML(srvc->fi, LOGL_ERROR, "removeMapping specifies invalid Bank ID %lu "
Harald Welte550b2952019-12-04 21:22:54 +0100238 "(we are %u)\n", rreq->bank.bankId, g_bankd->srvc.bankd.bank_id);
Harald Welte454f5e22019-03-09 21:38:34 +0100239 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalBankId);
Harald Welte2513d812019-04-01 21:03:02 +0200240 } else if (rreq->bank.slotNr >= g_bankd->srvc.bankd.num_slots) {
Harald Welte94ba99b2019-03-27 22:42:11 +0100241 LOGPFSML(srvc->fi, LOGL_ERROR, "removeMapping specifies invalid Slot Nr %lu "
Harald Welte550b2952019-12-04 21:22:54 +0100242 "(we have %u)\n", rreq->bank.slotNr, g_bankd->srvc.bankd.num_slots);
Harald Welte454f5e22019-03-09 21:38:34 +0100243 resp = rspro_gen_RemoveMappingRes(ResultCode_illegalSlotId);
Harald Welte94ba99b2019-03-27 22:42:11 +0100244 } else {
Harald Welte454f5e22019-03-09 21:38:34 +0100245 rspro2bank_slot(&bs, &rreq->bank);
246 /* Remove a mapping */
247 map = slotmap_by_bank(g_bankd->slotmaps, &bs);
Harald Welte94ba99b2019-03-27 22:42:11 +0100248 if (!map) {
249 LOGPFSML(srvc->fi, LOGL_ERROR, "could not find to-be-deleted slotmap\n");
Harald Welte454f5e22019-03-09 21:38:34 +0100250 resp = rspro_gen_RemoveMappingRes(ResultCode_unknownSlotmap);
Harald Welte94ba99b2019-03-27 22:42:11 +0100251 } else {
Harald Welted9fb9392019-12-04 19:05:01 +0100252 rspro2client_slot(&cs, &rreq->client);
253 if (!client_slot_equals(&map->client, &cs)) {
Harald Welte079c0682022-04-27 09:26:52 +0200254 LOGPFSML(srvc->fi, LOGL_NOTICE, "ClientId in removeMappingReq != map\n");
Harald Welted9fb9392019-12-04 19:05:01 +0100255 resp = rspro_gen_RemoveMappingRes(ResultCode_unknownSlotmap);
256 } else {
Harald Welte079c0682022-04-27 09:26:52 +0200257 LOGPFSML(srvc->fi, LOGL_INFO, "removing slotmap\n");
Harald Welted9fb9392019-12-04 19:05:01 +0100258 bankd_srvc_remove_mapping(map);
259 resp = rspro_gen_RemoveMappingRes(ResultCode_ok);
260 }
Harald Welte454f5e22019-03-09 21:38:34 +0100261 }
262 }
Harald Welte942f1ff2019-03-09 21:49:08 +0100263 server_conn_send_rspro(srvc, resp);
Harald Welte454f5e22019-03-09 21:38:34 +0100264 break;
Harald Weltef34fb792019-12-04 19:51:32 +0100265 case RsproPDUchoice_PR_resetStateReq:
266 /* delete all slotmaps */
267 slotmap_del_all(g_bankd->slotmaps);
268 /* notify all workers about maps having disappeared */
269 pthread_mutex_lock(&g_bankd->workers_mutex);
270 llist_for_each_entry(worker, &g_bankd->workers, list) {
271 pthread_kill(worker->thread, SIGMAPDEL);
272 }
273 pthread_mutex_unlock(&g_bankd->workers_mutex);
274 /* send response to server */
275 resp = rspro_gen_ResetStateRes(ResultCode_ok);
276 server_conn_send_rspro(srvc, resp);
277 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100278 default:
Harald Welteeb971b52019-03-27 22:41:45 +0100279 LOGPFSML(srvc->fi, LOGL_ERROR, "Unknown/Unsupported RSPRO PDU type: %u\n",
280 pdu->msg.present);
Harald Welte707c85a2019-03-09 12:56:35 +0100281 return -1;
282 }
283
284 return 0;
285}
286
Harald Welte5bae20b2019-04-01 09:36:42 +0200287static void printf_help()
288{
289 printf(
James Tavares31e8bd72022-11-14 17:19:10 -0500290" -h --help Print this help message\n"
291" -V --version Print the version of the program\n"
292" -d --debug option Enable debug logging (e.g. DMAIN:DST2)\n"
293" -i --server-host A.B.C.D remsim-server IP address (default: 127.0.0.1)\n"
294" -p --server-port <1-65535> remsim-server TCP port (default: 9998)\n"
295" -b --bank-id <1-1023> Bank Identifier of this SIM bank (default: 1)\n"
296" -n --num-slots <1-1023> Number of Slots in this SIM bank (default: 8)\n"
297" -I --bind-ip A.B.C.D Local IP address to bind for incoming client\n"
298" connections (default: INADDR_ANY)\n"
299" -P --bind-port <1-65535> Local TCP port to bind for incoming client\n"
300" connections (default: 9999)\n"
301" -s --permit-shared-pcsc Permit SHARED access to PC/SC readers (default: exclusive)\n"
302" -g --gsmtap-ip A.B.C.D Enable GSMTAP and send APDU traces to given IP\n"
303" -G --gsmtap-slot <0-1023> Limit tracing to given bank slot, only (default: all slots)\n"
Harald Welte5bae20b2019-04-01 09:36:42 +0200304 );
305}
306
307static int g_bind_port = 9999;
308static char *g_bind_ip = NULL;
Harald Welte00a96732019-03-11 17:18:02 +0100309
Harald Weltef8c6eeb2021-12-08 20:33:00 +0100310static void handle_options(int argc, char **argv)
Harald Welte707c85a2019-03-09 12:56:35 +0100311{
Harald Welte5bae20b2019-04-01 09:36:42 +0200312 while (1) {
313 int option_index = 0, c;
314 static const struct option long_options[] = {
315 { "help", 0, 0, 'h' },
Harald Weltecd7fcd72019-12-03 21:29:07 +0100316 { "version", 0, 0, 'V' },
Harald Welte80a01102020-05-25 14:55:12 +0200317 { "debug", 1, 0, 'd' },
Harald Welte5bae20b2019-04-01 09:36:42 +0200318 { "server-host", 1, 0, 'i' },
319 { "server-port", 1, 0, 'p' },
320 { "bank-id", 1, 0, 'b' },
Harald Welte2513d812019-04-01 21:03:02 +0200321 { "num-slots", 1, 0, 'n' },
Harald Welte5bae20b2019-04-01 09:36:42 +0200322 { "component-name", 1, 0, 'N' },
323 { "bind-ip", 1, 0, 'I' },
324 { "bind-port", 1, 0, 'P' },
Harald Welte628672b2022-07-13 15:20:13 +0200325 { "permit-shared-pcsc", 0, 0, 's' },
James Tavares31e8bd72022-11-14 17:19:10 -0500326 { "gsmtap-ip", 1, 0, 'g' },
327 { "gsmtap-slot", 1, 0, 'G' },
Harald Welte5bae20b2019-04-01 09:36:42 +0200328 { 0, 0, 0, 0 }
329 };
330
James Tavares31e8bd72022-11-14 17:19:10 -0500331 c = getopt_long(argc, argv, "hVd:i:p:b:n:N:I:P:sg:G:", long_options, &option_index);
Harald Welte5bae20b2019-04-01 09:36:42 +0200332 if (c == -1)
333 break;
334
335 switch (c) {
336 case 'h':
337 printf_help();
338 exit(0);
339 break;
Harald Weltecd7fcd72019-12-03 21:29:07 +0100340 case 'V':
341 printf("osmo-remsim-bankd version %s\n", VERSION);
342 exit(0);
343 break;
Harald Welte80a01102020-05-25 14:55:12 +0200344 case 'd':
345 log_parse_category_mask(osmo_stderr_target, optarg);
346 break;
Harald Welte5bae20b2019-04-01 09:36:42 +0200347 case 'i':
348 g_bankd->srvc.server_host = optarg;
349 break;
350 case 'p':
351 g_bankd->srvc.server_port = atoi(optarg);
352 break;
353 case 'b':
Harald Welte2513d812019-04-01 21:03:02 +0200354 g_bankd->srvc.bankd.bank_id = atoi(optarg);
355 break;
356 case 'n':
357 g_bankd->srvc.bankd.num_slots = atoi(optarg);
Harald Welte5bae20b2019-04-01 09:36:42 +0200358 break;
359 case 'N':
360 OSMO_STRLCPY_ARRAY(g_bankd->srvc.own_comp_id.name, optarg);
361 break;
362 case 'I':
363 g_bind_ip = optarg;
364 break;
365 case 'P':
366 g_bind_port = atoi(optarg);
367 break;
Harald Welte628672b2022-07-13 15:20:13 +0200368 case 's':
369 g_bankd->cfg.permit_shared_pcsc = true;
370 break;
James Tavares31e8bd72022-11-14 17:19:10 -0500371 case 'g':
372 g_bankd->cfg.gsmtap_host = optarg;
373 break;
374 case 'G':
375 g_bankd->cfg.gsmtap_slot = atoi(optarg);
376 break;
Harald Welte5bae20b2019-04-01 09:36:42 +0200377 }
378 }
Harald Welte707c85a2019-03-09 12:56:35 +0100379}
380
Harald Welte77911b02018-08-14 23:47:30 +0200381int main(int argc, char **argv)
382{
Harald Weltef4b16f12019-03-09 20:58:17 +0100383 struct rspro_server_conn *srvc;
Harald Welte77911b02018-08-14 23:47:30 +0200384 int i, rc;
385
Harald Weltef4b16f12019-03-09 20:58:17 +0100386 g_bankd = talloc_zero(NULL, struct bankd);
387 OSMO_ASSERT(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200388
Harald Welteeea631b2022-05-03 15:14:19 +0200389 if (gethostname(g_hostname, sizeof(g_hostname)) < 0)
390 OSMO_STRLCPY_ARRAY(g_hostname, "unknown");
391
Harald Weltef4b16f12019-03-09 20:58:17 +0100392 bankd_init(g_bankd);
393
394 srvc = &g_bankd->srvc;
Harald Welte707c85a2019-03-09 12:56:35 +0100395 srvc->server_host = "localhost";
396 srvc->server_port = 9998;
397 srvc->handle_rx = bankd_srvc_handle_rx;
398 srvc->own_comp_id.type = ComponentType_remsimBankd;
Harald Welteeea631b2022-05-03 15:14:19 +0200399 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.name, g_hostname);
Harald Welte707c85a2019-03-09 12:56:35 +0100400 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.software, "remsim-bankd");
401 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.sw_version, PACKAGE_VERSION);
402
403 handle_options(argc, argv);
404
Harald Welte25075972019-03-11 17:33:17 +0100405 g_bankd->main = pthread_self();
Harald Welte00a96732019-03-11 17:18:02 +0100406 signal(SIGMAPDEL, handle_sig_mapdel);
Harald Welte0fd77a52019-12-05 22:05:39 +0100407 signal(SIGMAPADD, handle_sig_mapadd);
Harald Welte25075972019-03-11 17:33:17 +0100408 signal(SIGUSR1, handle_sig_usr1);
Harald Welte00a96732019-03-11 17:18:02 +0100409
Harald Weltee89fecd2019-04-04 09:23:13 +0200410 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
411 * read once during bankd initialization, when the worker threads haven't
412 * started yet */
Harald Weltee9e505c2022-05-03 11:58:01 +0200413 rc = bankd_pcsc_read_slotnames(g_bankd, "bankd_pcsc_slots.csv");
414 if (rc)
415 exit(1);
Harald Weltee89fecd2019-04-04 09:23:13 +0200416
Harald Welte707c85a2019-03-09 12:56:35 +0100417 /* Connection towards remsim-server */
Harald Weltef4b16f12019-03-09 20:58:17 +0100418 rc = server_conn_fsm_alloc(g_bankd, srvc);
Harald Welte707c85a2019-03-09 12:56:35 +0100419 if (rc < 0) {
420 fprintf(stderr, "Unable to create Server conn FSM: %s\n", strerror(errno));
421 exit(1);
422 }
Harald Welted2192e22019-11-07 18:10:57 +0100423 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_ESTABLISH, NULL);
Harald Welte707c85a2019-03-09 12:56:35 +0100424
425 /* create listening socket for inbound client connections */
Harald Welte5bae20b2019-04-01 09:36:42 +0200426 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, g_bind_ip, g_bind_port, OSMO_SOCK_F_BIND);
Harald Weltee9e505c2022-05-03 11:58:01 +0200427 if (rc < 0) {
428 fprintf(stderr, "Unable to create TCP socket at %s:%d: %s\n",
429 g_bind_ip ? g_bind_ip : "INADDR_ANY", g_bind_port, strerror(errno));
Harald Welte12534e72018-08-15 23:37:29 +0200430 exit(1);
Harald Weltee9e505c2022-05-03 11:58:01 +0200431 }
Harald Weltef4b16f12019-03-09 20:58:17 +0100432 g_bankd->accept_fd = rc;
Harald Welte12534e72018-08-15 23:37:29 +0200433
James Tavares31e8bd72022-11-14 17:19:10 -0500434 /* initialize gsmtap, if required */
435 if (g_bankd->cfg.gsmtap_host) {
436 rc = bankd_gsmtap_init(g_bankd->cfg.gsmtap_host);
437 if (rc < 0) {
438 fprintf(stderr, "Unable to open GSMTAP");
439 exit(1);
440 }
441 }
442
Harald Weltea0f39502019-03-09 20:59:34 +0100443 /* create worker threads: One per reader/slot! */
Harald Welte2513d812019-04-01 21:03:02 +0200444 for (i = 0; i < g_bankd->srvc.bankd.num_slots; i++) {
Harald Welte77911b02018-08-14 23:47:30 +0200445 struct bankd_worker *w;
Harald Weltef4b16f12019-03-09 20:58:17 +0100446 w = bankd_create_worker(g_bankd, i);
Harald Weltee9e505c2022-05-03 11:58:01 +0200447 if (!w) {
448 fprintf(stderr, "Error creating bankd worker thread\n");
Harald Welte77911b02018-08-14 23:47:30 +0200449 exit(21);
Harald Weltee9e505c2022-05-03 11:58:01 +0200450 }
Harald Welte77911b02018-08-14 23:47:30 +0200451 }
452
453 while (1) {
454 if (terminate)
455 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100456 osmo_select_main(0);
Harald Welte77911b02018-08-14 23:47:30 +0200457 }
458
Harald Weltef4b16f12019-03-09 20:58:17 +0100459 talloc_free(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200460 exit(0);
461}
462
463
464
465/***********************************************************************
466 * bankd worker thread
467 ***********************************************************************/
468
Harald Welte00a96732019-03-11 17:18:02 +0100469static __thread struct bankd_worker *g_worker;
470
Harald Welte8d858292018-08-15 23:36:46 +0200471struct value_string worker_state_names[] = {
472 { BW_ST_INIT, "INIT" },
473 { BW_ST_ACCEPTING, "ACCEPTING" },
474 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
475 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200476 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200477 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
478 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
Harald Welte00a96732019-03-11 17:18:02 +0100479 { BW_ST_CONN_CLIENT_UNMAPPED, "CONN_CLIENT_UNMAPPED" },
Harald Welte8d858292018-08-15 23:36:46 +0200480 { 0, NULL }
481};
482
Harald Welte1f699b42019-03-28 13:41:08 +0100483static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu);
484
Harald Welte8d858292018-08-15 23:36:46 +0200485static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
486{
487 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
488 worker->state = new_state;
Harald Welte150d6d62018-10-03 23:07:47 +0200489 worker->timeout = 0;
490}
491
492static void worker_set_state_timeout(struct bankd_worker *worker, enum bankd_worker_state new_state,
493 unsigned int timeout_secs)
494{
495 LOGW(worker, "Changing state to %s (timeout=%u)\n",
496 get_value_string(worker_state_names, new_state), timeout_secs);
497 worker->state = new_state;
498 worker->timeout = timeout_secs;
Harald Welte8d858292018-08-15 23:36:46 +0200499}
Harald Welte77911b02018-08-14 23:47:30 +0200500
Harald Welte00a96732019-03-11 17:18:02 +0100501/* signal handler for receiving SIGMAPDEL from main thread */
502static void handle_sig_mapdel(int sig)
503{
504 LOGW(g_worker, "SIGMAPDEL received: Main thread informs us our map is gone\n");
505 OSMO_ASSERT(sig == SIGMAPDEL);
Harald Weltea8d945e2019-12-04 22:24:18 +0100506 if (g_worker->state >= BW_ST_CONN_CLIENT_MAPPED) {
507 g_worker->slot.bank_id = 0xffff;
508 g_worker->slot.slot_nr = 0xffff;
509 worker_set_state(g_worker, BW_ST_CONN_CLIENT_UNMAPPED);
510 }
Harald Welte00a96732019-03-11 17:18:02 +0100511}
512
Harald Welte0fd77a52019-12-05 22:05:39 +0100513/* signal handler for receiving SIGMAPADD from main thread */
514static void handle_sig_mapadd(int sig)
515{
516 LOGW(g_worker, "SIGMAPADD received\n");
517 /* do nothing */
518}
519
Harald Welte25075972019-03-11 17:33:17 +0100520static void handle_sig_usr1(int sig)
521{
522 OSMO_ASSERT(sig == SIGUSR1);
523
524 if (pthread_equal(g_bankd->main, pthread_self())) {
525 struct bankd_worker *worker;
526 /* main thread */
527 fprintf(stderr, "=== Talloc Report of main thread:\n");
Harald Welteb54a51e2019-03-31 15:57:59 +0200528 talloc_report_full(g_tall_ctx, stderr);
Harald Welte25075972019-03-11 17:33:17 +0100529
530 /* iterate over worker threads and ask them to dump their talloc state */
531 pthread_mutex_lock(&g_bankd->workers_mutex);
532 llist_for_each_entry(worker, &g_bankd->workers, list) {
533 pthread_kill(worker->thread, SIGUSR1);
534 }
535 pthread_mutex_unlock(&g_bankd->workers_mutex);
536 } else {
537 /* worker thread */
538 fprintf(stderr, "=== Talloc Report of %s\n", g_worker->name);
Harald Welteb54a51e2019-03-31 15:57:59 +0200539 talloc_report_full(g_worker->tall_ctx, stderr);
Harald Welte25075972019-03-11 17:33:17 +0100540 }
541}
542
Harald Welte77911b02018-08-14 23:47:30 +0200543static void worker_cleanup(void *arg)
544{
545 struct bankd_worker *worker = (struct bankd_worker *) arg;
546 struct bankd *bankd = worker->bankd;
547
548 /* FIXME: should we still do this? in the thread ?!? */
549 pthread_mutex_lock(&bankd->workers_mutex);
550 llist_del(&worker->list);
551 talloc_free(worker); /* FIXME: is this safe? */
552 pthread_mutex_unlock(&bankd->workers_mutex);
553}
554
Harald Welteaf614732018-08-17 22:10:05 +0200555static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200556{
Harald Welte297d72e2019-03-28 18:42:35 +0100557 int rc;
Harald Welte77911b02018-08-14 23:47:30 +0200558
Harald Welte150d6d62018-10-03 23:07:47 +0200559 OSMO_ASSERT(worker->state == BW_ST_CONN_CLIENT_MAPPED);
560
Harald Welte694df832018-10-03 22:47:52 +0200561 if (!worker->reader.name) {
562 /* resolve PC/SC reader name from slot_id -> name map */
563 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
564 if (!worker->reader.name) {
565 LOGW(worker, "No PC/SC reader name configured for %u/%u, fix your config\n",
566 worker->slot.bank_id, worker->slot.slot_nr);
Harald Welte297d72e2019-03-28 18:42:35 +0100567 return -1;
Harald Welte694df832018-10-03 22:47:52 +0200568 }
569 }
Harald Welte45c948c2018-09-23 19:26:52 +0200570 OSMO_ASSERT(worker->reader.name);
571
Harald Welte297d72e2019-03-28 18:42:35 +0100572 rc = worker->ops->open_card(worker);
573 if (rc < 0)
574 return rc;
Harald Welte1f699b42019-03-28 13:41:08 +0100575
Harald Welte57593f02018-09-23 19:30:31 +0200576 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
Harald Welte150d6d62018-10-03 23:07:47 +0200577 /* FIXME: notify client about this state change */
Harald Welte57593f02018-09-23 19:30:31 +0200578
Harald Welteaf614732018-08-17 22:10:05 +0200579 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200580}
Harald Welte77911b02018-08-14 23:47:30 +0200581
582
Harald Welte00a96732019-03-11 17:18:02 +0100583static int blocking_ipa_read(struct bankd_worker *worker, uint8_t *buf, unsigned int buf_size)
Harald Welte77911b02018-08-14 23:47:30 +0200584{
585 struct ipaccess_head *hh;
586 uint16_t len;
587 int needed, rc;
588
589 if (buf_size < sizeof(*hh))
590 return -1;
591
592 hh = (struct ipaccess_head *) buf;
593
Harald Welte00a96732019-03-11 17:18:02 +0100594 /* we use 'recv' and not 'read' below, as 'recv' will always fail with -EINTR
595 * in case of a signal being received */
596
597restart_hdr:
598 /* 1) blocking recv from the socket (IPA header) */
599 rc = recv(worker->client.fd, buf, sizeof(*hh), 0);
600 if (rc == -1 && errno == EINTR) {
601 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
602 return -23;
603 goto restart_hdr;
604 } else if (rc < 0)
605 return rc;
606 else if (rc < sizeof(*hh))
Harald Welte77911b02018-08-14 23:47:30 +0200607 return -2;
608
609 len = ntohs(hh->len);
610 needed = len; //- sizeof(*hh);
611
Harald Welte00a96732019-03-11 17:18:02 +0100612restart_body:
613 /* 2) blocking recv from the socket (payload) */
614 rc = recv(worker->client.fd, buf+sizeof(*hh), needed, 0);
615 if (rc == -1 && errno == EINTR) {
616 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
617 return -23;
618 goto restart_body;
619 } else if (rc < 0)
620 return rc;
621 else if (rc < needed)
Harald Welte77911b02018-08-14 23:47:30 +0200622 return -3;
623
624 return len;
625}
626
Harald Welte796a7492018-09-23 19:31:28 +0200627static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
628{
629 struct msgb *msg = rspro_enc_msg(pdu);
630 int rc;
631
632 if (!msg) {
Harald Welte2eee4502019-03-30 08:50:35 +0100633 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Welte796a7492018-09-23 19:31:28 +0200634 LOGW(worker, "error encoding RSPRO\n");
635 return -1;
636 }
637
Harald Weltefd471192018-09-24 14:51:14 +0200638 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200639 /* prepend the header */
640 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200641 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200642
643 /* actually send it through the socket */
644 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
645 if (rc == msgb_length(msg))
646 rc = 0;
647 else {
648 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
649 rc = -1;
650 }
651
652 msgb_free(msg);
653
654 return rc;
655}
656
Harald Welte150d6d62018-10-03 23:07:47 +0200657/* attempt to obtain slot-map */
658static int worker_try_slotmap(struct bankd_worker *worker)
659{
Harald Weltecbd18962019-03-03 19:02:38 +0100660 struct slot_mapping *slmap;
Harald Welte150d6d62018-10-03 23:07:47 +0200661
Harald Weltecbd18962019-03-03 19:02:38 +0100662 slmap = slotmap_by_client(worker->bankd->slotmaps, &worker->client.clslot);
Harald Welte150d6d62018-10-03 23:07:47 +0200663 if (!slmap) {
664 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
665 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
666 /* check in 10s if the map has been installed meanwhile by main thread */
667 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_WAIT_MAP, 10);
668 return -1;
669 } else {
670 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
671 slmap->client.client_id, slmap->client.slot_nr,
672 slmap->bank.bank_id, slmap->bank.slot_nr);
673 worker->slot = slmap->bank;
674 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_MAPPED, 10);
675 return worker_open_card(worker);
676 }
677}
678
Harald Welte1f699b42019-03-28 13:41:08 +0100679/* inform the remote end (client) about the (new) ATR */
680static int worker_send_atr(struct bankd_worker *worker)
681{
682 RsproPDU_t *set_atr;
683 set_atr = rspro_gen_SetAtrReq(worker->client.clslot.client_id,
684 worker->client.clslot.slot_nr,
685 worker->card.atr, worker->card.atr_len);
James Tavares31e8bd72022-11-14 17:19:10 -0500686
687 /* trace ATR to GSMTAP, if configured */
688 if (g_bankd->cfg.gsmtap_host && (g_bankd->cfg.gsmtap_slot == -1 ||
689 g_bankd->cfg.gsmtap_slot == worker->slot.slot_nr)) {
690 bankd_gsmtap_send_apdu(GSMTAP_SIM_ATR, worker->card.atr, worker->card.atr_len,
691 NULL, 0);
692 }
693
Harald Welte1f699b42019-03-28 13:41:08 +0100694 if (!set_atr)
695 return -1;
696 return worker_send_rspro(worker, set_atr);
697}
Harald Welte150d6d62018-10-03 23:07:47 +0200698
Harald Weltecce2aad2018-08-16 14:44:37 +0200699static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
700{
Harald Welteaf614732018-08-17 22:10:05 +0200701 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
Harald Welte458e01b2019-03-10 11:14:43 +0100702 RsproPDU_t *resp = NULL;
Harald Welte3e689872018-09-24 14:52:56 +0200703 e_ResultCode res;
Harald Welte458e01b2019-03-10 11:14:43 +0100704 int rc;
Harald Welteaf614732018-08-17 22:10:05 +0200705
Harald Weltecce2aad2018-08-16 14:44:37 +0200706 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
707
Harald Welte9f7ca612021-12-08 15:29:28 +0100708 LOGW(worker, "Rx RSPRO connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
Harald Weltecce2aad2018-08-16 14:44:37 +0200709 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
710 /* FIXME: store somewhere? */
711
712 if (worker->state != BW_ST_CONN_WAIT_ID) {
713 LOGW(worker, "Unexpected connectClientReq\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100714 rc = -102;
715 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200716 }
717
Harald Welte371d0262018-08-16 15:23:58 +0200718 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200719 LOGW(worker, "missing clientID, aborting\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100720 res = ResultCode_illegalClientId;
721 rc = -103;
722 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200723 }
Harald Welte371d0262018-08-16 15:23:58 +0200724 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
725 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200726 worker_set_state(worker, BW_ST_CONN_CLIENT);
727
Harald Welte150d6d62018-10-03 23:07:47 +0200728 if (worker_try_slotmap(worker) >= 0)
729 res = ResultCode_ok;
730 else
Harald Welte3e689872018-09-24 14:52:56 +0200731 res = ResultCode_cardNotPresent;
Harald Weltecce2aad2018-08-16 14:44:37 +0200732
Harald Welte3e689872018-09-24 14:52:56 +0200733 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
Harald Welte1f699b42019-03-28 13:41:08 +0100734 rc = worker_send_rspro(worker, resp);
735 if (rc < 0)
736 return rc;
737
738 if (res == ResultCode_ok)
739 rc = worker_send_atr(worker);
740
741 return rc;
Harald Welte458e01b2019-03-10 11:14:43 +0100742
743respond_and_err:
744 if (res) {
745 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
746 worker_send_rspro(worker, resp);
747 }
748 return rc;
Harald Weltecce2aad2018-08-16 14:44:37 +0200749}
750
Harald Welte796a7492018-09-23 19:31:28 +0200751static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
752{
753 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
Harald Welte796a7492018-09-23 19:31:28 +0200754 uint8_t rx_buf[1024];
755 DWORD rx_buf_len = sizeof(rx_buf);
756 RsproPDU_t *pdu_resp;
Harald Weltee1d32892019-03-27 20:47:42 +0100757 struct client_slot clslot;
758 struct bank_slot bslot;
Harald Welte297d72e2019-03-28 18:42:35 +0100759 int rc;
Harald Welte796a7492018-09-23 19:31:28 +0200760
Harald Welte9f7ca612021-12-08 15:29:28 +0100761 LOGW(worker, "Rx RSPRO tpduModemToCard(%s)\n",
762 osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
Harald Welte796a7492018-09-23 19:31:28 +0200763
764 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
765 LOGW(worker, "Unexpected tpduModemToCaard\n");
766 return -104;
767 }
768
Harald Weltee1d32892019-03-27 20:47:42 +0100769 /* Validate that toBankSlot / fromClientSlot match our expectations */
770 rspro2client_slot(&clslot, &mdm2sim->fromClientSlot);
771 rspro2bank_slot(&bslot, &mdm2sim->toBankSlot);
772 if (!bank_slot_equals(&worker->slot, &bslot)) {
773 LOGW(worker, "Unexpected BankSlot %u:%u in tpduModemToCard\n",
774 bslot.bank_id, bslot.slot_nr);
775 return -105;
776 }
777 if (!client_slot_equals(&worker->client.clslot, &clslot)) {
778 LOGW(worker, "Unexpected ClientSlot %u:%u in tpduModemToCard\n",
779 clslot.client_id, clslot.slot_nr);
780 return -106;
781 }
Harald Welte796a7492018-09-23 19:31:28 +0200782
Harald Welte297d72e2019-03-28 18:42:35 +0100783 rc = worker->ops->transceive(worker, mdm2sim->data.buf, mdm2sim->data.size,
784 rx_buf, &rx_buf_len);
785 if (rc < 0)
786 return rc;
Harald Welte796a7492018-09-23 19:31:28 +0200787
Harald Welte001884c2022-07-11 23:38:48 +0200788 LOGW(worker, "Tx RSPRO tpduCardToModem(%s)\n", osmo_hexdump_nospc(rx_buf, rx_buf_len));
Harald Welte796a7492018-09-23 19:31:28 +0200789 /* encode response PDU and send it */
790 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
791 rx_buf, rx_buf_len);
792 worker_send_rspro(worker, pdu_resp);
793
James Tavares31e8bd72022-11-14 17:19:10 -0500794 /* trace APDU to GSMTAP, if configured */
795 if (g_bankd->cfg.gsmtap_host && (g_bankd->cfg.gsmtap_slot == -1 ||
796 g_bankd->cfg.gsmtap_slot == worker->slot.slot_nr)) {
797 bankd_gsmtap_send_apdu(GSMTAP_SIM_APDU, mdm2sim->data.buf, mdm2sim->data.size, rx_buf,
798 rx_buf_len);
799 }
Harald Welte796a7492018-09-23 19:31:28 +0200800 return 0;
Harald Welte796a7492018-09-23 19:31:28 +0200801}
802
Harald Weltebbd18bd2019-12-16 13:11:50 +0100803static int worker_handle_clientSlotStatusInd(struct bankd_worker *worker, const RsproPDU_t *pdu)
804{
805 const struct ClientSlotStatusInd *cssi = &pdu->msg.choice.clientSlotStatusInd;
806 const struct SlotPhysStatus *sps = &cssi->slotPhysStatus;
807 int rc = 0;
808
Harald Welte9f7ca612021-12-08 15:29:28 +0100809 LOGW(worker, "Rx RSPRO clientSlotStatusInd(RST=%s, VCC=%s, CLK=%s)\n",
Harald Weltebbd18bd2019-12-16 13:11:50 +0100810 sps->resetActive ? "ACTIVE" : "INACTIVE",
811 sps->vccPresent ? *sps->vccPresent ? "PRESENT" : "ABSENT" : "NULL",
812 sps->clkActive ? *sps->clkActive ? "ACTIVE" : "INACTIVE" : "NULL");
813
814 /* perform cold or warm reset */
James Tavaresf74d1da2022-11-14 00:21:12 -0500815 if (sps->vccPresent && *sps->vccPresent == 0) {
816 /* VCC is not present */
817
818 if (worker->last_vccPresent) {
819 /* falling edge detected on VCC; perform cold reset */
820 rc = worker->ops->reset_card(worker, true);
821 }
822 } else if (sps->resetActive) {
823 if (!worker->last_resetActive) {
824 /* VCC is present (or not reported) and rising edge detected on reset; perform warm reset */
825 rc = worker->ops->reset_card(worker, false);
826 }
827 }
828
829 /* update last known states */
830 if (sps->vccPresent) {
831 worker->last_vccPresent = *sps->vccPresent != 0;
832 }
833
834 worker->last_resetActive = sps->resetActive != 0;
Harald Weltebbd18bd2019-12-16 13:11:50 +0100835
836 return rc;
837}
838
Harald Welte77911b02018-08-14 23:47:30 +0200839/* handle one incoming RSPRO message from a client inside a worker thread */
840static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
841{
Harald Weltecce2aad2018-08-16 14:44:37 +0200842 int rc = -100;
843
Harald Welte77911b02018-08-14 23:47:30 +0200844 switch (pdu->msg.present) {
845 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200846 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200847 break;
848 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200849 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200850 break;
851 case RsproPDUchoice_PR_clientSlotStatusInd:
Harald Weltebbd18bd2019-12-16 13:11:50 +0100852 rc = worker_handle_clientSlotStatusInd(worker, pdu);
Harald Welte24a3e322019-03-31 13:08:30 +0200853 rc = 0;
854 break;
855 case RsproPDUchoice_PR_setAtrRes:
Harald Welte9f7ca612021-12-08 15:29:28 +0100856 LOGW(worker, "Rx RSPRO %s\n", rspro_msgt_name(pdu));
Harald Welte24a3e322019-03-31 13:08:30 +0200857 rc = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200858 break;
859 default:
Harald Welte9f7ca612021-12-08 15:29:28 +0100860 LOGW(worker, "Rx RSPRO %s (unhandled)\n", rspro_msgt_name(pdu));
Harald Weltecce2aad2018-08-16 14:44:37 +0200861 rc = -101;
862 break;
Harald Welte77911b02018-08-14 23:47:30 +0200863 }
864
James Tavares2c0a5122022-11-13 23:22:22 -0500865 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200866}
867
Harald Welte694df832018-10-03 22:47:52 +0200868static int wait_for_fd_or_timeout(int fd, unsigned int timeout_secs)
869{
870 struct timeval tout = { timeout_secs, 0 };
871 fd_set readset;
872
873 FD_ZERO(&readset);
874 FD_SET(fd, &readset);
875 return select(fd + 1, &readset, NULL, NULL, timeout_secs ? &tout : NULL);
876}
877
Harald Welte77911b02018-08-14 23:47:30 +0200878/* body of the main transceive loop */
879static int worker_transceive_loop(struct bankd_worker *worker)
880{
881 struct ipaccess_head *hh;
882 struct ipaccess_head_ext *hh_ext;
883 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
884 asn_dec_rval_t rval;
885 int data_len, rc;
Harald Welte9ebbacc2018-09-24 17:43:39 +0200886 RsproPDU_t *pdu = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200887
Harald Welte00a96732019-03-11 17:18:02 +0100888restart_wait:
Harald Welte694df832018-10-03 22:47:52 +0200889 rc = wait_for_fd_or_timeout(worker->client.fd, worker->timeout);
Harald Welte00a96732019-03-11 17:18:02 +0100890 if (rc == -1 && errno == EINTR) {
891 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
892 return -23;
Harald Welte0fd77a52019-12-05 22:05:39 +0100893 else
894 worker_try_slotmap(worker);
Harald Welte00a96732019-03-11 17:18:02 +0100895 goto restart_wait;
896 } else if (rc < 0)
897 return rc;
898 else if (rc == 0) {
Harald Welte694df832018-10-03 22:47:52 +0200899 /* TIMEOUT case */
Harald Welte150d6d62018-10-03 23:07:47 +0200900 switch (worker->state) {
901 case BW_ST_CONN_CLIENT_WAIT_MAP:
902 /* re-check if mapping exists meanwhile? */
Harald Welte1f699b42019-03-28 13:41:08 +0100903 rc = worker_try_slotmap(worker);
Harald Welte150d6d62018-10-03 23:07:47 +0200904 break;
905 case BW_ST_CONN_CLIENT_MAPPED:
906 /* re-check if reader/card can be opened meanwhile? */
Harald Welte1f699b42019-03-28 13:41:08 +0100907 rc = worker_open_card(worker);
Harald Welte150d6d62018-10-03 23:07:47 +0200908 break;
909 default:
910 OSMO_ASSERT(0);
911 }
Harald Welte1f699b42019-03-28 13:41:08 +0100912 if (rc == 0)
913 worker_send_atr(worker);
Harald Welte150d6d62018-10-03 23:07:47 +0200914 /* return early, so we do another select rather than the blocking read below */
Harald Welte694df832018-10-03 22:47:52 +0200915 return 0;
916 };
917
Harald Welte77911b02018-08-14 23:47:30 +0200918 /* 1) blocking read of entire IPA message from the socket */
Harald Welte00a96732019-03-11 17:18:02 +0100919 rc = blocking_ipa_read(worker, buf, sizeof(buf));
Harald Welte77911b02018-08-14 23:47:30 +0200920 if (rc < 0)
921 return rc;
922 data_len = rc;
923
924 hh = (struct ipaccess_head *) buf;
Harald Welte5a3613a2018-10-11 12:56:21 +0200925 if (hh->proto != IPAC_PROTO_OSMO && hh->proto != IPAC_PROTO_IPACCESS) {
Harald Weltee1176cf2018-09-24 14:54:58 +0200926 LOGW(worker, "Received unsupported IPA protocol != OSMO: 0x%02x\n", hh->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200927 return -4;
Harald Weltee1176cf2018-09-24 14:54:58 +0200928 }
Harald Welte77911b02018-08-14 23:47:30 +0200929
Harald Welte5a3613a2018-10-11 12:56:21 +0200930 if (hh->proto == IPAC_PROTO_IPACCESS) {
Harald Welte19f881a2019-03-11 18:39:13 +0100931 switch (hh->data[0]) {
932 case IPAC_MSGT_PING:
933 return ipa_ccm_send_pong(worker->client.fd);
Harald Welte667d6942019-12-01 22:34:21 +0100934 case IPAC_MSGT_ID_ACK:
935 return ipa_ccm_send_id_ack(g_worker->client.fd);
Harald Welte19f881a2019-03-11 18:39:13 +0100936 default:
937 LOGW(worker, "IPA CCM 0x%02x not implemented yet\n", hh->data[0]);
938 break;
939 }
Harald Welte5a3613a2018-10-11 12:56:21 +0200940 return 0;
941 }
942
Harald Welte77911b02018-08-14 23:47:30 +0200943 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
Harald Weltee1176cf2018-09-24 14:54:58 +0200944 if (data_len < sizeof(*hh_ext)) {
945 LOGW(worker, "Received short message\n");
Harald Welte77911b02018-08-14 23:47:30 +0200946 return -5;
Harald Weltee1176cf2018-09-24 14:54:58 +0200947 }
Harald Welte77911b02018-08-14 23:47:30 +0200948 data_len -= sizeof(*hh_ext);
Harald Weltee1176cf2018-09-24 14:54:58 +0200949 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO) {
950 LOGW(worker, "Received unsupported IPA EXT protocol != RSPRO: 0x%02x\n", hh_ext->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200951 return -6;
Harald Weltee1176cf2018-09-24 14:54:58 +0200952 }
Harald Welte77911b02018-08-14 23:47:30 +0200953
954 /* 2) ASN1 BER decode of the message */
955 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
Harald Weltee1176cf2018-09-24 14:54:58 +0200956 if (rval.code != RC_OK) {
957 LOGW(worker, "Error during BER decode of RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200958 return -7;
Harald Weltee1176cf2018-09-24 14:54:58 +0200959 }
Harald Welte77911b02018-08-14 23:47:30 +0200960
961 /* 3) handling of the message, possibly resulting in PCSC commands */
962 rc = worker_handle_rspro(worker, pdu);
963 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Weltee1176cf2018-09-24 14:54:58 +0200964 if (rc < 0) {
965 LOGW(worker, "Error handling RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200966 return rc;
Harald Weltee1176cf2018-09-24 14:54:58 +0200967 }
Harald Welte77911b02018-08-14 23:47:30 +0200968
969 /* everything OK if we reach here */
970 return 0;
971}
972
Harald Welted6dfb8c2018-08-16 14:46:53 +0200973/* obtain an ascii representation of the client IP/port */
974static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
975{
976 char hostbuf[32], portbuf[32];
977 int rc;
978
979 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
980 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
981 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
982 if (rc != 0) {
983 out[0] = '\0';
984 return -1;
985 }
986 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
987 return 0;
988}
989
Harald Welte77911b02018-08-14 23:47:30 +0200990/* worker thread main function */
991static void *worker_main(void *arg)
992{
Harald Welte77911b02018-08-14 23:47:30 +0200993 void *top_ctx;
994 int rc;
Harald Welte31c9eca2018-10-03 21:03:34 +0200995
Harald Welte00a96732019-03-11 17:18:02 +0100996 g_worker = (struct bankd_worker *) arg;
997
Harald Welte00a96732019-03-11 17:18:02 +0100998 worker_set_state(g_worker, BW_ST_INIT);
Harald Welte8d858292018-08-15 23:36:46 +0200999
Harald Welte77911b02018-08-14 23:47:30 +02001000 /* not permitted in multithreaded environment */
1001 talloc_disable_null_tracking();
Harald Welte25075972019-03-11 17:33:17 +01001002 g_worker->tall_ctx = talloc_named_const(NULL, 0, "top");
1003 talloc_asn1_ctx = talloc_named_const(g_worker->tall_ctx, 0, "asn1");
Harald Welte77911b02018-08-14 23:47:30 +02001004
Harald Welte286a2be2019-03-11 17:36:58 +01001005 /* set the thread name */
1006 g_worker->name = talloc_asprintf(g_worker->tall_ctx, "bankd-worker(%u)", g_worker->num);
1007 pthread_setname_np(pthread_self(), g_worker->name);
1008
Harald Welte77911b02018-08-14 23:47:30 +02001009 /* push cleanup helper */
Harald Welte00a96732019-03-11 17:18:02 +01001010 pthread_cleanup_push(&worker_cleanup, g_worker);
Harald Welte77911b02018-08-14 23:47:30 +02001011
Harald Welte602b6f72019-12-04 21:51:02 +01001012 g_worker->slot.bank_id = 0xffff;
1013 g_worker->slot.slot_nr = 0xffff;
1014
Harald Welte77911b02018-08-14 23:47:30 +02001015 /* we continuously perform the same loop here, recycling the worker thread
1016 * once the client connection is gone or we have some trouble with the card/reader */
1017 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +02001018 char buf[128];
1019
Harald Welte00a96732019-03-11 17:18:02 +01001020 g_worker->client.peer_addr_len = sizeof(g_worker->client.peer_addr);
Harald Welte77911b02018-08-14 23:47:30 +02001021
Harald Welte00a96732019-03-11 17:18:02 +01001022 worker_set_state(g_worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +02001023 /* first wait for an incoming TCP connection */
Harald Welte00a96732019-03-11 17:18:02 +01001024 rc = accept(g_worker->bankd->accept_fd, (struct sockaddr *) &g_worker->client.peer_addr,
1025 &g_worker->client.peer_addr_len);
Harald Welte77911b02018-08-14 23:47:30 +02001026 if (rc < 0) {
1027 continue;
1028 }
Harald Welte00a96732019-03-11 17:18:02 +01001029 g_worker->client.fd = rc;
1030 worker_client_addrstr(buf, sizeof(buf), g_worker);
1031 LOGW(g_worker, "Accepted connection from %s\n", buf);
1032 worker_set_state(g_worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +02001033
1034 /* run the main worker transceive loop body until there was some error */
1035 while (1) {
Harald Welte00a96732019-03-11 17:18:02 +01001036 rc = worker_transceive_loop(g_worker);
Harald Welte77911b02018-08-14 23:47:30 +02001037 if (rc < 0)
1038 break;
Harald Welte653d6a02019-03-11 18:38:44 +01001039 if (g_worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
1040 break;
Harald Welte77911b02018-08-14 23:47:30 +02001041 }
1042
Harald Weltef4be5e12022-07-24 13:36:46 +02001043 if (rc == -23)
1044 LOGW(g_worker, "Client unmapped: Cleaning up state\n");
1045 else
1046 LOGW(g_worker, "Error %d occurred: Cleaning up state\n", rc);
Harald Welted6dfb8c2018-08-16 14:46:53 +02001047
Harald Welte77911b02018-08-14 23:47:30 +02001048 /* clean-up: reset to sane state */
Harald Welte1f699b42019-03-28 13:41:08 +01001049 memset(&g_worker->card, 0, sizeof(g_worker->card));
Harald Welte297d72e2019-03-28 18:42:35 +01001050 g_worker->ops->cleanup(g_worker);
Harald Welte00a96732019-03-11 17:18:02 +01001051 if (g_worker->reader.name)
1052 g_worker->reader.name = NULL;
1053 if (g_worker->client.fd >= 0)
1054 close(g_worker->client.fd);
1055 memset(&g_worker->client.peer_addr, 0, sizeof(g_worker->client.peer_addr));
1056 g_worker->client.fd = -1;
1057 g_worker->client.clslot.client_id = g_worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +02001058 }
1059
1060 pthread_cleanup_pop(1);
1061 talloc_free(top_ctx);
1062 pthread_exit(NULL);
1063}