blob: e002b948df807efd6c75af3694a9b99d449d7470 [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"
James Tavarese206e6a2022-11-15 08:04:03 -0500304" -L --disable-color Disable colors for logging to stderr\n"
Harald Welte5bae20b2019-04-01 09:36:42 +0200305 );
306}
307
308static int g_bind_port = 9999;
309static char *g_bind_ip = NULL;
Harald Welte00a96732019-03-11 17:18:02 +0100310
Harald Weltef8c6eeb2021-12-08 20:33:00 +0100311static void handle_options(int argc, char **argv)
Harald Welte707c85a2019-03-09 12:56:35 +0100312{
Harald Welte5bae20b2019-04-01 09:36:42 +0200313 while (1) {
314 int option_index = 0, c;
315 static const struct option long_options[] = {
316 { "help", 0, 0, 'h' },
Harald Weltecd7fcd72019-12-03 21:29:07 +0100317 { "version", 0, 0, 'V' },
Harald Welte80a01102020-05-25 14:55:12 +0200318 { "debug", 1, 0, 'd' },
Harald Welte5bae20b2019-04-01 09:36:42 +0200319 { "server-host", 1, 0, 'i' },
320 { "server-port", 1, 0, 'p' },
321 { "bank-id", 1, 0, 'b' },
Harald Welte2513d812019-04-01 21:03:02 +0200322 { "num-slots", 1, 0, 'n' },
Harald Welte5bae20b2019-04-01 09:36:42 +0200323 { "component-name", 1, 0, 'N' },
324 { "bind-ip", 1, 0, 'I' },
325 { "bind-port", 1, 0, 'P' },
Harald Welte628672b2022-07-13 15:20:13 +0200326 { "permit-shared-pcsc", 0, 0, 's' },
James Tavares31e8bd72022-11-14 17:19:10 -0500327 { "gsmtap-ip", 1, 0, 'g' },
328 { "gsmtap-slot", 1, 0, 'G' },
James Tavarese206e6a2022-11-15 08:04:03 -0500329 { "disable-color", 0, 0, 'L' },
Harald Welte5bae20b2019-04-01 09:36:42 +0200330 { 0, 0, 0, 0 }
331 };
332
James Tavarese206e6a2022-11-15 08:04:03 -0500333 c = getopt_long(argc, argv, "hVd:i:p:b:n:N:I:P:sg:G:L", long_options, &option_index);
Harald Welte5bae20b2019-04-01 09:36:42 +0200334 if (c == -1)
335 break;
336
337 switch (c) {
338 case 'h':
339 printf_help();
340 exit(0);
341 break;
Harald Weltecd7fcd72019-12-03 21:29:07 +0100342 case 'V':
343 printf("osmo-remsim-bankd version %s\n", VERSION);
344 exit(0);
345 break;
Harald Welte80a01102020-05-25 14:55:12 +0200346 case 'd':
347 log_parse_category_mask(osmo_stderr_target, optarg);
348 break;
Harald Welte5bae20b2019-04-01 09:36:42 +0200349 case 'i':
350 g_bankd->srvc.server_host = optarg;
351 break;
352 case 'p':
353 g_bankd->srvc.server_port = atoi(optarg);
354 break;
355 case 'b':
Harald Welte2513d812019-04-01 21:03:02 +0200356 g_bankd->srvc.bankd.bank_id = atoi(optarg);
357 break;
358 case 'n':
359 g_bankd->srvc.bankd.num_slots = atoi(optarg);
Harald Welte5bae20b2019-04-01 09:36:42 +0200360 break;
361 case 'N':
362 OSMO_STRLCPY_ARRAY(g_bankd->srvc.own_comp_id.name, optarg);
363 break;
364 case 'I':
365 g_bind_ip = optarg;
366 break;
367 case 'P':
368 g_bind_port = atoi(optarg);
369 break;
Harald Welte628672b2022-07-13 15:20:13 +0200370 case 's':
371 g_bankd->cfg.permit_shared_pcsc = true;
372 break;
James Tavares31e8bd72022-11-14 17:19:10 -0500373 case 'g':
374 g_bankd->cfg.gsmtap_host = optarg;
375 break;
376 case 'G':
377 g_bankd->cfg.gsmtap_slot = atoi(optarg);
378 break;
James Tavarese206e6a2022-11-15 08:04:03 -0500379 case 'L':
380 log_set_use_color(osmo_stderr_target, 0);
381 break;
Harald Welte5bae20b2019-04-01 09:36:42 +0200382 }
383 }
Harald Welte707c85a2019-03-09 12:56:35 +0100384}
385
Harald Welte77911b02018-08-14 23:47:30 +0200386int main(int argc, char **argv)
387{
Harald Weltef4b16f12019-03-09 20:58:17 +0100388 struct rspro_server_conn *srvc;
Harald Welte77911b02018-08-14 23:47:30 +0200389 int i, rc;
390
Harald Weltef4b16f12019-03-09 20:58:17 +0100391 g_bankd = talloc_zero(NULL, struct bankd);
392 OSMO_ASSERT(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200393
Harald Welteeea631b2022-05-03 15:14:19 +0200394 if (gethostname(g_hostname, sizeof(g_hostname)) < 0)
395 OSMO_STRLCPY_ARRAY(g_hostname, "unknown");
396
Harald Weltef4b16f12019-03-09 20:58:17 +0100397 bankd_init(g_bankd);
398
399 srvc = &g_bankd->srvc;
Harald Welte707c85a2019-03-09 12:56:35 +0100400 srvc->server_host = "localhost";
401 srvc->server_port = 9998;
402 srvc->handle_rx = bankd_srvc_handle_rx;
403 srvc->own_comp_id.type = ComponentType_remsimBankd;
Harald Welteeea631b2022-05-03 15:14:19 +0200404 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.name, g_hostname);
Harald Welte707c85a2019-03-09 12:56:35 +0100405 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.software, "remsim-bankd");
406 OSMO_STRLCPY_ARRAY(srvc->own_comp_id.sw_version, PACKAGE_VERSION);
407
408 handle_options(argc, argv);
409
Harald Welte25075972019-03-11 17:33:17 +0100410 g_bankd->main = pthread_self();
Harald Welte00a96732019-03-11 17:18:02 +0100411 signal(SIGMAPDEL, handle_sig_mapdel);
Harald Welte0fd77a52019-12-05 22:05:39 +0100412 signal(SIGMAPADD, handle_sig_mapadd);
Harald Welte25075972019-03-11 17:33:17 +0100413 signal(SIGUSR1, handle_sig_usr1);
Harald Welte00a96732019-03-11 17:18:02 +0100414
Harald Weltee89fecd2019-04-04 09:23:13 +0200415 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
416 * read once during bankd initialization, when the worker threads haven't
417 * started yet */
Harald Weltee9e505c2022-05-03 11:58:01 +0200418 rc = bankd_pcsc_read_slotnames(g_bankd, "bankd_pcsc_slots.csv");
419 if (rc)
420 exit(1);
Harald Weltee89fecd2019-04-04 09:23:13 +0200421
Harald Welte707c85a2019-03-09 12:56:35 +0100422 /* Connection towards remsim-server */
Harald Weltef4b16f12019-03-09 20:58:17 +0100423 rc = server_conn_fsm_alloc(g_bankd, srvc);
Harald Welte707c85a2019-03-09 12:56:35 +0100424 if (rc < 0) {
425 fprintf(stderr, "Unable to create Server conn FSM: %s\n", strerror(errno));
426 exit(1);
427 }
Harald Welted2192e22019-11-07 18:10:57 +0100428 osmo_fsm_inst_dispatch(srvc->fi, SRVC_E_ESTABLISH, NULL);
Harald Welte707c85a2019-03-09 12:56:35 +0100429
430 /* create listening socket for inbound client connections */
Harald Welte5bae20b2019-04-01 09:36:42 +0200431 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 +0200432 if (rc < 0) {
433 fprintf(stderr, "Unable to create TCP socket at %s:%d: %s\n",
434 g_bind_ip ? g_bind_ip : "INADDR_ANY", g_bind_port, strerror(errno));
Harald Welte12534e72018-08-15 23:37:29 +0200435 exit(1);
Harald Weltee9e505c2022-05-03 11:58:01 +0200436 }
Harald Weltef4b16f12019-03-09 20:58:17 +0100437 g_bankd->accept_fd = rc;
Harald Welte12534e72018-08-15 23:37:29 +0200438
James Tavares31e8bd72022-11-14 17:19:10 -0500439 /* initialize gsmtap, if required */
440 if (g_bankd->cfg.gsmtap_host) {
441 rc = bankd_gsmtap_init(g_bankd->cfg.gsmtap_host);
442 if (rc < 0) {
443 fprintf(stderr, "Unable to open GSMTAP");
444 exit(1);
445 }
446 }
447
Harald Weltea0f39502019-03-09 20:59:34 +0100448 /* create worker threads: One per reader/slot! */
Harald Welte2513d812019-04-01 21:03:02 +0200449 for (i = 0; i < g_bankd->srvc.bankd.num_slots; i++) {
Harald Welte77911b02018-08-14 23:47:30 +0200450 struct bankd_worker *w;
Harald Weltef4b16f12019-03-09 20:58:17 +0100451 w = bankd_create_worker(g_bankd, i);
Harald Weltee9e505c2022-05-03 11:58:01 +0200452 if (!w) {
453 fprintf(stderr, "Error creating bankd worker thread\n");
Harald Welte77911b02018-08-14 23:47:30 +0200454 exit(21);
Harald Weltee9e505c2022-05-03 11:58:01 +0200455 }
Harald Welte77911b02018-08-14 23:47:30 +0200456 }
457
458 while (1) {
459 if (terminate)
460 break;
Harald Welte707c85a2019-03-09 12:56:35 +0100461 osmo_select_main(0);
Harald Welte77911b02018-08-14 23:47:30 +0200462 }
463
Harald Weltef4b16f12019-03-09 20:58:17 +0100464 talloc_free(g_bankd);
Harald Welte77911b02018-08-14 23:47:30 +0200465 exit(0);
466}
467
468
469
470/***********************************************************************
471 * bankd worker thread
472 ***********************************************************************/
473
Harald Welte00a96732019-03-11 17:18:02 +0100474static __thread struct bankd_worker *g_worker;
475
Harald Welte8d858292018-08-15 23:36:46 +0200476struct value_string worker_state_names[] = {
477 { BW_ST_INIT, "INIT" },
478 { BW_ST_ACCEPTING, "ACCEPTING" },
479 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
480 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200481 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200482 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
483 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
Harald Welte00a96732019-03-11 17:18:02 +0100484 { BW_ST_CONN_CLIENT_UNMAPPED, "CONN_CLIENT_UNMAPPED" },
Harald Welte8d858292018-08-15 23:36:46 +0200485 { 0, NULL }
486};
487
Harald Welte1f699b42019-03-28 13:41:08 +0100488static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu);
489
Harald Welte8d858292018-08-15 23:36:46 +0200490static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
491{
492 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
493 worker->state = new_state;
Harald Welte150d6d62018-10-03 23:07:47 +0200494 worker->timeout = 0;
495}
496
497static void worker_set_state_timeout(struct bankd_worker *worker, enum bankd_worker_state new_state,
498 unsigned int timeout_secs)
499{
500 LOGW(worker, "Changing state to %s (timeout=%u)\n",
501 get_value_string(worker_state_names, new_state), timeout_secs);
502 worker->state = new_state;
503 worker->timeout = timeout_secs;
Harald Welte8d858292018-08-15 23:36:46 +0200504}
Harald Welte77911b02018-08-14 23:47:30 +0200505
Harald Welte00a96732019-03-11 17:18:02 +0100506/* signal handler for receiving SIGMAPDEL from main thread */
507static void handle_sig_mapdel(int sig)
508{
509 LOGW(g_worker, "SIGMAPDEL received: Main thread informs us our map is gone\n");
510 OSMO_ASSERT(sig == SIGMAPDEL);
Harald Weltea8d945e2019-12-04 22:24:18 +0100511 if (g_worker->state >= BW_ST_CONN_CLIENT_MAPPED) {
512 g_worker->slot.bank_id = 0xffff;
513 g_worker->slot.slot_nr = 0xffff;
514 worker_set_state(g_worker, BW_ST_CONN_CLIENT_UNMAPPED);
515 }
Harald Welte00a96732019-03-11 17:18:02 +0100516}
517
Harald Welte0fd77a52019-12-05 22:05:39 +0100518/* signal handler for receiving SIGMAPADD from main thread */
519static void handle_sig_mapadd(int sig)
520{
521 LOGW(g_worker, "SIGMAPADD received\n");
522 /* do nothing */
523}
524
Harald Welte25075972019-03-11 17:33:17 +0100525static void handle_sig_usr1(int sig)
526{
527 OSMO_ASSERT(sig == SIGUSR1);
528
529 if (pthread_equal(g_bankd->main, pthread_self())) {
530 struct bankd_worker *worker;
531 /* main thread */
532 fprintf(stderr, "=== Talloc Report of main thread:\n");
Harald Welteb54a51e2019-03-31 15:57:59 +0200533 talloc_report_full(g_tall_ctx, stderr);
Harald Welte25075972019-03-11 17:33:17 +0100534
535 /* iterate over worker threads and ask them to dump their talloc state */
536 pthread_mutex_lock(&g_bankd->workers_mutex);
537 llist_for_each_entry(worker, &g_bankd->workers, list) {
538 pthread_kill(worker->thread, SIGUSR1);
539 }
540 pthread_mutex_unlock(&g_bankd->workers_mutex);
541 } else {
542 /* worker thread */
543 fprintf(stderr, "=== Talloc Report of %s\n", g_worker->name);
Harald Welteb54a51e2019-03-31 15:57:59 +0200544 talloc_report_full(g_worker->tall_ctx, stderr);
Harald Welte25075972019-03-11 17:33:17 +0100545 }
546}
547
Harald Welte77911b02018-08-14 23:47:30 +0200548static void worker_cleanup(void *arg)
549{
550 struct bankd_worker *worker = (struct bankd_worker *) arg;
551 struct bankd *bankd = worker->bankd;
552
553 /* FIXME: should we still do this? in the thread ?!? */
554 pthread_mutex_lock(&bankd->workers_mutex);
555 llist_del(&worker->list);
556 talloc_free(worker); /* FIXME: is this safe? */
557 pthread_mutex_unlock(&bankd->workers_mutex);
558}
559
Harald Welteaf614732018-08-17 22:10:05 +0200560static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200561{
Harald Welte297d72e2019-03-28 18:42:35 +0100562 int rc;
Harald Welte77911b02018-08-14 23:47:30 +0200563
Harald Welte150d6d62018-10-03 23:07:47 +0200564 OSMO_ASSERT(worker->state == BW_ST_CONN_CLIENT_MAPPED);
565
Harald Welte694df832018-10-03 22:47:52 +0200566 if (!worker->reader.name) {
567 /* resolve PC/SC reader name from slot_id -> name map */
568 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
569 if (!worker->reader.name) {
570 LOGW(worker, "No PC/SC reader name configured for %u/%u, fix your config\n",
571 worker->slot.bank_id, worker->slot.slot_nr);
Harald Welte297d72e2019-03-28 18:42:35 +0100572 return -1;
Harald Welte694df832018-10-03 22:47:52 +0200573 }
574 }
Harald Welte45c948c2018-09-23 19:26:52 +0200575 OSMO_ASSERT(worker->reader.name);
576
Harald Welte297d72e2019-03-28 18:42:35 +0100577 rc = worker->ops->open_card(worker);
578 if (rc < 0)
579 return rc;
Harald Welte1f699b42019-03-28 13:41:08 +0100580
Harald Welte57593f02018-09-23 19:30:31 +0200581 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
Harald Welte150d6d62018-10-03 23:07:47 +0200582 /* FIXME: notify client about this state change */
Harald Welte57593f02018-09-23 19:30:31 +0200583
Harald Welteaf614732018-08-17 22:10:05 +0200584 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200585}
Harald Welte77911b02018-08-14 23:47:30 +0200586
587
Harald Welte00a96732019-03-11 17:18:02 +0100588static int blocking_ipa_read(struct bankd_worker *worker, uint8_t *buf, unsigned int buf_size)
Harald Welte77911b02018-08-14 23:47:30 +0200589{
590 struct ipaccess_head *hh;
591 uint16_t len;
592 int needed, rc;
593
594 if (buf_size < sizeof(*hh))
595 return -1;
596
597 hh = (struct ipaccess_head *) buf;
598
Harald Welte00a96732019-03-11 17:18:02 +0100599 /* we use 'recv' and not 'read' below, as 'recv' will always fail with -EINTR
600 * in case of a signal being received */
601
602restart_hdr:
603 /* 1) blocking recv from the socket (IPA header) */
604 rc = recv(worker->client.fd, buf, sizeof(*hh), 0);
605 if (rc == -1 && errno == EINTR) {
606 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
607 return -23;
608 goto restart_hdr;
609 } else if (rc < 0)
610 return rc;
611 else if (rc < sizeof(*hh))
Harald Welte77911b02018-08-14 23:47:30 +0200612 return -2;
613
614 len = ntohs(hh->len);
615 needed = len; //- sizeof(*hh);
616
Harald Welte00a96732019-03-11 17:18:02 +0100617restart_body:
618 /* 2) blocking recv from the socket (payload) */
619 rc = recv(worker->client.fd, buf+sizeof(*hh), needed, 0);
620 if (rc == -1 && errno == EINTR) {
621 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
622 return -23;
623 goto restart_body;
624 } else if (rc < 0)
625 return rc;
626 else if (rc < needed)
Harald Welte77911b02018-08-14 23:47:30 +0200627 return -3;
628
629 return len;
630}
631
Harald Welte796a7492018-09-23 19:31:28 +0200632static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
633{
634 struct msgb *msg = rspro_enc_msg(pdu);
635 int rc;
636
637 if (!msg) {
Harald Welte2eee4502019-03-30 08:50:35 +0100638 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Welte796a7492018-09-23 19:31:28 +0200639 LOGW(worker, "error encoding RSPRO\n");
640 return -1;
641 }
642
Harald Weltefd471192018-09-24 14:51:14 +0200643 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200644 /* prepend the header */
645 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200646 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200647
648 /* actually send it through the socket */
649 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
650 if (rc == msgb_length(msg))
651 rc = 0;
652 else {
653 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
654 rc = -1;
655 }
656
657 msgb_free(msg);
658
659 return rc;
660}
661
Harald Welte150d6d62018-10-03 23:07:47 +0200662/* attempt to obtain slot-map */
663static int worker_try_slotmap(struct bankd_worker *worker)
664{
Harald Weltecbd18962019-03-03 19:02:38 +0100665 struct slot_mapping *slmap;
Harald Welte150d6d62018-10-03 23:07:47 +0200666
Harald Weltecbd18962019-03-03 19:02:38 +0100667 slmap = slotmap_by_client(worker->bankd->slotmaps, &worker->client.clslot);
Harald Welte150d6d62018-10-03 23:07:47 +0200668 if (!slmap) {
669 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
670 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
671 /* check in 10s if the map has been installed meanwhile by main thread */
672 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_WAIT_MAP, 10);
673 return -1;
674 } else {
675 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
676 slmap->client.client_id, slmap->client.slot_nr,
677 slmap->bank.bank_id, slmap->bank.slot_nr);
678 worker->slot = slmap->bank;
679 worker_set_state_timeout(worker, BW_ST_CONN_CLIENT_MAPPED, 10);
680 return worker_open_card(worker);
681 }
682}
683
Harald Welte1f699b42019-03-28 13:41:08 +0100684/* inform the remote end (client) about the (new) ATR */
685static int worker_send_atr(struct bankd_worker *worker)
686{
687 RsproPDU_t *set_atr;
688 set_atr = rspro_gen_SetAtrReq(worker->client.clslot.client_id,
689 worker->client.clslot.slot_nr,
690 worker->card.atr, worker->card.atr_len);
James Tavares31e8bd72022-11-14 17:19:10 -0500691
692 /* trace ATR to GSMTAP, if configured */
693 if (g_bankd->cfg.gsmtap_host && (g_bankd->cfg.gsmtap_slot == -1 ||
694 g_bankd->cfg.gsmtap_slot == worker->slot.slot_nr)) {
695 bankd_gsmtap_send_apdu(GSMTAP_SIM_ATR, worker->card.atr, worker->card.atr_len,
696 NULL, 0);
697 }
698
Harald Welte1f699b42019-03-28 13:41:08 +0100699 if (!set_atr)
700 return -1;
701 return worker_send_rspro(worker, set_atr);
702}
Harald Welte150d6d62018-10-03 23:07:47 +0200703
Harald Weltecce2aad2018-08-16 14:44:37 +0200704static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
705{
Harald Welteaf614732018-08-17 22:10:05 +0200706 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
Harald Welte458e01b2019-03-10 11:14:43 +0100707 RsproPDU_t *resp = NULL;
Harald Welte3e689872018-09-24 14:52:56 +0200708 e_ResultCode res;
Harald Welte458e01b2019-03-10 11:14:43 +0100709 int rc;
Harald Welteaf614732018-08-17 22:10:05 +0200710
Harald Weltecce2aad2018-08-16 14:44:37 +0200711 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
712
Harald Welte9f7ca612021-12-08 15:29:28 +0100713 LOGW(worker, "Rx RSPRO connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
Harald Weltecce2aad2018-08-16 14:44:37 +0200714 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
715 /* FIXME: store somewhere? */
716
717 if (worker->state != BW_ST_CONN_WAIT_ID) {
718 LOGW(worker, "Unexpected connectClientReq\n");
Harald Weltea4f19142023-02-03 20:31:52 +0100719 res = ResultCode_illegalClientId;
Harald Welte458e01b2019-03-10 11:14:43 +0100720 rc = -102;
721 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200722 }
723
Harald Welte371d0262018-08-16 15:23:58 +0200724 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200725 LOGW(worker, "missing clientID, aborting\n");
Harald Welte458e01b2019-03-10 11:14:43 +0100726 res = ResultCode_illegalClientId;
727 rc = -103;
728 goto respond_and_err;
Harald Weltecce2aad2018-08-16 14:44:37 +0200729 }
Harald Welte371d0262018-08-16 15:23:58 +0200730 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
731 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200732 worker_set_state(worker, BW_ST_CONN_CLIENT);
733
Harald Welte150d6d62018-10-03 23:07:47 +0200734 if (worker_try_slotmap(worker) >= 0)
735 res = ResultCode_ok;
736 else
Harald Welte3e689872018-09-24 14:52:56 +0200737 res = ResultCode_cardNotPresent;
Harald Weltecce2aad2018-08-16 14:44:37 +0200738
Harald Welte3e689872018-09-24 14:52:56 +0200739 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
Harald Welte1f699b42019-03-28 13:41:08 +0100740 rc = worker_send_rspro(worker, resp);
741 if (rc < 0)
742 return rc;
743
744 if (res == ResultCode_ok)
745 rc = worker_send_atr(worker);
746
747 return rc;
Harald Welte458e01b2019-03-10 11:14:43 +0100748
749respond_and_err:
750 if (res) {
751 resp = rspro_gen_ConnectClientRes(&worker->bankd->comp_id, res);
752 worker_send_rspro(worker, resp);
753 }
754 return rc;
Harald Weltecce2aad2018-08-16 14:44:37 +0200755}
756
Harald Welte796a7492018-09-23 19:31:28 +0200757static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
758{
759 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
Harald Welte796a7492018-09-23 19:31:28 +0200760 uint8_t rx_buf[1024];
761 DWORD rx_buf_len = sizeof(rx_buf);
762 RsproPDU_t *pdu_resp;
Harald Weltee1d32892019-03-27 20:47:42 +0100763 struct client_slot clslot;
764 struct bank_slot bslot;
Harald Welte297d72e2019-03-28 18:42:35 +0100765 int rc;
Harald Welte796a7492018-09-23 19:31:28 +0200766
Harald Welte9f7ca612021-12-08 15:29:28 +0100767 LOGW(worker, "Rx RSPRO tpduModemToCard(%s)\n",
768 osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
Harald Welte796a7492018-09-23 19:31:28 +0200769
770 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
771 LOGW(worker, "Unexpected tpduModemToCaard\n");
772 return -104;
773 }
774
Harald Weltee1d32892019-03-27 20:47:42 +0100775 /* Validate that toBankSlot / fromClientSlot match our expectations */
776 rspro2client_slot(&clslot, &mdm2sim->fromClientSlot);
777 rspro2bank_slot(&bslot, &mdm2sim->toBankSlot);
778 if (!bank_slot_equals(&worker->slot, &bslot)) {
779 LOGW(worker, "Unexpected BankSlot %u:%u in tpduModemToCard\n",
780 bslot.bank_id, bslot.slot_nr);
781 return -105;
782 }
783 if (!client_slot_equals(&worker->client.clslot, &clslot)) {
784 LOGW(worker, "Unexpected ClientSlot %u:%u in tpduModemToCard\n",
785 clslot.client_id, clslot.slot_nr);
786 return -106;
787 }
Harald Welte796a7492018-09-23 19:31:28 +0200788
Harald Welte297d72e2019-03-28 18:42:35 +0100789 rc = worker->ops->transceive(worker, mdm2sim->data.buf, mdm2sim->data.size,
790 rx_buf, &rx_buf_len);
791 if (rc < 0)
792 return rc;
Harald Welte796a7492018-09-23 19:31:28 +0200793
Harald Welte001884c2022-07-11 23:38:48 +0200794 LOGW(worker, "Tx RSPRO tpduCardToModem(%s)\n", osmo_hexdump_nospc(rx_buf, rx_buf_len));
Harald Welte796a7492018-09-23 19:31:28 +0200795 /* encode response PDU and send it */
796 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
797 rx_buf, rx_buf_len);
798 worker_send_rspro(worker, pdu_resp);
799
James Tavares31e8bd72022-11-14 17:19:10 -0500800 /* trace APDU to GSMTAP, if configured */
801 if (g_bankd->cfg.gsmtap_host && (g_bankd->cfg.gsmtap_slot == -1 ||
802 g_bankd->cfg.gsmtap_slot == worker->slot.slot_nr)) {
803 bankd_gsmtap_send_apdu(GSMTAP_SIM_APDU, mdm2sim->data.buf, mdm2sim->data.size, rx_buf,
804 rx_buf_len);
805 }
Harald Welte796a7492018-09-23 19:31:28 +0200806 return 0;
Harald Welte796a7492018-09-23 19:31:28 +0200807}
808
Harald Weltebbd18bd2019-12-16 13:11:50 +0100809static int worker_handle_clientSlotStatusInd(struct bankd_worker *worker, const RsproPDU_t *pdu)
810{
811 const struct ClientSlotStatusInd *cssi = &pdu->msg.choice.clientSlotStatusInd;
812 const struct SlotPhysStatus *sps = &cssi->slotPhysStatus;
813 int rc = 0;
814
Harald Welte9f7ca612021-12-08 15:29:28 +0100815 LOGW(worker, "Rx RSPRO clientSlotStatusInd(RST=%s, VCC=%s, CLK=%s)\n",
Harald Weltebbd18bd2019-12-16 13:11:50 +0100816 sps->resetActive ? "ACTIVE" : "INACTIVE",
817 sps->vccPresent ? *sps->vccPresent ? "PRESENT" : "ABSENT" : "NULL",
818 sps->clkActive ? *sps->clkActive ? "ACTIVE" : "INACTIVE" : "NULL");
819
820 /* perform cold or warm reset */
James Tavaresf74d1da2022-11-14 00:21:12 -0500821 if (sps->vccPresent && *sps->vccPresent == 0) {
822 /* VCC is not present */
823
824 if (worker->last_vccPresent) {
825 /* falling edge detected on VCC; perform cold reset */
826 rc = worker->ops->reset_card(worker, true);
827 }
828 } else if (sps->resetActive) {
829 if (!worker->last_resetActive) {
830 /* VCC is present (or not reported) and rising edge detected on reset; perform warm reset */
831 rc = worker->ops->reset_card(worker, false);
832 }
833 }
834
835 /* update last known states */
836 if (sps->vccPresent) {
837 worker->last_vccPresent = *sps->vccPresent != 0;
838 }
839
840 worker->last_resetActive = sps->resetActive != 0;
Harald Weltebbd18bd2019-12-16 13:11:50 +0100841
842 return rc;
843}
844
Harald Welte77911b02018-08-14 23:47:30 +0200845/* handle one incoming RSPRO message from a client inside a worker thread */
846static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
847{
Harald Weltecce2aad2018-08-16 14:44:37 +0200848 int rc = -100;
849
Harald Welte77911b02018-08-14 23:47:30 +0200850 switch (pdu->msg.present) {
851 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200852 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200853 break;
854 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200855 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200856 break;
857 case RsproPDUchoice_PR_clientSlotStatusInd:
Harald Weltebbd18bd2019-12-16 13:11:50 +0100858 rc = worker_handle_clientSlotStatusInd(worker, pdu);
Harald Welte24a3e322019-03-31 13:08:30 +0200859 rc = 0;
860 break;
861 case RsproPDUchoice_PR_setAtrRes:
Harald Welte9f7ca612021-12-08 15:29:28 +0100862 LOGW(worker, "Rx RSPRO %s\n", rspro_msgt_name(pdu));
Harald Welte24a3e322019-03-31 13:08:30 +0200863 rc = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200864 break;
865 default:
Harald Welte9f7ca612021-12-08 15:29:28 +0100866 LOGW(worker, "Rx RSPRO %s (unhandled)\n", rspro_msgt_name(pdu));
Harald Weltecce2aad2018-08-16 14:44:37 +0200867 rc = -101;
868 break;
Harald Welte77911b02018-08-14 23:47:30 +0200869 }
870
James Tavares2c0a5122022-11-13 23:22:22 -0500871 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200872}
873
Harald Welte694df832018-10-03 22:47:52 +0200874static int wait_for_fd_or_timeout(int fd, unsigned int timeout_secs)
875{
876 struct timeval tout = { timeout_secs, 0 };
877 fd_set readset;
878
879 FD_ZERO(&readset);
880 FD_SET(fd, &readset);
881 return select(fd + 1, &readset, NULL, NULL, timeout_secs ? &tout : NULL);
882}
883
Harald Welte77911b02018-08-14 23:47:30 +0200884/* body of the main transceive loop */
885static int worker_transceive_loop(struct bankd_worker *worker)
886{
887 struct ipaccess_head *hh;
888 struct ipaccess_head_ext *hh_ext;
889 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
890 asn_dec_rval_t rval;
891 int data_len, rc;
Harald Welte9ebbacc2018-09-24 17:43:39 +0200892 RsproPDU_t *pdu = NULL;
Harald Welte77911b02018-08-14 23:47:30 +0200893
Harald Welte00a96732019-03-11 17:18:02 +0100894restart_wait:
Harald Welte694df832018-10-03 22:47:52 +0200895 rc = wait_for_fd_or_timeout(worker->client.fd, worker->timeout);
Harald Welte00a96732019-03-11 17:18:02 +0100896 if (rc == -1 && errno == EINTR) {
897 if (worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
898 return -23;
Harald Welte0fd77a52019-12-05 22:05:39 +0100899 else
900 worker_try_slotmap(worker);
Harald Welte00a96732019-03-11 17:18:02 +0100901 goto restart_wait;
902 } else if (rc < 0)
903 return rc;
904 else if (rc == 0) {
Harald Welte694df832018-10-03 22:47:52 +0200905 /* TIMEOUT case */
Harald Welte150d6d62018-10-03 23:07:47 +0200906 switch (worker->state) {
907 case BW_ST_CONN_CLIENT_WAIT_MAP:
908 /* re-check if mapping exists meanwhile? */
Harald Welte1f699b42019-03-28 13:41:08 +0100909 rc = worker_try_slotmap(worker);
Harald Welte150d6d62018-10-03 23:07:47 +0200910 break;
911 case BW_ST_CONN_CLIENT_MAPPED:
912 /* re-check if reader/card can be opened meanwhile? */
Harald Welte1f699b42019-03-28 13:41:08 +0100913 rc = worker_open_card(worker);
Harald Welte150d6d62018-10-03 23:07:47 +0200914 break;
915 default:
916 OSMO_ASSERT(0);
917 }
Harald Welte1f699b42019-03-28 13:41:08 +0100918 if (rc == 0)
919 worker_send_atr(worker);
Harald Welte150d6d62018-10-03 23:07:47 +0200920 /* return early, so we do another select rather than the blocking read below */
Harald Welte694df832018-10-03 22:47:52 +0200921 return 0;
922 };
923
Harald Welte77911b02018-08-14 23:47:30 +0200924 /* 1) blocking read of entire IPA message from the socket */
Harald Welte00a96732019-03-11 17:18:02 +0100925 rc = blocking_ipa_read(worker, buf, sizeof(buf));
Harald Welte77911b02018-08-14 23:47:30 +0200926 if (rc < 0)
927 return rc;
928 data_len = rc;
929
930 hh = (struct ipaccess_head *) buf;
Harald Welte5a3613a2018-10-11 12:56:21 +0200931 if (hh->proto != IPAC_PROTO_OSMO && hh->proto != IPAC_PROTO_IPACCESS) {
Harald Weltee1176cf2018-09-24 14:54:58 +0200932 LOGW(worker, "Received unsupported IPA protocol != OSMO: 0x%02x\n", hh->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200933 return -4;
Harald Weltee1176cf2018-09-24 14:54:58 +0200934 }
Harald Welte77911b02018-08-14 23:47:30 +0200935
Harald Welte5a3613a2018-10-11 12:56:21 +0200936 if (hh->proto == IPAC_PROTO_IPACCESS) {
Harald Welte19f881a2019-03-11 18:39:13 +0100937 switch (hh->data[0]) {
938 case IPAC_MSGT_PING:
939 return ipa_ccm_send_pong(worker->client.fd);
Harald Welte667d6942019-12-01 22:34:21 +0100940 case IPAC_MSGT_ID_ACK:
941 return ipa_ccm_send_id_ack(g_worker->client.fd);
Harald Welte19f881a2019-03-11 18:39:13 +0100942 default:
943 LOGW(worker, "IPA CCM 0x%02x not implemented yet\n", hh->data[0]);
944 break;
945 }
Harald Welte5a3613a2018-10-11 12:56:21 +0200946 return 0;
947 }
948
Harald Welte77911b02018-08-14 23:47:30 +0200949 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
Harald Weltee1176cf2018-09-24 14:54:58 +0200950 if (data_len < sizeof(*hh_ext)) {
951 LOGW(worker, "Received short message\n");
Harald Welte77911b02018-08-14 23:47:30 +0200952 return -5;
Harald Weltee1176cf2018-09-24 14:54:58 +0200953 }
Harald Welte77911b02018-08-14 23:47:30 +0200954 data_len -= sizeof(*hh_ext);
Harald Weltee1176cf2018-09-24 14:54:58 +0200955 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO) {
956 LOGW(worker, "Received unsupported IPA EXT protocol != RSPRO: 0x%02x\n", hh_ext->proto);
Harald Welte77911b02018-08-14 23:47:30 +0200957 return -6;
Harald Weltee1176cf2018-09-24 14:54:58 +0200958 }
Harald Welte77911b02018-08-14 23:47:30 +0200959
960 /* 2) ASN1 BER decode of the message */
961 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
Harald Weltee1176cf2018-09-24 14:54:58 +0200962 if (rval.code != RC_OK) {
963 LOGW(worker, "Error during BER decode of RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200964 return -7;
Harald Weltee1176cf2018-09-24 14:54:58 +0200965 }
Harald Welte77911b02018-08-14 23:47:30 +0200966
967 /* 3) handling of the message, possibly resulting in PCSC commands */
968 rc = worker_handle_rspro(worker, pdu);
969 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
Harald Weltee1176cf2018-09-24 14:54:58 +0200970 if (rc < 0) {
971 LOGW(worker, "Error handling RSPRO\n");
Harald Welte77911b02018-08-14 23:47:30 +0200972 return rc;
Harald Weltee1176cf2018-09-24 14:54:58 +0200973 }
Harald Welte77911b02018-08-14 23:47:30 +0200974
975 /* everything OK if we reach here */
976 return 0;
977}
978
Harald Welted6dfb8c2018-08-16 14:46:53 +0200979/* obtain an ascii representation of the client IP/port */
980static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
981{
982 char hostbuf[32], portbuf[32];
983 int rc;
984
985 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
986 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
987 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
988 if (rc != 0) {
989 out[0] = '\0';
990 return -1;
991 }
992 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
993 return 0;
994}
995
Harald Welte77911b02018-08-14 23:47:30 +0200996/* worker thread main function */
997static void *worker_main(void *arg)
998{
Harald Welte77911b02018-08-14 23:47:30 +0200999 void *top_ctx;
1000 int rc;
Harald Welte31c9eca2018-10-03 21:03:34 +02001001
Harald Welte00a96732019-03-11 17:18:02 +01001002 g_worker = (struct bankd_worker *) arg;
1003
Harald Welte00a96732019-03-11 17:18:02 +01001004 worker_set_state(g_worker, BW_ST_INIT);
Harald Welte8d858292018-08-15 23:36:46 +02001005
Harald Welte77911b02018-08-14 23:47:30 +02001006 /* not permitted in multithreaded environment */
1007 talloc_disable_null_tracking();
Harald Welte25075972019-03-11 17:33:17 +01001008 g_worker->tall_ctx = talloc_named_const(NULL, 0, "top");
1009 talloc_asn1_ctx = talloc_named_const(g_worker->tall_ctx, 0, "asn1");
Harald Welte77911b02018-08-14 23:47:30 +02001010
Harald Welte286a2be2019-03-11 17:36:58 +01001011 /* set the thread name */
1012 g_worker->name = talloc_asprintf(g_worker->tall_ctx, "bankd-worker(%u)", g_worker->num);
1013 pthread_setname_np(pthread_self(), g_worker->name);
1014
Harald Welte77911b02018-08-14 23:47:30 +02001015 /* push cleanup helper */
Harald Welte00a96732019-03-11 17:18:02 +01001016 pthread_cleanup_push(&worker_cleanup, g_worker);
Harald Welte77911b02018-08-14 23:47:30 +02001017
Harald Welte602b6f72019-12-04 21:51:02 +01001018 g_worker->slot.bank_id = 0xffff;
1019 g_worker->slot.slot_nr = 0xffff;
1020
Harald Welte77911b02018-08-14 23:47:30 +02001021 /* we continuously perform the same loop here, recycling the worker thread
1022 * once the client connection is gone or we have some trouble with the card/reader */
1023 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +02001024 char buf[128];
1025
Harald Welte00a96732019-03-11 17:18:02 +01001026 g_worker->client.peer_addr_len = sizeof(g_worker->client.peer_addr);
Harald Welte77911b02018-08-14 23:47:30 +02001027
Harald Welte00a96732019-03-11 17:18:02 +01001028 worker_set_state(g_worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +02001029 /* first wait for an incoming TCP connection */
Harald Welte00a96732019-03-11 17:18:02 +01001030 rc = accept(g_worker->bankd->accept_fd, (struct sockaddr *) &g_worker->client.peer_addr,
1031 &g_worker->client.peer_addr_len);
Harald Welte77911b02018-08-14 23:47:30 +02001032 if (rc < 0) {
1033 continue;
1034 }
Harald Welte00a96732019-03-11 17:18:02 +01001035 g_worker->client.fd = rc;
1036 worker_client_addrstr(buf, sizeof(buf), g_worker);
1037 LOGW(g_worker, "Accepted connection from %s\n", buf);
1038 worker_set_state(g_worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +02001039
1040 /* run the main worker transceive loop body until there was some error */
1041 while (1) {
Harald Welte00a96732019-03-11 17:18:02 +01001042 rc = worker_transceive_loop(g_worker);
Harald Welte77911b02018-08-14 23:47:30 +02001043 if (rc < 0)
1044 break;
Harald Welte653d6a02019-03-11 18:38:44 +01001045 if (g_worker->state == BW_ST_CONN_CLIENT_UNMAPPED)
1046 break;
Harald Welte77911b02018-08-14 23:47:30 +02001047 }
1048
Harald Weltef4be5e12022-07-24 13:36:46 +02001049 if (rc == -23)
1050 LOGW(g_worker, "Client unmapped: Cleaning up state\n");
1051 else
1052 LOGW(g_worker, "Error %d occurred: Cleaning up state\n", rc);
Harald Welted6dfb8c2018-08-16 14:46:53 +02001053
Harald Welte77911b02018-08-14 23:47:30 +02001054 /* clean-up: reset to sane state */
Harald Welte1f699b42019-03-28 13:41:08 +01001055 memset(&g_worker->card, 0, sizeof(g_worker->card));
Harald Welte297d72e2019-03-28 18:42:35 +01001056 g_worker->ops->cleanup(g_worker);
Harald Welte00a96732019-03-11 17:18:02 +01001057 if (g_worker->reader.name)
1058 g_worker->reader.name = NULL;
1059 if (g_worker->client.fd >= 0)
1060 close(g_worker->client.fd);
1061 memset(&g_worker->client.peer_addr, 0, sizeof(g_worker->client.peer_addr));
1062 g_worker->client.fd = -1;
1063 g_worker->client.clslot.client_id = g_worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +02001064 }
1065
1066 pthread_cleanup_pop(1);
1067 talloc_free(top_ctx);
1068 pthread_exit(NULL);
1069}