blob: f888e9a565f4bee8a7ed16ab7c4d73e9e950d163 [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 Weltee72e5732018-09-23 19:31:55 +020048
49 /* HACK HACK HACK */
50 {
51 struct bank_slot bs = { .bank_id = 1, };
52 struct client_slot cs = { .client_id = 23, };
53 int i;
54 for (i = 0; i < 5; i++) {
55 bs.slot_nr = cs.slot_nr = i;
56 bankd_slotmap_add(bankd, &bs, &cs);
57 }
58 }
Harald Welte77911b02018-08-14 23:47:30 +020059}
60
61/* create + start a new bankd_worker thread */
Harald Welte8d858292018-08-15 23:36:46 +020062static struct bankd_worker *bankd_create_worker(struct bankd *bankd, unsigned int i)
Harald Welte77911b02018-08-14 23:47:30 +020063{
64 struct bankd_worker *worker;
65 int rc;
66
67 worker = talloc_zero(bankd, struct bankd_worker);
68 if (!worker)
69 return NULL;
70
71 worker->bankd = bankd;
Harald Welte8d858292018-08-15 23:36:46 +020072 worker->num = i;
Harald Welte77911b02018-08-14 23:47:30 +020073
74 /* in the initial state, the worker has no client.fd, bank_slot or pcsc handle yet */
75
76 rc = pthread_create(&worker->thread, NULL, worker_main, worker);
77 if (rc != 0) {
78 talloc_free(worker);
79 return NULL;
80 }
81
82 pthread_mutex_lock(&bankd->workers_mutex);
83 llist_add_tail(&worker->list, &bankd->workers);
84 pthread_mutex_unlock(&bankd->workers_mutex);
85
86 return worker;
87}
88
89static bool terminate = false;
90
91int main(int argc, char **argv)
92{
93 struct bankd *bankd = talloc_zero(NULL, struct bankd);
94 int i, rc;
95
96 OSMO_ASSERT(bankd);
97 bankd_init(bankd);
98
Harald Welte12534e72018-08-15 23:37:29 +020099 /* create listening socket */
100 rc = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 9999, OSMO_SOCK_F_BIND);
101 if (rc < 0)
102 exit(1);
103 bankd->accept_fd = rc;
104
105 /* create worker threads. FIXME: one per reader/slot! */
Harald Welte77911b02018-08-14 23:47:30 +0200106 for (i = 0; i < 10; i++) {
107 struct bankd_worker *w;
Harald Welte8d858292018-08-15 23:36:46 +0200108 w = bankd_create_worker(bankd, i);
Harald Welte77911b02018-08-14 23:47:30 +0200109 if (!w)
110 exit(21);
111 }
112
113 while (1) {
114 if (terminate)
115 break;
Harald Welte7f684a02018-08-16 14:43:50 +0200116 sleep(1);
Harald Welte77911b02018-08-14 23:47:30 +0200117 }
118
119 talloc_free(bankd);
120 exit(0);
121}
122
123
124
125/***********************************************************************
126 * bankd worker thread
127 ***********************************************************************/
128
Harald Welte8d858292018-08-15 23:36:46 +0200129struct value_string worker_state_names[] = {
130 { BW_ST_INIT, "INIT" },
131 { BW_ST_ACCEPTING, "ACCEPTING" },
132 { BW_ST_CONN_WAIT_ID, "CONN_WAIT_ID" },
133 { BW_ST_CONN_CLIENT, "CONN_CLIENT" },
Harald Welteaf614732018-08-17 22:10:05 +0200134 { BW_ST_CONN_CLIENT_WAIT_MAP, "CONN_CLIENT_WAIT_MAP" },
Harald Welte8d858292018-08-15 23:36:46 +0200135 { BW_ST_CONN_CLIENT_MAPPED, "CONN_CLIENT_MAPPED" },
136 { BW_ST_CONN_CLIENT_MAPPED_CARD,"CONN_CLIENT_MAPPED_CARD" },
137 { 0, NULL }
138};
139
Harald Welteceb3e682018-08-16 14:47:11 +0200140#define LOGW(w, fmt, args...) \
141 printf("[%03u %s] %s:%u " fmt, (w)->num, get_value_string(worker_state_names, (w)->state), \
142 __FILE__, __LINE__, ## args)
143
Harald Welteaf614732018-08-17 22:10:05 +0200144#define PCSC_ERROR(w, rv, text) \
145if (rv != SCARD_S_SUCCESS) { \
146 LOGW((w), text ": %s (0x%lX)\n", pcsc_stringify_error(rv), rv); \
147 goto end; \
148} else { \
149 LOGW((w), ": OK\n\n"); \
150}
151
Harald Welte8d858292018-08-15 23:36:46 +0200152static void worker_set_state(struct bankd_worker *worker, enum bankd_worker_state new_state)
153{
154 LOGW(worker, "Changing state to %s\n", get_value_string(worker_state_names, new_state));
155 worker->state = new_state;
156}
Harald Welte77911b02018-08-14 23:47:30 +0200157
158static void worker_cleanup(void *arg)
159{
160 struct bankd_worker *worker = (struct bankd_worker *) arg;
161 struct bankd *bankd = worker->bankd;
162
163 /* FIXME: should we still do this? in the thread ?!? */
164 pthread_mutex_lock(&bankd->workers_mutex);
165 llist_del(&worker->list);
166 talloc_free(worker); /* FIXME: is this safe? */
167 pthread_mutex_unlock(&bankd->workers_mutex);
168}
169
170
Harald Welteaf614732018-08-17 22:10:05 +0200171static int worker_open_card(struct bankd_worker *worker)
Harald Welte77911b02018-08-14 23:47:30 +0200172{
Harald Welteaf614732018-08-17 22:10:05 +0200173 long rc;
Harald Welte77911b02018-08-14 23:47:30 +0200174
Harald Welte45c948c2018-09-23 19:26:52 +0200175 /* resolve PC/SC reader name from slot_id -> name map */
176 worker->reader.name = bankd_pcsc_get_slot_name(worker->bankd, &worker->slot);
177 OSMO_ASSERT(worker->reader.name);
178
179 LOGW(worker, "Attempting to open card/slot '%s'\n", worker->reader.name);
180
Harald Welte77911b02018-08-14 23:47:30 +0200181 /* The PC/SC context must be created inside the thread where we'll later use it */
182 rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &worker->reader.pcsc.hContext);
Harald Welteaf614732018-08-17 22:10:05 +0200183 PCSC_ERROR(worker, rc, "SCardEstablishContext")
Harald Welte77911b02018-08-14 23:47:30 +0200184
Harald Welte48865c22018-09-23 19:30:07 +0200185 DWORD dwActiveProtocol;
Harald Welte77911b02018-08-14 23:47:30 +0200186 rc = SCardConnect(worker->reader.pcsc.hContext, worker->reader.name, SCARD_SHARE_SHARED,
Harald Welte48865c22018-09-23 19:30:07 +0200187 SCARD_PROTOCOL_T0, &worker->reader.pcsc.hCard, &dwActiveProtocol);
Harald Welteaf614732018-08-17 22:10:05 +0200188 PCSC_ERROR(worker, rc, "SCardConnect")
Harald Welte77911b02018-08-14 23:47:30 +0200189
Harald Welte57593f02018-09-23 19:30:31 +0200190 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED_CARD);
191
Harald Welteaf614732018-08-17 22:10:05 +0200192 return 0;
Harald Welte77911b02018-08-14 23:47:30 +0200193end:
Harald Welteaf614732018-08-17 22:10:05 +0200194 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200195}
Harald Welte77911b02018-08-14 23:47:30 +0200196
197
198static int blocking_ipa_read(int fd, uint8_t *buf, unsigned int buf_size)
199{
200 struct ipaccess_head *hh;
201 uint16_t len;
202 int needed, rc;
203
204 if (buf_size < sizeof(*hh))
205 return -1;
206
207 hh = (struct ipaccess_head *) buf;
208
209 /* 1) blocking read from the socket (IPA header) */
210 rc = read(fd, buf, sizeof(*hh));
211 if (rc < sizeof(*hh))
212 return -2;
213
214 len = ntohs(hh->len);
215 needed = len; //- sizeof(*hh);
216
217 /* 2) blocking read from the socket (payload) */
218 rc = read(fd, buf+sizeof(*hh), needed);
219 if (rc < needed)
220 return -3;
221
222 return len;
223}
224
Harald Welte796a7492018-09-23 19:31:28 +0200225static int worker_send_rspro(struct bankd_worker *worker, RsproPDU_t *pdu)
226{
227 struct msgb *msg = rspro_enc_msg(pdu);
228 int rc;
229
230 if (!msg) {
231 LOGW(worker, "error encoding RSPRO\n");
232 return -1;
233 }
234
Harald Weltefd471192018-09-24 14:51:14 +0200235 msg->l2h = msg->data;
Harald Welte796a7492018-09-23 19:31:28 +0200236 /* prepend the header */
237 ipa_prepend_header_ext(msg, IPAC_PROTO_EXT_RSPRO);
Harald Weltefd471192018-09-24 14:51:14 +0200238 ipa_prepend_header(msg, IPAC_PROTO_OSMO);
Harald Welte796a7492018-09-23 19:31:28 +0200239
240 /* actually send it through the socket */
241 rc = write(worker->client.fd, msgb_data(msg), msgb_length(msg));
242 if (rc == msgb_length(msg))
243 rc = 0;
244 else {
245 LOGW(worker, "error during write: %d != %d\n", rc, msgb_length(msg));
246 rc = -1;
247 }
248
249 msgb_free(msg);
250
251 return rc;
252}
253
Harald Weltecce2aad2018-08-16 14:44:37 +0200254static int worker_handle_connectClientReq(struct bankd_worker *worker, const RsproPDU_t *pdu)
255{
Harald Welteaf614732018-08-17 22:10:05 +0200256 const struct ComponentIdentity *cid = &pdu->msg.choice.connectClientReq.identity;
257 struct bankd_slot_mapping *slmap;
258
Harald Weltecce2aad2018-08-16 14:44:37 +0200259 OSMO_ASSERT(pdu->msg.present == RsproPDUchoice_PR_connectClientReq);
260
Harald Weltecce2aad2018-08-16 14:44:37 +0200261
262 LOGW(worker, "connectClientReq(T=%lu, N='%s', SW='%s', VER='%s')\n",
263 cid->type, cid->name.buf, cid->software.buf, cid->swVersion.buf);
264 /* FIXME: store somewhere? */
265
266 if (worker->state != BW_ST_CONN_WAIT_ID) {
267 LOGW(worker, "Unexpected connectClientReq\n");
268 return -102;
269 }
270
Harald Welte371d0262018-08-16 15:23:58 +0200271 if (!pdu->msg.choice.connectClientReq.clientSlot) {
Harald Weltecce2aad2018-08-16 14:44:37 +0200272 LOGW(worker, "missing clientID, aborting\n");
273 return -103;
274 }
Harald Welte371d0262018-08-16 15:23:58 +0200275 worker->client.clslot.client_id = pdu->msg.choice.connectClientReq.clientSlot->clientId;
276 worker->client.clslot.slot_nr = pdu->msg.choice.connectClientReq.clientSlot->slotNr;
Harald Weltecce2aad2018-08-16 14:44:37 +0200277 worker_set_state(worker, BW_ST_CONN_CLIENT);
278
Harald Welteaf614732018-08-17 22:10:05 +0200279 slmap = bankd_slotmap_by_client(worker->bankd, &worker->client.clslot);
280 if (!slmap) {
281 LOGW(worker, "No slotmap (yet) for client C(%u:%u)\n",
282 worker->client.clslot.client_id, worker->client.clslot.slot_nr);
283 worker_set_state(worker, BW_ST_CONN_CLIENT_WAIT_MAP);
284 /* FIXME: how to update the map in case a map is installed later */
285 } else {
286 LOGW(worker, "slotmap found: C(%u:%u) -> B(%u:%u)\n",
287 slmap->client.client_id, slmap->client.slot_nr,
288 slmap->bank.bank_id, slmap->bank.slot_nr);
Harald Welte796a7492018-09-23 19:31:28 +0200289 worker->slot = slmap->bank;
Harald Welteaf614732018-08-17 22:10:05 +0200290 worker_set_state(worker, BW_ST_CONN_CLIENT_MAPPED);
Harald Welte796a7492018-09-23 19:31:28 +0200291 /* actually open the mapped reader/card/slot */
292 worker_open_card(worker);
Harald Welteaf614732018-08-17 22:10:05 +0200293 }
Harald Weltecce2aad2018-08-16 14:44:37 +0200294
295 return 0;
296}
297
Harald Welte796a7492018-09-23 19:31:28 +0200298static int worker_handle_tpduModemToCard(struct bankd_worker *worker, const RsproPDU_t *pdu)
299{
300 const struct TpduModemToCard *mdm2sim = &pdu->msg.choice.tpduModemToCard;
301 const SCARD_IO_REQUEST *pioSendPci = SCARD_PCI_T0;
302 SCARD_IO_REQUEST pioRecvPci;
303 uint8_t rx_buf[1024];
304 DWORD rx_buf_len = sizeof(rx_buf);
305 RsproPDU_t *pdu_resp;
306 long rc;
307
308 LOGW(worker, "tpduModemToCard(%s)\n", osmo_hexdump_nospc(mdm2sim->data.buf, mdm2sim->data.size));
309
310 if (worker->state != BW_ST_CONN_CLIENT_MAPPED_CARD) {
311 LOGW(worker, "Unexpected tpduModemToCaard\n");
312 return -104;
313 }
314
315 /* FIXME: Validate that toBankSlot / fromClientSlot match our expectations */
316
317 rc = SCardTransmit(worker->reader.pcsc.hCard,
318 pioSendPci, mdm2sim->data.buf, mdm2sim->data.size,
319 &pioRecvPci, rx_buf, &rx_buf_len);
320 PCSC_ERROR(worker, rc, "SCardTransmit");
321
322 /* encode response PDU and send it */
323 pdu_resp = rspro_gen_TpduCard2Modem(&mdm2sim->toBankSlot, &mdm2sim->fromClientSlot,
324 rx_buf, rx_buf_len);
325 worker_send_rspro(worker, pdu_resp);
326
327 return 0;
328end:
329 return rc;
330}
331
Harald Welte77911b02018-08-14 23:47:30 +0200332/* handle one incoming RSPRO message from a client inside a worker thread */
333static int worker_handle_rspro(struct bankd_worker *worker, const RsproPDU_t *pdu)
334{
Harald Weltecce2aad2018-08-16 14:44:37 +0200335 int rc = -100;
336
Harald Welte77911b02018-08-14 23:47:30 +0200337 switch (pdu->msg.present) {
338 case RsproPDUchoice_PR_connectClientReq:
Harald Weltecce2aad2018-08-16 14:44:37 +0200339 rc = worker_handle_connectClientReq(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200340 break;
341 case RsproPDUchoice_PR_tpduModemToCard:
Harald Welte796a7492018-09-23 19:31:28 +0200342 rc = worker_handle_tpduModemToCard(worker, pdu);
Harald Welte77911b02018-08-14 23:47:30 +0200343 break;
344 case RsproPDUchoice_PR_clientSlotStatusInd:
345 /* FIXME */
346 break;
347 default:
Harald Weltecce2aad2018-08-16 14:44:37 +0200348 rc = -101;
349 break;
Harald Welte77911b02018-08-14 23:47:30 +0200350 }
351
Harald Weltecce2aad2018-08-16 14:44:37 +0200352 return rc;
Harald Welte77911b02018-08-14 23:47:30 +0200353}
354
355/* body of the main transceive loop */
356static int worker_transceive_loop(struct bankd_worker *worker)
357{
358 struct ipaccess_head *hh;
359 struct ipaccess_head_ext *hh_ext;
360 uint8_t buf[65536]; /* maximum length expressed in 16bit length field */
361 asn_dec_rval_t rval;
362 int data_len, rc;
363 RsproPDU_t *pdu;
364
365 /* 1) blocking read of entire IPA message from the socket */
366 rc = blocking_ipa_read(worker->client.fd, buf, sizeof(buf));
367 if (rc < 0)
368 return rc;
369 data_len = rc;
370
371 hh = (struct ipaccess_head *) buf;
372 if (hh->proto != IPAC_PROTO_OSMO)
373 return -4;
374
375 hh_ext = (struct ipaccess_head_ext *) buf + sizeof(*hh);
376 if (data_len < sizeof(*hh_ext))
377 return -5;
378 data_len -= sizeof(*hh_ext);
379 if (hh_ext->proto != IPAC_PROTO_EXT_RSPRO)
380 return -6;
381
382 /* 2) ASN1 BER decode of the message */
383 rval = ber_decode(NULL, &asn_DEF_RsproPDU, (void **) &pdu, hh_ext->data, data_len);
384 if (rval.code != RC_OK)
385 return -7;
386
387 /* 3) handling of the message, possibly resulting in PCSC commands */
388 rc = worker_handle_rspro(worker, pdu);
389 ASN_STRUCT_FREE(asn_DEF_RsproPDU, pdu);
390 if (rc < 0)
391 return rc;
392
393 /* everything OK if we reach here */
394 return 0;
395}
396
Harald Welted6dfb8c2018-08-16 14:46:53 +0200397/* obtain an ascii representation of the client IP/port */
398static int worker_client_addrstr(char *out, unsigned int outlen, const struct bankd_worker *worker)
399{
400 char hostbuf[32], portbuf[32];
401 int rc;
402
403 rc = getnameinfo((const struct sockaddr *)&worker->client.peer_addr,
404 worker->client.peer_addr_len, hostbuf, sizeof(hostbuf),
405 portbuf, sizeof(portbuf), NI_NUMERICHOST | NI_NUMERICSERV);
406 if (rc != 0) {
407 out[0] = '\0';
408 return -1;
409 }
410 snprintf(out, outlen, "%s:%s", hostbuf, portbuf);
411 return 0;
412}
413
Harald Welte77911b02018-08-14 23:47:30 +0200414/* worker thread main function */
415static void *worker_main(void *arg)
416{
417 struct bankd_worker *worker = (struct bankd_worker *) arg;
418 void *top_ctx;
419 int rc;
420
Harald Welte8d858292018-08-15 23:36:46 +0200421 worker_set_state(worker, BW_ST_INIT);
422
Harald Welte77911b02018-08-14 23:47:30 +0200423 /* not permitted in multithreaded environment */
424 talloc_disable_null_tracking();
425 top_ctx = talloc_named_const(NULL, 0, "top");
426 talloc_asn1_ctx = talloc_named_const(top_ctx, 0, "asn1");
427
428 /* push cleanup helper */
429 pthread_cleanup_push(&worker_cleanup, worker);
430
431 /* we continuously perform the same loop here, recycling the worker thread
432 * once the client connection is gone or we have some trouble with the card/reader */
433 while (1) {
Harald Welted6dfb8c2018-08-16 14:46:53 +0200434 char buf[128];
435
Harald Welte77911b02018-08-14 23:47:30 +0200436 worker->client.peer_addr_len = sizeof(worker->client.peer_addr);
437
Harald Welte8d858292018-08-15 23:36:46 +0200438 worker_set_state(worker, BW_ST_ACCEPTING);
Harald Welte77911b02018-08-14 23:47:30 +0200439 /* first wait for an incoming TCP connection */
440 rc = accept(worker->bankd->accept_fd, (struct sockaddr *) &worker->client.peer_addr,
441 &worker->client.peer_addr_len);
442 if (rc < 0) {
443 continue;
444 }
445 worker->client.fd = rc;
Harald Welted6dfb8c2018-08-16 14:46:53 +0200446 worker_client_addrstr(buf, sizeof(buf), worker);
447 LOGW(worker, "Accepted connection from %s\n", buf);
Harald Welte8d858292018-08-15 23:36:46 +0200448 worker_set_state(worker, BW_ST_CONN_WAIT_ID);
Harald Welte77911b02018-08-14 23:47:30 +0200449
450 /* run the main worker transceive loop body until there was some error */
451 while (1) {
452 rc = worker_transceive_loop(worker);
453 if (rc < 0)
454 break;
455 }
456
Harald Welted6dfb8c2018-08-16 14:46:53 +0200457 LOGW(worker, "Error %d occurred: Cleaning up state\n", rc);
458
Harald Welte77911b02018-08-14 23:47:30 +0200459 /* clean-up: reset to sane state */
460 if (worker->reader.pcsc.hCard) {
461 SCardDisconnect(worker->reader.pcsc.hCard, SCARD_UNPOWER_CARD);
462 worker->reader.pcsc.hCard = 0;
463 }
464 if (worker->reader.pcsc.hContext) {
465 SCardReleaseContext(worker->reader.pcsc.hContext);
466 worker->reader.pcsc.hContext = 0;
467 }
468 if (worker->client.fd >= 0)
469 close(worker->client.fd);
Harald Welte415e8f62018-08-16 14:47:38 +0200470 memset(&worker->client.peer_addr, 0, sizeof(worker->client.peer_addr));
Harald Welte77911b02018-08-14 23:47:30 +0200471 worker->client.fd = -1;
Harald Welte371d0262018-08-16 15:23:58 +0200472 worker->client.clslot.client_id = worker->client.clslot.slot_nr = 0;
Harald Welte77911b02018-08-14 23:47:30 +0200473 }
474
475 pthread_cleanup_pop(1);
476 talloc_free(top_ctx);
477 pthread_exit(NULL);
478}