blob: bebf521c7407003953cc98e84a9a0608d4203a4b [file] [log] [blame]
Harald Welte77911b02018-08-14 23:47:30 +02001#include <stdio.h>
2#include <stdlib.h>
3#include <stdint.h>
4#include <unistd.h>
5
6#include <pthread.h>
7
8#include <wintypes.h>
9#include <winscard.h>
10#include <pcsclite.h>
11
Harald Welted6dfb8c2018-08-16 14:46:53 +020012#include <sys/socket.h>
13#include <netdb.h>
14
Harald Welte12534e72018-08-15 23:37:29 +020015#include <osmocom/core/socket.h>
Harald Welte77911b02018-08-14 23:47:30 +020016#include <osmocom/core/linuxlist.h>
17
18#include <osmocom/gsm/ipa.h>
19#include <osmocom/gsm/protocol/ipaccess.h>
20
21#include <asn1c/asn_application.h>
22#include <osmocom/rspro/RsproPDU.h>
23
24#include "bankd.h"
Harald Welte796a7492018-09-23 19:31:28 +020025#include "rspro_util.h"
Harald Welte77911b02018-08-14 23:47:30 +020026
27__thread void *talloc_asn1_ctx;
28
29static void *worker_main(void *arg);
30
31/***********************************************************************
32* bankd core / main thread
33***********************************************************************/
34
35static void bankd_init(struct bankd *bankd)
36{
37 /* intialize members of 'bankd' */
38 INIT_LLIST_HEAD(&bankd->slot_mappings);
39 pthread_rwlock_init(&bankd->slot_mappings_rwlock, NULL);
40 INIT_LLIST_HEAD(&bankd->workers);
41 pthread_mutex_init(&bankd->workers_mutex, NULL);
Harald Welte45c948c2018-09-23 19:26:52 +020042
43 /* Np lock or mutex required for the pcsc_slot_names list, as this is only
44 * read once during bankd initialization, when the worker threads haven't
45 * started yet */
46 INIT_LLIST_HEAD(&bankd->pcsc_slot_names);
47 OSMO_ASSERT(bankd_pcsc_read_slotnames(bankd, "bankd_pcsc_slots.csv") == 0);
Harald Welte77911b02018-08-14 23:47:30 +020048}
49
50/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +020051static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +020052{
53 struct bankd_worker *worker;
54 int rc;
55
56 worker = talloc_zero(bankd, struct bankd_worker);
57 if (!worker)
58 return NULL;
59
60 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +020061 worker->num = i;
Harald Welte77911b02018-08-14 23:47:30 +020062
63 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
64
65 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
66 if (rc != 0) {
67 talloc_free(worker);
68 return NULL;
69 }
70
71 pthread_mutex_lock(&bankd->workers_mutex);
72 llist_add_tail(&worker->list, &bankd->workers);
73 pthread_mutex_unlock(&bankd->workers_mutex);
74
75 return worker;
76}
77
78static bool terminate = false;
79
80int main(int argc, char **argv)
81{
82 struct bankd *bankd = talloc_zero(NULL, struct bankd);
83 int i, rc;
84
85 OSMO_ASSERT(bankd);
86 bankd_init(bankd);
87
Harald Welte12534e72018-08-15 23:37:29 +020088 /* create listening socket */
89 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 9999, OSMO_SOCK_F_BIND);
90 if (rc < 0)
91 exit(1);
92 bankd->accept_fd = rc;
93
94 /* create worker threads. FIXME: one per reader/slot! */
Harald Welte77911b02018-08-14 23:47:30 +020095 for (i = 0; i < 10; i++) {
96 struct bankd_worker *w;
Harald Welte8d858292018-08-15 23:36:46 +020097 w = bankd_create_worker(bankd, i);
Harald Welte77911b02018-08-14 23:47:30 +020098 if (!w)
99 exit(21);
100 }
101
102 while (1) {
103 if (terminate)
104 break;
Harald Welte7f684a02018-08-16 14:43:50 +0200105 sleep(1);
Harald Welte77911b02018-08-14 23:47:30 +0200106 }
107
108 talloc_free(bankd);
109 exit(0);
110}
111
112
113
114/***********************************************************************
115 * bankd worker thread
116 ***********************************************************************/
117
Harald Welte8d858292018-08-15 23:36:46 +0200118struct value_string worker_state_names[] = {
119 { BW_ST_INIT, "INIT" },
120 { BW_ST_ACCEPTING, "ACCEPTING" },
121 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
122 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200123 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200124 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
125 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
126 { 0, NULL }
127};
128
Harald Welteceb3e682018-08-16 14:47:11 +0200129#define LOGW(w, fmt, args...) \
130 printf("[%03u %s] %s:%u " fmt, (w)->num, get_value_string(worker_state_names, (w)->state), \
131 __FILE__, __LINE__, ## args)
132
Harald Welteaf614732018-08-17 22:10:05 +0200133#define PCSC_ERROR(w, rv, text) \
134if (rv != SCARD_S_SUCCESS) { \
135 LOGW((w), text ": %s (0x%lX)\n", pcsc_stringify_error(rv), rv); \
136 goto end; \
137} else { \
138 LOGW((w), ": OK\n\n"); \
139}
140
Harald Welte8d858292018-08-15 23:36:46 +0200141static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
142{
143 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
144 worker->state = new_state;
145}
Harald Welte77911b02018-08-14 23:47:30 +0200146
147static void worker_cleanup(void *arg)
148{
149 struct bankd_worker *worker = (struct bankd_worker *) arg;
150 struct bankd *bankd = worker->bankd;
151
152 /* FIXME: should we still do this? in the thread ?!? */
153 pthread_mutex_lock(&bankd->workers_mutex);
154 llist_del(&worker->list);
155 talloc_free(worker); /* FIXME: is this safe? */
156 pthread_mutex_unlock(&bankd->workers_mutex);
157}
158
159
Harald Welteaf614732018-08-17 22:10:05 +0200160static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200161{
Harald Welteaf614732018-08-17 22:10:05 +0200162 long rc;
Harald Welte77911b02018-08-14 23:47:30 +0200163
Harald Welte45c948c2018-09-23 19:26:52 +0200164 /* resolve PC/SC reader name from slot_id -> name map */
165 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
166 OSMO_ASSERT(worker->reader.name);
167
168 LOGW(worker, "Attempting to open card/slot '%s'\n", worker->reader.name);
169
Harald Welte77911b02018-08-14 23:47:30 +0200170 /* The PC/SC context must be created inside the thread where we'll later use it */
171 rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &worker->reader.pcsc.hContext);
Harald Welteaf614732018-08-17 22:10:05 +0200172 PCSC_ERROR(worker, rc, "SCardEstablishContext")
Harald Welte77911b02018-08-14 23:47:30 +0200173
Harald Welte48865c22018-09-23 19:30:07 +0200174 DWORD dwActiveProtocol;
Harald Welte77911b02018-08-14 23:47:30 +0200175 rc = SCardConnect(worker->reader.pcsc.hContext, worker->reader.name, SCARD_SHARE_SHARED,
Harald Welte48865c22018-09-23 19:30:07 +0200176 SCARD_PROTOCOL_T0, &worker->reader.pcsc.hCard, &dwActiveProtocol);
Harald Welteaf614732018-08-17 22:10:05 +0200177 PCSC_ERROR(worker, rc, "SCardConnect")
Harald Welte77911b02018-08-14 23:47:30 +0200178
Harald Welte57593f02018-09-23 19:30:31 +0200179 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
180
Harald Welteaf614732018-08-17 22:10:05 +0200181 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200182end:
Harald Welteaf614732018-08-17 22:10:05 +0200183 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200184}
Harald Welte77911b02018-08-14 23:47:30 +0200185
186
187static int blocking_ipa_read(int fd, uint8_t *buf, unsigned int buf_size)
188{
189 struct ipaccess_head *hh;
190 uint16_t len;
191 int needed, rc;
192
193 if (buf_size < sizeof(*hh))
194 return -1;
195
196 hh = (struct ipaccess_head *) buf;
197
198 /* 1) blocking read from the socket (IPA header) */
199 rc = read(fd, buf, sizeof(*hh));
200 if (rc < sizeof(*hh))
201 return -2;
202
203 len = ntohs(hh->len);
204 needed = len; //- sizeof(*hh);
205
206 /* 2) blocking read from the socket (payload) */
207 rc = read(fd, buf+sizeof(*hh), needed);
208 if (rc < needed)
209 return -3;
210
211 return len;
212}
213
Harald Welte796a7492018-09-23 19:31:28 +0200214static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
215{
216 struct msgb *msg = rspro_enc_msg(pdu);
217 int rc;
218
219 if (!msg) {
220 LOGW(worker, "error encoding RSPRO\n");
221 return -1;
222 }
223
224 /* prepend the header */
225 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
226
227 /* actually send it through the socket */
228 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
229 if (rc == msgb_length(msg))
230 rc = 0;
231 else {
232 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
233 rc = -1;
234 }
235
236 msgb_free(msg);
237
238 return rc;
239}
240
Harald Weltecce2aad2018-08-16 14:44:37 +0200241static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
242{
Harald Welteaf614732018-08-17 22:10:05 +0200243 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
244 struct bankd_slot_mapping *slmap;
245
Harald Weltecce2aad2018-08-16 14:44:37 +0200246 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
247
Harald Weltecce2aad2018-08-16 14:44:37 +0200248
249 LOGW(worker, "connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
250 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
251 /* FIXME: store somewhere? */
252
253 if (worker->state != BW_ST_CONN_WAIT_ID) {
254 LOGW(worker, "Unexpected connectClientReq\n");
255 return -102;
256 }
257
Harald Welte371d0262018-08-16 15:23:58 +0200258 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200259 LOGW(worker, "missing clientID, aborting\n");
260 return -103;
261 }
Harald Welte371d0262018-08-16 15:23:58 +0200262 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
263 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200264 worker_set_state(worker, BW_ST_CONN_CLIENT);
265
Harald Welteaf614732018-08-17 22:10:05 +0200266 slmap = bankd_slotmap_by_client(worker->bankd, &worker->client.clslot);
267 if (!slmap) {
268 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
269 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
270 worker_set_state(worker, BW_ST_CONN_CLIENT_WAIT_MAP);
271 /* FIXME: how to update the map in case a map is installed later */
272 } else {
273 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
274 slmap->client.client_id, slmap->client.slot_nr,
275 slmap->bank.bank_id, slmap->bank.slot_nr);
Harald Welte796a7492018-09-23 19:31:28 +0200276 worker->slot = slmap->bank;
Harald Welteaf614732018-08-17 22:10:05 +0200277 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED);
Harald Welte796a7492018-09-23 19:31:28 +0200278 /* actually open the mapped reader/card/slot */
279 worker_open_card(worker);
Harald Welteaf614732018-08-17 22:10:05 +0200280 }
Harald Weltecce2aad2018-08-16 14:44:37 +0200281
282 return 0;
283}
284
Harald Welte796a7492018-09-23 19:31:28 +0200285static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
286{
287 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
288 const SCARD_IO_REQUEST *pioSendPci = SCARD_PCI_T0;
289 SCARD_IO_REQUEST pioRecvPci;
290 uint8_t rx_buf[1024];
291 DWORD rx_buf_len = sizeof(rx_buf);
292 RsproPDU_t *pdu_resp;
293 long rc;
294
295 LOGW(worker, "tpduModemToCard(%s)\n", osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
296
297 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
298 LOGW(worker, "Unexpected tpduModemToCaard\n");
299 return -104;
300 }
301
302 /* FIXME: Validate that toBankSlot / fromClientSlot match our expectations */
303
304 rc = SCardTransmit(worker->reader.pcsc.hCard,
305 pioSendPci, mdm2sim->data.buf, mdm2sim->data.size,
306 &pioRecvPci, rx_buf, &rx_buf_len);
307 PCSC_ERROR(worker, rc, "SCardTransmit");
308
309 /* encode response PDU and send it */
310 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
311 rx_buf, rx_buf_len);
312 worker_send_rspro(worker, pdu_resp);
313
314 return 0;
315end:
316 return rc;
317}
318
Harald Welte77911b02018-08-14 23:47:30 +0200319/* handle one incoming RSPRO message from a client inside a worker thread */
320static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
321{
Harald Weltecce2aad2018-08-16 14:44:37 +0200322 int rc = -100;
323
Harald Welte77911b02018-08-14 23:47:30 +0200324 switch (pdu->msg.present) {
325 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200326 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200327 break;
328 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200329 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200330 break;
331 case RsproPDUchoice_PR_clientSlotStatusInd:
332 /* FIXME */
333 break;
334 default:
Harald Weltecce2aad2018-08-16 14:44:37 +0200335 rc = -101;
336 break;
Harald Welte77911b02018-08-14 23:47:30 +0200337 }
338
Harald Weltecce2aad2018-08-16 14:44:37 +0200339 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200340}
341
342/* body of the main transceive loop */
343static int worker_transceive_loop(struct bankd_worker *worker)
344{
345 struct ipaccess_head *hh;
346 struct ipaccess_head_ext *hh_ext;
347 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
348 asn_dec_rval_t rval;
349 int data_len, rc;
350 RsproPDU_t *pdu;
351
352 /* 1) blocking read of entire IPA message from the socket */
353 rc = blocking_ipa_read(worker->client.fd, buf, sizeof(buf));
354 if (rc < 0)
355 return rc;
356 data_len = rc;
357
358 hh = (struct ipaccess_head *) buf;
359 if (hh->proto != IPAC_PROTO_OSMO)
360 return -4;
361
362 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
363 if (data_len < sizeof(*hh_ext))
364 return -5;
365 data_len -= sizeof(*hh_ext);
366 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO)
367 return -6;
368
369 /* 2) ASN1 BER decode of the message */
370 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
371 if (rval.code != RC_OK)
372 return -7;
373
374 /* 3) handling of the message, possibly resulting in PCSC commands */
375 rc = worker_handle_rspro(worker, pdu);
376 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
377 if (rc < 0)
378 return rc;
379
380 /* everything OK if we reach here */
381 return 0;
382}
383
Harald Welted6dfb8c2018-08-16 14:46:53 +0200384/* obtain an ascii representation of the client IP/port */
385static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
386{
387 char hostbuf[32], portbuf[32];
388 int rc;
389
390 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
391 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
392 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
393 if (rc != 0) {
394 out[0] = '\0';
395 return -1;
396 }
397 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
398 return 0;
399}
400
Harald Welte77911b02018-08-14 23:47:30 +0200401/* worker thread main function */
402static void *worker_main(void *arg)
403{
404 struct bankd_worker *worker = (struct bankd_worker *) arg;
405 void *top_ctx;
406 int rc;
407
Harald Welte8d858292018-08-15 23:36:46 +0200408 worker_set_state(worker, BW_ST_INIT);
409
Harald Welte77911b02018-08-14 23:47:30 +0200410 /* not permitted in multithreaded environment */
411 talloc_disable_null_tracking();
412 top_ctx = talloc_named_const(NULL, 0, "top");
413 talloc_asn1_ctx = talloc_named_const(top_ctx, 0, "asn1");
414
415 /* push cleanup helper */
416 pthread_cleanup_push(&worker_cleanup, worker);
417
418 /* we continuously perform the same loop here, recycling the worker thread
419 * once the client connection is gone or we have some trouble with the card/reader */
420 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +0200421 char buf[128];
422
Harald Welte77911b02018-08-14 23:47:30 +0200423 worker->client.peer_addr_len = sizeof(worker->client.peer_addr);
424
Harald Welte8d858292018-08-15 23:36:46 +0200425 worker_set_state(worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +0200426 /* first wait for an incoming TCP connection */
427 rc = accept(worker->bankd->accept_fd, (struct sockaddr *) &worker->client.peer_addr,
428 &worker->client.peer_addr_len);
429 if (rc < 0) {
430 continue;
431 }
432 worker->client.fd = rc;
Harald Welted6dfb8c2018-08-16 14:46:53 +0200433 worker_client_addrstr(buf, sizeof(buf), worker);
434 LOGW(worker, "Accepted connection from %s\n", buf);
Harald Welte8d858292018-08-15 23:36:46 +0200435 worker_set_state(worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +0200436
437 /* run the main worker transceive loop body until there was some error */
438 while (1) {
439 rc = worker_transceive_loop(worker);
440 if (rc < 0)
441 break;
442 }
443
Harald Welted6dfb8c2018-08-16 14:46:53 +0200444 LOGW(worker, "Error %d occurred: Cleaning up state\n", rc);
445
Harald Welte77911b02018-08-14 23:47:30 +0200446 /* clean-up: reset to sane state */
447 if (worker->reader.pcsc.hCard) {
448 SCardDisconnect(worker->reader.pcsc.hCard, SCARD_UNPOWER_CARD);
449 worker->reader.pcsc.hCard = 0;
450 }
451 if (worker->reader.pcsc.hContext) {
452 SCardReleaseContext(worker->reader.pcsc.hContext);
453 worker->reader.pcsc.hContext = 0;
454 }
455 if (worker->client.fd >= 0)
456 close(worker->client.fd);
Harald Welte415e8f62018-08-16 14:47:38 +0200457 memset(&worker->client.peer_addr, 0, sizeof(worker->client.peer_addr));
Harald Welte77911b02018-08-14 23:47:30 +0200458 worker->client.fd = -1;
Harald Welte371d0262018-08-16 15:23:58 +0200459 worker->client.clslot.client_id = worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200460 }
461
462 pthread_cleanup_pop(1);
463 talloc_free(top_ctx);
464 pthread_exit(NULL);
465}