b95858f89f012bcb9ac0756351bafcccc886bc8a
[osmocom-bb.git] / src / host / layer23 / src / mobile / subscriber.c
1 /*
2  * (C) 2010 by Andreas Eversberg <jolly@eversberg.eu>
3  *
4  * All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  *
20  */
21
22 #include <stdint.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <arpa/inet.h>
26 #include <osmocore/talloc.h>
27 #include <osmocore/comp128.h>
28
29 #include <osmocom/bb/common/logging.h>
30 #include <osmocom/bb/common/osmocom_data.h>
31 #include <osmocom/bb/common/networks.h>
32 #include <osmocom/bb/mobile/vty.h>
33
34 void *l23_ctx;
35
36 static void subscr_sim_query_cb(struct osmocom_ms *ms, struct msgb *msg);
37 static void subscr_sim_update_cb(struct osmocom_ms *ms, struct msgb *msg);
38 static void subscr_sim_key_cb(struct osmocom_ms *ms, struct msgb *msg);
39
40 /*
41  * support
42  */
43
44 char *gsm_check_imsi(const char *imsi)
45 {
46         int i;
47
48         if (!imsi || strlen(imsi) != 15)
49                 return "IMSI must have 15 digits!";
50
51         for (i = 0; i < strlen(imsi); i++) {
52                 if (imsi[i] < '0' || imsi[i] > '9')
53                         return "IMSI must have digits 0 to 9 only!";
54         }
55
56         return NULL;
57 }
58
59 static char *sim_decode_bcd(uint8_t *data, uint8_t length)
60 {
61         int i, j = 0;
62         static char result[32], c;
63
64         for (i = 0; i < (length << 1); i++) {
65                 if ((i & 1))
66                         c = (data[i >> 1] >> 4);
67                 else
68                         c = (data[i >> 1] & 0xf);
69                 if (c == 0xf)
70                         break;
71                 result[j++] = c + '0';
72                 if (j == sizeof(result) - 1)
73                         break;
74         }
75         result[j] = '\0';
76
77         return result;
78 }
79
80 static void xor96(uint8_t *ki, uint8_t *rand, uint8_t *sres, uint8_t *kc)
81 {
82         int i;
83
84         for (i=0; i < 4; i++)
85                 sres[i] = rand[i] ^ ki[i];
86         for (i=0; i < 8; i++)
87                 kc[i] = rand[i] ^ ki[i+4];
88 }
89
90 /*
91  * init/exit
92  */
93
94 int gsm_subscr_init(struct osmocom_ms *ms)
95 {
96         struct gsm_subscriber *subscr = &ms->subscr;
97
98         memset(subscr, 0, sizeof(*subscr));
99         subscr->ms = ms;
100
101         /* set TMSI / LAC invalid */
102         subscr->tmsi = 0xffffffff;
103         subscr->lac = 0x0000;
104
105         /* set key invalid */
106         subscr->key_seq = 7;
107
108         /* init lists */
109         INIT_LLIST_HEAD(&subscr->plmn_list);
110         INIT_LLIST_HEAD(&subscr->plmn_na);
111
112         /* open SIM */
113         subscr->sim_handle_query = sim_open(ms, subscr_sim_query_cb);
114         subscr->sim_handle_update = sim_open(ms, subscr_sim_update_cb);
115         subscr->sim_handle_key = sim_open(ms, subscr_sim_key_cb);
116
117         return 0;
118 }
119
120 int gsm_subscr_exit(struct osmocom_ms *ms)
121 {
122         struct gsm_subscriber *subscr = &ms->subscr;
123         struct llist_head *lh, *lh2;
124
125         if (subscr->sim_handle_query) {
126                 sim_close(ms, subscr->sim_handle_query);
127                 subscr->sim_handle_query = 0;
128         }
129         if (subscr->sim_handle_update) {
130                 sim_close(ms, subscr->sim_handle_update);
131                 subscr->sim_handle_update = 0;
132         }
133         if (subscr->sim_handle_key) {
134                 sim_close(ms, subscr->sim_handle_key);
135                 subscr->sim_handle_key = 0;
136         }
137
138         /* flush lists */
139         llist_for_each_safe(lh, lh2, &subscr->plmn_list) {
140                 llist_del(lh);
141                 talloc_free(lh);
142         }
143         llist_for_each_safe(lh, lh2, &subscr->plmn_na) {
144                 llist_del(lh);
145                 talloc_free(lh);
146         }
147
148         return 0;
149 }
150
151 /*
152  * test card
153  */
154
155 /* Attach test card, no SIM must be currently attached */
156 int gsm_subscr_testcard(struct osmocom_ms *ms, uint16_t mcc, uint16_t mnc)
157 {
158         struct gsm_settings *set = &ms->settings;
159         struct gsm_subscriber *subscr = &ms->subscr;
160         struct msgb *nmsg;
161         char *error;
162
163         if (subscr->sim_valid) {
164                 LOGP(DMM, LOGL_ERROR, "Cannot insert card, until current card "
165                         "is detached.\n");
166                 return -EBUSY;
167         }
168
169         error = gsm_check_imsi(set->test_imsi);
170         if (error) {
171                 LOGP(DMM, LOGL_ERROR, "%s\n", error);
172                 return -EINVAL;
173         }
174
175         /* reset subscriber */
176         gsm_subscr_exit(ms);
177         gsm_subscr_init(ms);
178
179         subscr->sim_type = GSM_SIM_TYPE_TEST;
180         sprintf(subscr->sim_name, "test");
181         subscr->sim_valid = 1;
182         subscr->ustate = GSM_SIM_U2_NOT_UPDATED;
183         subscr->acc_barr = set->test_barr; /* we may access barred cell */
184         subscr->acc_class = 0xffff; /* we have any access class */
185         subscr->plmn_valid = set->test_rplmn_valid;
186         subscr->plmn_mcc = mcc;
187         subscr->plmn_mnc = mnc;
188         subscr->always_search_hplmn = set->test_always;
189         subscr->t6m_hplmn = 1; /* try to find home network every 6 min */
190         strcpy(subscr->imsi, set->test_imsi);
191
192         LOGP(DMM, LOGL_INFO, "(ms %s) Inserting test card (IMSI=%s %s, %s)\n",
193                 ms->name, subscr->imsi, gsm_imsi_mcc(subscr->imsi),
194                 gsm_imsi_mnc(subscr->imsi));
195
196         if (subscr->plmn_valid)
197                 LOGP(DMM, LOGL_INFO, "-> Test card registered to %s %s "
198                         "(%s, %s)\n", gsm_print_mcc(mcc), gsm_print_mnc(mnc),
199                         gsm_get_mcc(mcc), gsm_get_mnc(mcc, mnc));
200         else
201                 LOGP(DMM, LOGL_INFO, "-> Test card not registered\n");
202
203         /* insert card */
204         nmsg = gsm48_mmr_msgb_alloc(GSM48_MMR_REG_REQ);
205         if (!nmsg)
206                 return -ENOMEM;
207         gsm48_mmr_downmsg(ms, nmsg);
208
209         return 0;
210 }
211
212 /*
213  * sim card
214  */
215
216 static int subscr_sim_iccid(struct osmocom_ms *ms, uint8_t *data,
217         uint8_t length)
218 {
219         struct gsm_subscriber *subscr = &ms->subscr;
220
221         strcpy(subscr->iccid, sim_decode_bcd(data, length));
222         sprintf(subscr->sim_name, "sim-%s", subscr->iccid);
223         LOGP(DMM, LOGL_INFO, "received ICCID %s from SIM\n", subscr->iccid);
224
225         return 0;
226 }
227
228 static int subscr_sim_imsi(struct osmocom_ms *ms, uint8_t *data,
229         uint8_t length)
230 {
231         struct gsm_subscriber *subscr = &ms->subscr;
232         char *imsi;
233
234         /* get actual length */
235         if (length < 1)
236                 return -EINVAL;
237         if (data[0] + 1 < length) {
238                 LOGP(DMM, LOGL_NOTICE, "invalid length = %d\n", length);
239                 return -EINVAL;
240         }
241         length = data[0];
242
243         /* decode IMSI, skip first digit (parity) */
244         imsi = sim_decode_bcd(data + 1, length);
245         if (strlen(imsi) - 1 > GSM_IMSI_LENGTH - 1 || strlen(imsi) - 1 < 6) {
246                 LOGP(DMM, LOGL_NOTICE, "IMSI invalid length = %d\n",
247                         strlen(imsi) - 1);
248                 return -EINVAL;
249         }
250
251         strncpy(subscr->imsi, imsi + 1, sizeof(subscr->imsi) - 1);
252
253         LOGP(DMM, LOGL_INFO, "received IMSI %s from SIM\n", subscr->imsi);
254
255         return 0;
256 }
257
258 static int subscr_sim_loci(struct osmocom_ms *ms, uint8_t *data,
259         uint8_t length)
260 {
261         struct gsm_subscriber *subscr = &ms->subscr;
262         struct gsm1111_ef_loci *loci;
263
264         if (length < 11)
265                 return -EINVAL;
266         loci = (struct gsm1111_ef_loci *) data;
267
268         /* TMSI */
269         subscr->tmsi = ntohl(loci->tmsi);
270
271         /* LAI */
272         gsm48_decode_lai(&loci->lai, &subscr->mcc, &subscr->mnc, &subscr->lac);
273
274         /* location update status */
275         switch (loci->lupd_status & 0x07) {
276         case 0x00:
277                 subscr->ustate = GSM_SIM_U1_UPDATED;
278                 break;
279         case 0x02:
280         case 0x03:
281                 subscr->ustate = GSM_SIM_U3_ROAMING_NA;
282                 break;
283         default:
284                 subscr->ustate = GSM_SIM_U2_NOT_UPDATED;
285         }
286
287         LOGP(DMM, LOGL_INFO, "received LOCI from SIM (mcc=%s mnc=%s lac=0x%04x "
288                 "U%d)\n", gsm_print_mcc(subscr->mcc),
289                 gsm_print_mnc(subscr->mnc), subscr->lac, subscr->ustate);
290
291         return 0;
292 }
293
294 static int subscr_sim_msisdn(struct osmocom_ms *ms, uint8_t *data,
295         uint8_t length)
296 {
297         struct gsm_subscriber *subscr = &ms->subscr;
298         struct gsm1111_ef_adn *adn;
299
300         if (length < sizeof(*adn))
301                 return -EINVAL;
302         adn = (struct gsm1111_ef_adn *) (data + length - sizeof(*adn));
303
304         /* empty */
305         subscr->msisdn[0] = '\0';
306         if (adn->len_bcd <= 1)
307                 return 0;
308
309         /* number */
310         if (adn->ton_npi == 1)
311                 strcpy(subscr->msisdn, "+");
312         if (adn->ton_npi == 2)
313                 strcpy(subscr->msisdn, "0");
314         strncat(subscr->msisdn, sim_decode_bcd(adn->number, adn->len_bcd - 1),
315                 sizeof(subscr->msisdn) - 2);
316
317         LOGP(DMM, LOGL_INFO, "received MSISDN %s from SIM\n", subscr->msisdn);
318
319         return 0;
320 }
321
322 static int subscr_sim_kc(struct osmocom_ms *ms, uint8_t *data,
323         uint8_t length)
324 {
325         struct gsm_subscriber *subscr = &ms->subscr;
326
327         if (length < 9)
328                 return -EINVAL;
329
330         /* key */
331         memcpy(subscr->key, data, 8);
332
333         /* key sequence */
334         subscr->key_seq = data[8] & 0x07;
335
336         LOGP(DMM, LOGL_INFO, "received KEY from SIM\n");
337
338         return 0;
339 }
340
341 static int subscr_sim_plmnsel(struct osmocom_ms *ms, uint8_t *data,
342         uint8_t length)
343 {
344         struct gsm_subscriber *subscr = &ms->subscr;
345         struct gsm_sub_plmn_list *plmn;
346         struct llist_head *lh, *lh2;
347         uint8_t lai[5];
348         uint16_t dummy_lac;
349
350         /* flush list */
351         llist_for_each_safe(lh, lh2, &subscr->plmn_list) {
352                 llist_del(lh);
353                 talloc_free(lh);
354         }
355
356         while(length >= 3) {
357                 /* end of list inside mandatory fields */
358                 if (data[0] == 0xff && data[1] == 0xff && data[2] == 0x0ff)
359                         break;
360
361                 /* add to list */
362                 plmn = talloc_zero(l23_ctx, struct gsm_sub_plmn_list);
363                 if (!plmn)
364                         return -ENOMEM;
365                 lai[0] = data[0];
366                 lai[1] = data[1];
367                 lai[2] = data[2];
368                 gsm48_decode_lai((struct gsm48_loc_area_id *)lai, &plmn->mcc,
369                         &plmn->mnc, &dummy_lac);
370                 llist_add_tail(&plmn->entry, &subscr->plmn_list);
371
372                 LOGP(DMM, LOGL_INFO, "received PLMN selector (mcc=%s mnc=%s) "
373                         "from SIM\n",
374                         gsm_print_mcc(plmn->mcc), gsm_print_mnc(plmn->mnc));
375
376                 data += 3;
377                 length -= 3;
378         }
379
380         return 0;
381 }
382
383 static int subscr_sim_hpplmn(struct osmocom_ms *ms, uint8_t *data,
384         uint8_t length)
385 {
386         struct gsm_subscriber *subscr = &ms->subscr;
387
388         if (length < 1)
389                 return -EINVAL;
390
391         /* HPLMN search interval */
392         subscr->t6m_hplmn = *data; /* multiple of 6 minutes */
393
394         LOGP(DMM, LOGL_INFO, "received HPPLMN %d (%d mins) from SIM\n",
395                 subscr->t6m_hplmn, subscr->t6m_hplmn * 6);
396
397         return 0;
398 }
399
400 static int subscr_sim_spn(struct osmocom_ms *ms, uint8_t *data,
401         uint8_t length)
402 {
403         struct gsm_subscriber *subscr = &ms->subscr;
404         int i;
405
406         /* UCS2 code not supported */
407         if (length < 17 || data[1] >= 0x80)
408                 return -ENOTSUP;
409
410         data++;
411         for (i = 0; i < 16; i++) {
412                 if (*data == 0xff)
413                         break;
414                 subscr->sim_spn[i] = *data++;
415         }
416         subscr->sim_spn[i] = '\0';
417
418         LOGP(DMM, LOGL_INFO, "received SPN %s from SIM\n", subscr->sim_spn);
419
420         return 0;
421 }
422
423 static int subscr_sim_acc(struct osmocom_ms *ms, uint8_t *data,
424         uint8_t length)
425 {
426         struct gsm_subscriber *subscr = &ms->subscr;
427         uint16_t ac;
428
429         if (length < 2)
430                 return -EINVAL;
431
432         /* cell access */
433         memcpy(&ac, data, sizeof(ac));
434         subscr->acc_class = ntohs(ac);
435
436         LOGP(DMM, LOGL_INFO, "received ACC %04x from SIM\n", subscr->acc_class);
437
438         return 0;
439 }
440
441 static int subscr_sim_fplmn(struct osmocom_ms *ms, uint8_t *data,
442         uint8_t length)
443 {
444         struct gsm_subscriber *subscr = &ms->subscr;
445         struct gsm_sub_plmn_na *na;
446         struct llist_head *lh, *lh2;
447         uint8_t lai[5];
448         uint16_t dummy_lac;
449
450         /* flush list */
451         llist_for_each_safe(lh, lh2, &subscr->plmn_na) {
452                 llist_del(lh);
453                 talloc_free(lh);
454         }
455
456         while (length >= 3) {
457                 /* end of list inside mandatory fields */
458                 if (data[0] == 0xff && data[1] == 0xff && data[2] == 0x0ff)
459                         break;
460
461                 /* add to list */
462                 na = talloc_zero(l23_ctx, struct gsm_sub_plmn_na);
463                 if (!na)
464                         return -ENOMEM;
465                 lai[0] = data[0];
466                 lai[1] = data[1];
467                 lai[2] = data[2];
468                 gsm48_decode_lai((struct gsm48_loc_area_id *)lai, &na->mcc,
469                         &na->mnc, &dummy_lac);
470                 na->cause = 0;
471                 llist_add_tail(&na->entry, &subscr->plmn_na);
472
473                 data += 3;
474                 length -= 3;
475         }
476         return 0;
477 }
478
479 static struct subscr_sim_file {
480         uint8_t         mandatory;
481         uint16_t        path[MAX_SIM_PATH_LENGTH];
482         uint16_t        file;
483         int             (*func)(struct osmocom_ms *ms, uint8_t *data,
484                                 uint8_t length);
485 } subscr_sim_files[] = {
486         { 1, { 0 },         0x2fe2, subscr_sim_iccid },
487         { 1, { 0x7f20, 0 }, 0x6f07, subscr_sim_imsi },
488         { 1, { 0x7f20, 0 }, 0x6f7e, subscr_sim_loci },
489         { 0, { 0x7f20, 0 }, 0x6f40, subscr_sim_msisdn },
490         { 0, { 0x7f20, 0 }, 0x6f20, subscr_sim_kc },
491         { 0, { 0x7f20, 0 }, 0x6f30, subscr_sim_plmnsel },
492         { 0, { 0x7f20, 0 }, 0x6f31, subscr_sim_hpplmn },
493         { 0, { 0x7f20, 0 }, 0x6f46, subscr_sim_spn },
494         { 0, { 0x7f20, 0 }, 0x6f78, subscr_sim_acc },
495         { 0, { 0x7f20, 0 }, 0x6f7b, subscr_sim_fplmn },
496         { 0, { 0 },         0,      NULL }
497 };
498
499 /* request file from SIM */
500 static int subscr_sim_request(struct osmocom_ms *ms)
501 {
502         struct gsm_subscriber *subscr = &ms->subscr;
503         struct subscr_sim_file *sf = &subscr_sim_files[subscr->sim_file_index];
504         struct msgb *nmsg;
505         struct sim_hdr *nsh;
506         int i;
507
508         /* we are done, fire up PLMN and cell selection process */
509         if (!sf->func) {
510                 LOGP(DMM, LOGL_INFO, "(ms %s) Done reading SIM card "
511                         "(IMSI=%s %s, %s)\n", ms->name, subscr->imsi,
512                         gsm_imsi_mcc(subscr->imsi), gsm_imsi_mnc(subscr->imsi));
513
514                 /* if LAI is valid, set RPLMN */
515                 if (subscr->lac > 0x0000 && subscr->lac < 0xfffe) {
516                         subscr->plmn_valid = 1;
517                         subscr->plmn_mcc = subscr->mcc;
518                         subscr->plmn_mnc = subscr->mnc;
519                         LOGP(DMM, LOGL_INFO, "-> SIM card registered to %s %s "
520                                 "(%s, %s)\n", gsm_print_mcc(subscr->plmn_mcc),
521                                 gsm_print_mnc(subscr->plmn_mnc),
522                                 gsm_get_mcc(subscr->plmn_mcc),
523                                 gsm_get_mnc(subscr->plmn_mcc,
524                                         subscr->plmn_mnc));
525                 } else
526                         LOGP(DMM, LOGL_INFO, "-> SIM card not registered\n");
527
528                 /* insert card */
529                 nmsg = gsm48_mmr_msgb_alloc(GSM48_MMR_REG_REQ);
530                 if (!nmsg)
531                         return -ENOMEM;
532                 gsm48_mmr_downmsg(ms, nmsg);
533
534                 return 0;
535         }
536
537         /* trigger SIM reading */
538         nmsg = gsm_sim_msgb_alloc(subscr->sim_handle_query,
539                 SIM_JOB_READ_BINARY);
540         if (!nmsg)
541                 return -ENOMEM;
542         nsh = (struct sim_hdr *) nmsg->data;
543         i = 0;
544         while (sf->path[i]) {
545                 nsh->path[i] = sf->path[i];
546                 i++;
547         }
548         nsh->path[i] = 0; /* end of path */
549         nsh->file = sf->file;
550         LOGP(DMM, LOGL_INFO, "Requesting SIM file 0x%04x\n", nsh->file);
551         sim_job(ms, nmsg);
552
553         return 0;
554 }
555
556 static void subscr_sim_query_cb(struct osmocom_ms *ms, struct msgb *msg)
557 {
558         struct gsm_subscriber *subscr = &ms->subscr;
559         struct sim_hdr *sh = (struct sim_hdr *) msg->data;
560         uint8_t *payload = msg->data + sizeof(*sh);
561         uint16_t payload_len = msg->len - sizeof(*sh);
562         int rc;
563
564         /* error handling */
565         if (sh->job_type == SIM_JOB_ERROR) {
566                 uint8_t cause = payload[0];
567
568                 switch (cause) {
569                         /* unlocking required */
570                 case SIM_CAUSE_PIN1_REQUIRED:
571                         LOGP(DMM, LOGL_INFO, "PIN is required, %d tries left\n",
572                                 payload[1]);
573
574                         vty_notify(ms, NULL);
575                         vty_notify(ms, "Please give PIN for ICCID %s (you have "
576                                 "%d tries left)\n", subscr->iccid, payload[1]);
577                         subscr->sim_pin_required = 1;
578                         break;
579                 case SIM_CAUSE_PIN1_BLOCKED:
580                         LOGP(DMM, LOGL_NOTICE, "PIN is blocked\n");
581
582                         vty_notify(ms, NULL);
583                         vty_notify(ms, "PIN is blocked\n");
584                         break;
585                 default:
586                         if (!subscr_sim_files[subscr->sim_file_index].
587                                                                 mandatory) {
588                                 LOGP(DMM, LOGL_NOTICE, "SIM reading failed, "
589                                         "ignoring!\n");
590                                 goto ignore;
591                         }
592                         LOGP(DMM, LOGL_NOTICE, "SIM reading failed\n");
593
594                         vty_notify(ms, NULL);
595                         vty_notify(ms, "SIM failed, replace SIM!\n");
596                 }
597                 msgb_free(msg);
598
599                 return;
600         }
601
602         /* call function do decode SIM reply */
603         rc = subscr_sim_files[subscr->sim_file_index].func(ms, payload,
604                 payload_len);
605
606         if (rc) {
607                 LOGP(DMM, LOGL_NOTICE, "SIM reading failed, file invalid\n");
608                 if (subscr_sim_files[subscr->sim_file_index].mandatory) {
609                         vty_notify(ms, NULL);
610                         vty_notify(ms, "SIM failed, data invalid, replace "
611                                 "SIM!\n");
612                         msgb_free(msg);
613
614                         return;
615                 }
616         }
617
618 ignore:
619         msgb_free(msg);
620
621         /* trigger next file */
622         subscr->sim_file_index++;
623         subscr_sim_request(ms);
624 }
625
626 /* enter PIN */
627 void gsm_subscr_sim_pin(struct osmocom_ms *ms, char *pin)
628 {
629         struct gsm_subscriber *subscr = &ms->subscr;
630         struct msgb *nmsg;
631
632         if (!subscr->sim_pin_required) {
633                 LOGP(DMM, LOGL_ERROR, "No PIN required now\n");
634                 return;
635         }
636
637         subscr->sim_pin_required = 0;
638         LOGP(DMM, LOGL_INFO, "Unlocking PIN %s\n", pin);
639         nmsg = gsm_sim_msgb_alloc(subscr->sim_handle_update,
640                 SIM_JOB_PIN1_UNLOCK);
641         if (!nmsg)
642                 return;
643         memcpy(msgb_put(nmsg, strlen(pin)), pin, strlen(pin));
644         sim_job(ms, nmsg);
645 }
646
647 /* Attach SIM reader, no SIM must be currently attached */
648 int gsm_subscr_simcard(struct osmocom_ms *ms)
649 {
650         struct gsm_subscriber *subscr = &ms->subscr;
651
652         if (subscr->sim_valid) {
653                 LOGP(DMM, LOGL_ERROR, "Cannot attach card, until current card "
654                         "is detached.\n");
655                 return -EBUSY;
656         }
657
658         /* reset subscriber */
659         gsm_subscr_exit(ms);
660         gsm_subscr_init(ms);
661
662         subscr->sim_type = GSM_SIM_TYPE_READER;
663         sprintf(subscr->sim_name, "sim");
664         subscr->sim_valid = 1;
665         subscr->ustate = GSM_SIM_U2_NOT_UPDATED;
666
667         /* start with first index */
668         subscr->sim_file_index = 0;
669         return subscr_sim_request(ms);
670 }
671
672 /* update plmn not allowed list on SIM */
673 static int subscr_write_plmn_na(struct osmocom_ms *ms)
674 {
675         struct gsm_subscriber *subscr = &ms->subscr;
676         struct msgb *nmsg;
677         struct sim_hdr *nsh;
678         struct gsm_sub_plmn_na *na, *nas[4] = { NULL, NULL, NULL, NULL };
679         int count = 0, i;
680         uint8_t *data;
681         uint8_t lai[5];
682
683         /* skip, if no real valid SIM */
684         if (subscr->sim_type != GSM_SIM_TYPE_READER || !subscr->sim_valid)
685                 return 0;
686
687         /* get tail list from "PLMN not allowed" */
688         llist_for_each_entry(na, &subscr->plmn_na, entry) {
689                 if (count < 4)
690                         nas[count] = na;
691                 else {
692                         nas[0] = nas[1];
693                         nas[1] = nas[2];
694                         nas[2] = nas[3];
695                         nas[3] = na;
696                 }
697                 count++;
698         }
699
700         /* write to SIM */
701         LOGP(DMM, LOGL_INFO, "Updating FPLMN on SIM\n");
702         nmsg = gsm_sim_msgb_alloc(subscr->sim_handle_update,
703                 SIM_JOB_UPDATE_BINARY);
704         if (!nmsg)
705                 return -ENOMEM;
706         nsh = (struct sim_hdr *) nmsg->data;
707         data = msgb_put(nmsg, 12);
708         nsh->path[0] = 0x7f20;
709         nsh->path[1] = 0;
710         nsh->file = 0x6f7b;
711         for (i = 0; i < 4; i++) {
712                 if (nas[i]) {
713                         gsm48_encode_lai((struct gsm48_loc_area_id *)lai,
714                         nas[i]->mcc, nas[i]->mnc, 0);
715                         *data++ = lai[0];
716                         *data++ = lai[1];
717                         *data++ = lai[2];
718                 } else {
719                         *data++ = 0xff;
720                         *data++ = 0xff;
721                         *data++ = 0xff;
722                 }
723         }
724         sim_job(ms, nmsg);
725
726         return 0;
727 }
728
729 /* update LOCI on SIM */
730 int gsm_subscr_write_loci(struct osmocom_ms *ms)
731 {
732         struct gsm_subscriber *subscr = &ms->subscr;
733         struct msgb *nmsg;
734         struct sim_hdr *nsh;
735         struct gsm1111_ef_loci *loci;
736
737         /* skip, if no real valid SIM */
738         if (subscr->sim_type != GSM_SIM_TYPE_READER || !subscr->sim_valid)
739                 return 0;
740
741         LOGP(DMM, LOGL_INFO, "Updating LOCI on SIM\n");
742
743         /* write to SIM */
744         nmsg = gsm_sim_msgb_alloc(subscr->sim_handle_update,
745                 SIM_JOB_UPDATE_BINARY);
746         if (!nmsg)
747                 return -ENOMEM;
748         nsh = (struct sim_hdr *) nmsg->data;
749         nsh->path[0] = 0x7f20;
750         nsh->path[1] = 0;
751         nsh->file = 0x6f7e;
752         loci = (struct gsm1111_ef_loci *)msgb_put(nmsg, sizeof(*loci));
753
754         /* TMSI */
755         loci->tmsi = htonl(subscr->tmsi);
756
757         /* LAI */
758         gsm48_encode_lai(&loci->lai, subscr->mcc, subscr->mnc, subscr->lac);
759
760         /* TMSI time */
761         loci->tmsi_time = 0xff;
762
763         /* location update status */
764         switch (subscr->ustate) {
765         case GSM_SIM_U1_UPDATED:
766                 loci->lupd_status = 0x00;
767                 break;
768         case GSM_SIM_U3_ROAMING_NA:
769                 loci->lupd_status = 0x03;
770                 break;
771         default:
772                 loci->lupd_status = 0x01;
773         }
774
775         sim_job(ms, nmsg);
776
777         return 0;
778 }
779
780 static void subscr_sim_update_cb(struct osmocom_ms *ms, struct msgb *msg)
781 {
782         struct sim_hdr *sh = (struct sim_hdr *) msg->data;
783         uint8_t *payload = msg->data + sizeof(*sh);
784
785         /* error handling */
786         if (sh->job_type == SIM_JOB_ERROR)
787                 LOGP(DMM, LOGL_NOTICE, "SIM update failed (cause %d)\n",
788                         *payload);
789
790         msgb_free(msg);
791 }
792
793 int gsm_subscr_generate_kc(struct osmocom_ms *ms, uint8_t key_seq,
794         uint8_t *rand, uint8_t no_sim)
795 {
796         struct gsm_subscriber *subscr = &ms->subscr;
797         struct msgb *nmsg;
798         struct sim_hdr *nsh;
799
800         /* not a SIM */
801         if ((subscr->sim_type != GSM_SIM_TYPE_READER
802           && subscr->sim_type != GSM_SIM_TYPE_TEST)
803          || !subscr->sim_valid || no_sim) {
804                 struct gsm48_mm_event *nmme;
805
806                 LOGP(DMM, LOGL_INFO, "Sending dummy authentication response\n");
807                 nmsg = gsm48_mmevent_msgb_alloc(GSM48_MM_EVENT_AUTH_RESPONSE);
808                 if (!nmsg)
809                         return -ENOMEM;
810                 nmme = (struct gsm48_mm_event *) nmsg->data;
811                 nmme->sres[0] = 0x12;
812                 nmme->sres[1] = 0x34;
813                 nmme->sres[2] = 0x56;
814                 nmme->sres[3] = 0x78;
815                 gsm48_mmevent_msg(ms, nmsg);
816
817                 return 0;
818         }
819
820         /* test SIM */
821         if (subscr->sim_type == GSM_SIM_TYPE_TEST) {
822                 struct gsm48_mm_event *nmme;
823                 uint8_t sres[4];
824                 struct gsm_settings *set = &ms->settings;
825
826                 if (set->test_ki_type == GSM_SIM_KEY_COMP128)
827                         comp128(set->test_ki, rand, sres, subscr->key);
828                 else
829                         xor96(set->test_ki, rand, sres, subscr->key);
830                 /* store sequence */
831                 subscr->key_seq = key_seq;
832
833                 LOGP(DMM, LOGL_INFO, "Sending authentication response\n");
834                 nmsg = gsm48_mmevent_msgb_alloc(GSM48_MM_EVENT_AUTH_RESPONSE);
835                 if (!nmsg)
836                         return -ENOMEM;
837                 nmme = (struct gsm48_mm_event *) nmsg->data;
838                 memcpy(nmme->sres, sres, 4);
839                 gsm48_mmevent_msg(ms, nmsg);
840
841                 return 0;
842         }
843
844         LOGP(DMM, LOGL_INFO, "Generating KEY at SIM\n");
845
846         /* command to SIM */
847         nmsg = gsm_sim_msgb_alloc(subscr->sim_handle_key, SIM_JOB_RUN_GSM_ALGO);
848         if (!nmsg)
849                 return -ENOMEM;
850         nsh = (struct sim_hdr *) nmsg->data;
851         nsh->path[0] = 0x7f20;
852         nsh->path[1] = 0;
853
854         /* random */
855         memcpy(msgb_put(nmsg, 16), rand, 16);
856
857         /* store sequence */
858         subscr->key_seq = key_seq;
859
860         sim_job(ms, nmsg);
861
862         return 0;
863 }
864
865 static void subscr_sim_key_cb(struct osmocom_ms *ms, struct msgb *msg)
866 {
867         struct gsm_subscriber *subscr = &ms->subscr;
868         struct sim_hdr *sh = (struct sim_hdr *) msg->data;
869         uint8_t *payload = msg->data + sizeof(*sh);
870         uint16_t payload_len = msg->len - sizeof(*sh);
871         struct msgb *nmsg;
872         struct sim_hdr *nsh;
873         struct gsm48_mm_event *nmme;
874         uint8_t *data;
875
876         /* error handling */
877         if (sh->job_type == SIM_JOB_ERROR) {
878                 LOGP(DMM, LOGL_NOTICE, "key generation on SIM failed "
879                         "(cause %d)\n", *payload);
880
881                 msgb_free(msg);
882
883                 return;
884         }
885
886         if (payload_len < 12) {
887                 LOGP(DMM, LOGL_NOTICE, "response from SIM too short\n");
888                 return;
889         }
890
891         /* store key */
892         memcpy(subscr->key, payload + 4, 8);
893
894         /* write to SIM */
895         LOGP(DMM, LOGL_INFO, "Updating KC on SIM\n");
896         nmsg = gsm_sim_msgb_alloc(subscr->sim_handle_update,
897                 SIM_JOB_UPDATE_BINARY);
898         if (!nmsg)
899                 return;
900         nsh = (struct sim_hdr *) nmsg->data;
901         nsh->path[0] = 0x7f20;
902         nsh->path[1] = 0;
903         nsh->file = 0x6f20;
904         data = msgb_put(nmsg, 9);
905         memcpy(data, subscr->key, 8);
906         data[8] = subscr->key_seq;
907         sim_job(ms, nmsg);
908
909         /* return signed response */
910         nmsg = gsm48_mmevent_msgb_alloc(GSM48_MM_EVENT_AUTH_RESPONSE);
911         if (!nmsg)
912                 return;
913         nmme = (struct gsm48_mm_event *) nmsg->data;
914         memcpy(nmme->sres, payload, 4);
915         gsm48_mmevent_msg(ms, nmsg);
916
917         msgb_free(msg);
918 }
919
920 /*
921  * detach
922  */
923
924 /* Detach card */
925 int gsm_subscr_remove(struct osmocom_ms *ms)
926 {
927         struct gsm_subscriber *subscr = &ms->subscr;
928         struct msgb *nmsg;
929
930         if (!subscr->sim_valid) {
931                 LOGP(DMM, LOGL_ERROR, "Cannot remove card, no card present\n");
932                 return -EINVAL;
933         }
934
935         /* remove card */
936         nmsg = gsm48_mmr_msgb_alloc(GSM48_MMR_NREG_REQ);
937         if (!nmsg)
938                 return -ENOMEM;
939         gsm48_mmr_downmsg(ms, nmsg);
940
941         return 0;
942 }
943
944 /*
945  * state and lists
946  */
947
948 static const char *subscr_ustate_names[] = {
949         "U0_NULL",
950         "U1_UPDATED",
951         "U2_NOT_UPDATED",
952         "U3_ROAMING_NA"
953 };
954
955 /* change to new U state */
956 void new_sim_ustate(struct gsm_subscriber *subscr, int state)
957 {
958         LOGP(DMM, LOGL_INFO, "(ms %s) new state %s -> %s\n", subscr->ms->name,
959                 subscr_ustate_names[subscr->ustate],
960                 subscr_ustate_names[state]);
961
962         subscr->ustate = state;
963 }
964
965 /* del forbidden PLMN */
966 int gsm_subscr_del_forbidden_plmn(struct gsm_subscriber *subscr, uint16_t mcc,
967         uint16_t mnc)
968 {
969         struct gsm_sub_plmn_na *na;
970
971         llist_for_each_entry(na, &subscr->plmn_na, entry) {
972                 if (na->mcc == mcc && na->mnc == mnc) {
973                         LOGP(DPLMN, LOGL_INFO, "Delete from list of forbidden "
974                                 "PLMNs (mcc=%s, mnc=%s)\n",
975                                 gsm_print_mcc(mcc), gsm_print_mnc(mnc));
976                         llist_del(&na->entry);
977                         talloc_free(na);
978                         /* update plmn not allowed list on SIM */
979                         subscr_write_plmn_na(subscr->ms);
980                         return 0;
981                 }
982         }
983
984         return -EINVAL;
985 }
986
987 /* add forbidden PLMN */
988 int gsm_subscr_add_forbidden_plmn(struct gsm_subscriber *subscr, uint16_t mcc,
989                                         uint16_t mnc, uint8_t cause)
990 {
991         struct gsm_sub_plmn_na *na;
992
993         /* if already in the list, remove and add to tail */
994         gsm_subscr_del_forbidden_plmn(subscr, mcc, mnc);
995
996         LOGP(DPLMN, LOGL_INFO, "Add to list of forbidden PLMNs "
997                 "(mcc=%s, mnc=%s)\n", gsm_print_mcc(mcc), gsm_print_mnc(mnc));
998         na = talloc_zero(l23_ctx, struct gsm_sub_plmn_na);
999         if (!na)
1000                 return -ENOMEM;
1001         na->mcc = mcc;
1002         na->mnc = mnc;
1003         na->cause = cause;
1004         llist_add_tail(&na->entry, &subscr->plmn_na);
1005
1006         /* don't add Home PLMN to SIM */
1007         if (subscr->sim_valid && gsm_match_mnc(mcc, mnc, subscr->imsi))
1008                 return -EINVAL;
1009
1010         /* update plmn not allowed list on SIM */
1011         subscr_write_plmn_na(subscr->ms);
1012
1013         return 0;
1014 }
1015
1016 /* search forbidden PLMN */
1017 int gsm_subscr_is_forbidden_plmn(struct gsm_subscriber *subscr, uint16_t mcc,
1018                                         uint16_t mnc)
1019 {
1020         struct gsm_sub_plmn_na *na;
1021
1022         llist_for_each_entry(na, &subscr->plmn_na, entry) {
1023                 if (na->mcc == mcc && na->mnc == mnc)
1024                         return 1;
1025         }
1026
1027         return 0;
1028 }
1029
1030 int gsm_subscr_dump_forbidden_plmn(struct osmocom_ms *ms,
1031                         void (*print)(void *, const char *, ...), void *priv)
1032 {
1033         struct gsm_subscriber *subscr = &ms->subscr;
1034         struct gsm_sub_plmn_na *temp;
1035
1036         print(priv, "MCC    |MNC    |cause\n");
1037         print(priv, "-------+-------+-------\n");
1038         llist_for_each_entry(temp, &subscr->plmn_na, entry)
1039                 print(priv, "%s    |%s%s    |#%d\n",
1040                         gsm_print_mcc(temp->mcc), gsm_print_mnc(temp->mnc),
1041                         ((temp->mnc & 0x00f) == 0x00f) ? " ":"", temp->cause);
1042
1043         return 0;
1044 }
1045
1046 /* dump subscriber */
1047 void gsm_subscr_dump(struct gsm_subscriber *subscr,
1048                         void (*print)(void *, const char *, ...), void *priv)
1049 {
1050         int i;
1051         struct gsm_sub_plmn_list *plmn_list;
1052         struct gsm_sub_plmn_na *plmn_na;
1053
1054         print(priv, "Mobile Subscriber of MS '%s':\n", subscr->ms->name);
1055
1056         if (!subscr->sim_valid) {
1057                 print(priv, " No SIM present.\n");
1058                 return;
1059         }
1060
1061         print(priv, " IMSI: %s\n", subscr->imsi);
1062         if (subscr->msisdn[0])
1063                 print(priv, " MSISDN: %s\n", subscr->msisdn);
1064         print(priv, " Status: %s  IMSI %s", subscr_ustate_names[subscr->ustate],
1065                 (subscr->imsi_attached) ? "attached" : "detached");
1066         if (subscr->tmsi != 0xffffffff)
1067                 print(priv, "  TSMI  %08x", subscr->tmsi);
1068         if (subscr->lac > 0x0000 && subscr->lac < 0xfffe)
1069                 print(priv, "  LAI: MCC %s  MNC %s  LAC 0x%04x  (%s, %s)\n",
1070                         gsm_print_mcc(subscr->mcc),
1071                         gsm_print_mnc(subscr->mnc), subscr->lac,
1072                         gsm_get_mcc(subscr->mcc),
1073                         gsm_get_mnc(subscr->mcc, subscr->mnc));
1074         else
1075                 print(priv, "  LAI: invalid\n");
1076         if (subscr->key_seq != 7) {
1077                 print(priv, " Key: sequence %d ");
1078                 for (i = 0; i < sizeof(subscr->key); i++)
1079                         print(priv, " %02x", subscr->key[i]);
1080                 print(priv, "\n");
1081         }
1082         if (subscr->plmn_valid)
1083                 print(priv, " Registered PLMN: MCC %s  MNC %s  (%s, %s)\n",
1084                         gsm_print_mcc(subscr->plmn_mcc),
1085                         gsm_print_mnc(subscr->plmn_mnc),
1086                         gsm_get_mcc(subscr->plmn_mcc),
1087                         gsm_get_mnc(subscr->plmn_mcc, subscr->plmn_mnc));
1088         print(priv, " Access barred cells: %s\n",
1089                 (subscr->acc_barr) ? "yes" : "no");
1090         print(priv, " Access classes:");
1091         for (i = 0; i < 16; i++)
1092                 if ((subscr->acc_class & (1 << i)))
1093                         print(priv, " C%d", i);
1094         print(priv, "\n");
1095         if (!llist_empty(&subscr->plmn_list)) {
1096                 print(priv, " List of preferred PLMNs:\n");
1097                 print(priv, "        MCC    |MNC\n");
1098                 print(priv, "        -------+-------\n");
1099                 llist_for_each_entry(plmn_list, &subscr->plmn_list, entry)
1100                         print(priv, "        %s    |%s\n",
1101                         gsm_print_mcc(plmn_list->mcc),
1102                         gsm_print_mnc(plmn_list->mnc));
1103         }
1104         if (!llist_empty(&subscr->plmn_na)) {
1105                 print(priv, " List of forbidden PLMNs:\n");
1106                 print(priv, "        MCC    |MNC    |cause\n");
1107                 print(priv, "        -------+-------+-------\n");
1108                 llist_for_each_entry(plmn_na, &subscr->plmn_na, entry)
1109                         print(priv, "        %s    |%s%s    |#%d\n",
1110                                 gsm_print_mcc(plmn_na->mcc),
1111                                 gsm_print_mnc(plmn_na->mnc),
1112                                 ((plmn_na->mnc & 0x00f) == 0x00f) ? " ":"",
1113                                 plmn_na->cause);
1114         }
1115 }
1116