0792b1cabb063854620394adb5f9272ab6dd2985
[platform/upstream/ofono.git] / src / sim.c
1 /*
2  *
3  *  oFono - Open Source Telephony
4  *
5  *  Copyright (C) 2008-2010  Intel Corporation. All rights reserved.
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 version 2 as
9  *  published by the Free Software Foundation.
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
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #define _GNU_SOURCE
27 #include <string.h>
28 #include <stdio.h>
29
30 #include <glib.h>
31 #include <gdbus.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <unistd.h>
37
38 #include "ofono.h"
39
40 #include "common.h"
41 #include "util.h"
42 #include "smsutil.h"
43 #include "simutil.h"
44 #include "storage.h"
45 #include "simfs.h"
46 #include "stkutil.h"
47
48 static GSList *g_drivers = NULL;
49
50 static void sim_own_numbers_update(struct ofono_sim *sim);
51 static void sim_pin_check(struct ofono_sim *sim);
52 static void sim_set_ready(struct ofono_sim *sim);
53
54 struct ofono_sim {
55         /* Contents of the SIM file system, in rough initialization order */
56         char *iccid;
57
58         char **language_prefs;
59         unsigned char *efli;
60         unsigned char efli_length;
61
62         enum ofono_sim_password_type pin_type;
63         gboolean locked_pins[OFONO_SIM_PASSWORD_SIM_PUK]; /* Number of PINs */
64
65         enum ofono_sim_phase phase;
66         unsigned char mnc_length;
67         enum ofono_sim_cphs_phase cphs_phase;
68         unsigned char cphs_service_table[2];
69         unsigned char *efust;
70         unsigned char efust_length;
71         unsigned char *efest;
72         unsigned char efest_length;
73         unsigned char *efsst;
74         unsigned char efsst_length;
75         gboolean fixed_dialing;
76         gboolean barred_dialing;
77
78         char *imsi;
79
80         GSList *own_numbers;
81         GSList *new_numbers;
82         unsigned char efmsisdn_length;
83         unsigned char efmsisdn_records;
84
85         GSList *service_numbers;
86         gboolean sdn_ready;
87
88         unsigned char *efimg;
89         unsigned short efimg_length;
90
91         enum ofono_sim_state state;
92         struct ofono_watchlist *state_watches;
93
94         struct sim_fs *simfs;
95
96         unsigned char *iidf_image;
97
98         DBusMessage *pending;
99         const struct ofono_sim_driver *driver;
100         void *driver_data;
101         struct ofono_atom *atom;
102 };
103
104 struct msisdn_set_request {
105         struct ofono_sim *sim;
106         int pending;
107         int failed;
108         DBusMessage *msg;
109 };
110
111 struct service_number {
112         char *id;
113         struct ofono_phone_number ph;
114 };
115
116 static const char *const passwd_name[] = {
117         [OFONO_SIM_PASSWORD_NONE] = "none",
118         [OFONO_SIM_PASSWORD_SIM_PIN] = "pin",
119         [OFONO_SIM_PASSWORD_SIM_PUK] = "puk",
120         [OFONO_SIM_PASSWORD_PHSIM_PIN] = "phone",
121         [OFONO_SIM_PASSWORD_PHFSIM_PIN] = "firstphone",
122         [OFONO_SIM_PASSWORD_PHFSIM_PUK] = "firstphonepuk",
123         [OFONO_SIM_PASSWORD_SIM_PIN2] = "pin2",
124         [OFONO_SIM_PASSWORD_SIM_PUK2] = "puk2",
125         [OFONO_SIM_PASSWORD_PHNET_PIN] = "network",
126         [OFONO_SIM_PASSWORD_PHNET_PUK] = "networkpuk",
127         [OFONO_SIM_PASSWORD_PHNETSUB_PIN] = "netsub",
128         [OFONO_SIM_PASSWORD_PHNETSUB_PUK] = "netsubpuk",
129         [OFONO_SIM_PASSWORD_PHSP_PIN] = "service",
130         [OFONO_SIM_PASSWORD_PHSP_PUK] = "servicepuk",
131         [OFONO_SIM_PASSWORD_PHCORP_PIN] = "corp",
132         [OFONO_SIM_PASSWORD_PHCORP_PUK] = "corppuk",
133 };
134
135 static const char *sim_passwd_name(enum ofono_sim_password_type type)
136 {
137         return passwd_name[type];
138 }
139
140 static enum ofono_sim_password_type sim_string_to_passwd(const char *name)
141 {
142         int len = sizeof(passwd_name) / sizeof(*passwd_name);
143         int i;
144
145         for (i = 0; i < len; i++)
146                 if (!strcmp(passwd_name[i], name))
147                         return i;
148
149         return OFONO_SIM_PASSWORD_INVALID;
150 }
151
152 static gboolean password_is_pin(enum ofono_sim_password_type type)
153 {
154         switch (type) {
155         case OFONO_SIM_PASSWORD_SIM_PIN:
156         case OFONO_SIM_PASSWORD_PHSIM_PIN:
157         case OFONO_SIM_PASSWORD_PHFSIM_PIN:
158         case OFONO_SIM_PASSWORD_SIM_PIN2:
159         case OFONO_SIM_PASSWORD_PHNET_PIN:
160         case OFONO_SIM_PASSWORD_PHNETSUB_PIN:
161         case OFONO_SIM_PASSWORD_PHSP_PIN:
162         case OFONO_SIM_PASSWORD_PHCORP_PIN:
163                 return TRUE;
164         case OFONO_SIM_PASSWORD_SIM_PUK:
165         case OFONO_SIM_PASSWORD_PHFSIM_PUK:
166         case OFONO_SIM_PASSWORD_SIM_PUK2:
167         case OFONO_SIM_PASSWORD_PHNET_PUK:
168         case OFONO_SIM_PASSWORD_PHNETSUB_PUK:
169         case OFONO_SIM_PASSWORD_PHSP_PUK:
170         case OFONO_SIM_PASSWORD_PHCORP_PUK:
171         case OFONO_SIM_PASSWORD_INVALID:
172         case OFONO_SIM_PASSWORD_NONE:
173                 return FALSE;
174         }
175
176         return FALSE;
177 }
178
179 static enum ofono_sim_password_type puk2pin(enum ofono_sim_password_type type)
180 {
181         switch (type) {
182         case OFONO_SIM_PASSWORD_SIM_PUK:
183                 return OFONO_SIM_PASSWORD_SIM_PIN;
184         case OFONO_SIM_PASSWORD_PHFSIM_PUK:
185                 return OFONO_SIM_PASSWORD_PHFSIM_PIN;
186         case OFONO_SIM_PASSWORD_SIM_PUK2:
187                 return OFONO_SIM_PASSWORD_SIM_PIN2;
188         case OFONO_SIM_PASSWORD_PHNET_PUK:
189                 return OFONO_SIM_PASSWORD_PHNET_PUK;
190         case OFONO_SIM_PASSWORD_PHNETSUB_PUK:
191                 return OFONO_SIM_PASSWORD_PHNETSUB_PIN;
192         case OFONO_SIM_PASSWORD_PHSP_PUK:
193                 return OFONO_SIM_PASSWORD_PHSP_PIN;
194         case OFONO_SIM_PASSWORD_PHCORP_PUK:
195                 return OFONO_SIM_PASSWORD_PHCORP_PIN;
196         default:
197                 return OFONO_SIM_PASSWORD_INVALID;
198         }
199 }
200
201 static char **get_own_numbers(GSList *own_numbers)
202 {
203         int nelem = 0;
204         GSList *l;
205         struct ofono_phone_number *num;
206         char **ret;
207
208         if (own_numbers)
209                 nelem = g_slist_length(own_numbers);
210
211         ret = g_new0(char *, nelem + 1);
212
213         nelem = 0;
214         for (l = own_numbers; l; l = l->next) {
215                 num = l->data;
216
217                 ret[nelem++] = g_strdup(phone_number_to_string(num));
218         }
219
220         return ret;
221 }
222
223 static char **get_locked_pins(struct ofono_sim *sim)
224 {
225         int i;
226         int nelem = 0;
227         char **ret;
228
229         for (i = 1; i < OFONO_SIM_PASSWORD_SIM_PUK; i++) {
230                 if (sim->locked_pins[i] == FALSE)
231                         continue;
232
233                 nelem += 1;
234         }
235
236         ret = g_new0(char *, nelem + 1);
237
238         nelem = 0;
239
240         for (i = 1; i < OFONO_SIM_PASSWORD_SIM_PUK; i++) {
241                 if (sim->locked_pins[i] == FALSE)
242                         continue;
243
244                 ret[nelem] = g_strdup(sim_passwd_name(i));
245                 nelem += 1;
246         }
247
248         return ret;
249 }
250
251 static char **get_service_numbers(GSList *service_numbers)
252 {
253         int nelem;
254         GSList *l;
255         struct service_number *num;
256         char **ret;
257
258         nelem = g_slist_length(service_numbers) * 2;
259
260         ret = g_new0(char *, nelem + 1);
261
262         nelem = 0;
263         for (l = service_numbers; l; l = l->next) {
264                 num = l->data;
265
266                 ret[nelem++] = g_strdup(num->id);
267                 ret[nelem++] = g_strdup(phone_number_to_string(&num->ph));
268         }
269
270         return ret;
271 }
272
273 static void service_number_free(struct service_number *num)
274 {
275         g_free(num->id);
276         g_free(num);
277 }
278
279 static DBusMessage *sim_get_properties(DBusConnection *conn,
280                                         DBusMessage *msg, void *data)
281 {
282         struct ofono_sim *sim = data;
283         DBusMessage *reply;
284         DBusMessageIter iter;
285         DBusMessageIter dict;
286         char **own_numbers;
287         char **service_numbers;
288         char **locked_pins;
289         const char *pin_name;
290         dbus_bool_t present = sim->state != OFONO_SIM_STATE_NOT_PRESENT;
291         dbus_bool_t fdn;
292         dbus_bool_t bdn;
293
294         reply = dbus_message_new_method_return(msg);
295         if (!reply)
296                 return NULL;
297
298         dbus_message_iter_init_append(reply, &iter);
299
300         dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
301                                         OFONO_PROPERTIES_ARRAY_SIGNATURE,
302                                         &dict);
303
304         ofono_dbus_dict_append(&dict, "Present", DBUS_TYPE_BOOLEAN, &present);
305
306         if (!present)
307                 goto done;
308
309         if (sim->iccid)
310                 ofono_dbus_dict_append(&dict, "CardIdentifier",
311                                         DBUS_TYPE_STRING, &sim->iccid);
312
313         if (sim->imsi)
314                 ofono_dbus_dict_append(&dict, "SubscriberIdentity",
315                                         DBUS_TYPE_STRING, &sim->imsi);
316
317         fdn = sim->fixed_dialing;
318         ofono_dbus_dict_append(&dict, "FixedDialing", DBUS_TYPE_BOOLEAN, &fdn);
319
320         bdn = sim->barred_dialing;
321         ofono_dbus_dict_append(&dict, "BarredDialing", DBUS_TYPE_BOOLEAN, &bdn);
322
323         if (sim->mnc_length && sim->imsi) {
324                 char mcc[OFONO_MAX_MCC_LENGTH + 1];
325                 char mnc[OFONO_MAX_MNC_LENGTH + 1];
326                 const char *str;
327
328                 strncpy(mcc, sim->imsi, OFONO_MAX_MCC_LENGTH);
329                 mcc[OFONO_MAX_MCC_LENGTH] = '\0';
330                 strncpy(mnc, sim->imsi + OFONO_MAX_MCC_LENGTH, sim->mnc_length);
331                 mnc[sim->mnc_length] = '\0';
332
333                 str = mcc;
334                 ofono_dbus_dict_append(&dict, "MobileCountryCode",
335                                         DBUS_TYPE_STRING, &str);
336
337                 str = mnc;
338                 ofono_dbus_dict_append(&dict, "MobileNetworkCode",
339                                         DBUS_TYPE_STRING, &str);
340         }
341
342         own_numbers = get_own_numbers(sim->own_numbers);
343
344         ofono_dbus_dict_append_array(&dict, "SubscriberNumbers",
345                                         DBUS_TYPE_STRING, &own_numbers);
346         g_strfreev(own_numbers);
347
348         locked_pins = get_locked_pins(sim);
349         ofono_dbus_dict_append_array(&dict, "LockedPins",
350                                         DBUS_TYPE_STRING, &locked_pins);
351         g_strfreev(locked_pins);
352
353         if (sim->service_numbers && sim->sdn_ready) {
354                 service_numbers = get_service_numbers(sim->service_numbers);
355
356                 ofono_dbus_dict_append_dict(&dict, "ServiceNumbers",
357                                                 DBUS_TYPE_STRING,
358                                                 &service_numbers);
359                 g_strfreev(service_numbers);
360         }
361
362         if (sim->language_prefs)
363                 ofono_dbus_dict_append_array(&dict, "PreferredLanguages",
364                                                 DBUS_TYPE_STRING,
365                                                 &sim->language_prefs);
366
367         pin_name = sim_passwd_name(sim->pin_type);
368         ofono_dbus_dict_append(&dict, "PinRequired",
369                                 DBUS_TYPE_STRING,
370                                 (void *) &pin_name);
371
372 done:
373         dbus_message_iter_close_container(&iter, &dict);
374
375         return reply;
376 }
377
378 static void msisdn_set_done(struct msisdn_set_request *req)
379 {
380         DBusMessage *reply;
381
382         if (req->failed)
383                 reply = __ofono_error_failed(req->msg);
384         else
385                 reply = dbus_message_new_method_return(req->msg);
386
387         __ofono_dbus_pending_reply(&req->msg, reply);
388
389         /* Re-read the numbers and emit signal if needed */
390         sim_own_numbers_update(req->sim);
391
392         g_free(req);
393 }
394
395 static void msisdn_set_cb(int ok, void *data)
396 {
397         struct msisdn_set_request *req = data;
398
399         if (!ok)
400                 req->failed++;
401
402         req->pending--;
403
404         if (!req->pending)
405                 msisdn_set_done(req);
406 }
407
408 static gboolean set_own_numbers(struct ofono_sim *sim,
409                                 GSList *new_numbers, DBusMessage *msg)
410 {
411         struct msisdn_set_request *req;
412         int record;
413         unsigned char efmsisdn[255];
414         struct ofono_phone_number *number;
415
416         if (new_numbers && g_slist_length(new_numbers) > sim->efmsisdn_records)
417                 return FALSE;
418
419         req = g_new0(struct msisdn_set_request, 1);
420
421         req->sim = sim;
422         req->msg = dbus_message_ref(msg);
423
424         for (record = 1; record <= sim->efmsisdn_records; record++) {
425                 if (new_numbers) {
426                         number = new_numbers->data;
427                         sim_adn_build(efmsisdn, sim->efmsisdn_length,
428                                         number, NULL);
429                         new_numbers = new_numbers->next;
430                 } else {
431                         memset(efmsisdn, 0xff, sim->efmsisdn_length);
432                 }
433
434                 if (ofono_sim_write(req->sim, SIM_EFMSISDN_FILEID,
435                                 msisdn_set_cb, OFONO_SIM_FILE_STRUCTURE_FIXED,
436                                 record, efmsisdn,
437                                 sim->efmsisdn_length, req) == 0)
438                         req->pending++;
439                 else
440                         req->failed++;
441         }
442
443         if (!req->pending)
444                 msisdn_set_done(req);
445
446         return TRUE;
447 }
448
449 static DBusMessage *sim_set_property(DBusConnection *conn, DBusMessage *msg,
450                                         void *data)
451 {
452         struct ofono_sim *sim = data;
453         DBusMessageIter iter;
454         DBusMessageIter var;
455         DBusMessageIter var_elem;
456         const char *name, *value;
457
458         if (!dbus_message_iter_init(msg, &iter))
459                 return __ofono_error_invalid_args(msg);
460
461         if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
462                 return __ofono_error_invalid_args(msg);
463
464         dbus_message_iter_get_basic(&iter, &name);
465
466         if (!strcmp(name, "SubscriberNumbers")) {
467                 gboolean set_ok = FALSE;
468                 struct ofono_phone_number *own;
469                 GSList *own_numbers = NULL;
470
471                 if (sim->efmsisdn_length == 0)
472                         return __ofono_error_busy(msg);
473
474                 dbus_message_iter_next(&iter);
475
476                 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
477                         return __ofono_error_invalid_args(msg);
478
479                 dbus_message_iter_recurse(&iter, &var);
480
481                 if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_ARRAY ||
482                                 dbus_message_iter_get_element_type(&var) !=
483                                 DBUS_TYPE_STRING)
484                         return __ofono_error_invalid_args(msg);
485
486                 dbus_message_iter_recurse(&var, &var_elem);
487
488                 /* Empty lists are supported */
489                 while (dbus_message_iter_get_arg_type(&var_elem) !=
490                                 DBUS_TYPE_INVALID) {
491                         if (dbus_message_iter_get_arg_type(&var_elem) !=
492                                         DBUS_TYPE_STRING)
493                                 goto error;
494
495                         dbus_message_iter_get_basic(&var_elem, &value);
496
497                         if (!valid_phone_number_format(value))
498                                 goto error;
499
500                         own = g_new0(struct ofono_phone_number, 1);
501                         string_to_phone_number(value, own);
502
503                         own_numbers = g_slist_prepend(own_numbers, own);
504
505                         dbus_message_iter_next(&var_elem);
506                 }
507
508                 own_numbers = g_slist_reverse(own_numbers);
509                 set_ok = set_own_numbers(sim, own_numbers, msg);
510
511 error:
512                 g_slist_foreach(own_numbers, (GFunc) g_free, 0);
513                 g_slist_free(own_numbers);
514
515                 if (set_ok)
516                         return NULL;
517         }
518
519         return __ofono_error_invalid_args(msg);
520 }
521
522 static void sim_locked_cb(struct ofono_sim *sim, gboolean locked)
523 {
524         DBusConnection *conn = ofono_dbus_get_connection();
525         const char *path = __ofono_atom_get_path(sim->atom);
526         const char *typestr;
527         const char *pin;
528         char **locked_pins;
529         enum ofono_sim_password_type type;
530         DBusMessage *reply;
531
532         reply = dbus_message_new_method_return(sim->pending);
533
534         dbus_message_get_args(sim->pending, NULL, DBUS_TYPE_STRING, &typestr,
535                                         DBUS_TYPE_STRING, &pin,
536                                         DBUS_TYPE_INVALID);
537
538         type = sim_string_to_passwd(typestr);
539
540         /* This is used by lock/unlock pin, no puks allowed */
541         sim->locked_pins[type] = locked;
542         __ofono_dbus_pending_reply(&sim->pending, reply);
543
544         locked_pins = get_locked_pins(sim);
545         ofono_dbus_signal_array_property_changed(conn, path,
546                                                 OFONO_SIM_MANAGER_INTERFACE,
547                                                 "LockedPins", DBUS_TYPE_STRING,
548                                                 &locked_pins);
549         g_strfreev(locked_pins);
550 }
551
552 static void sim_unlock_cb(const struct ofono_error *error, void *data)
553 {
554         struct ofono_sim *sim = data;
555
556         if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
557                 DBusMessage *reply = __ofono_error_failed(sim->pending);
558                 __ofono_dbus_pending_reply(&sim->pending, reply);
559                 return;
560         }
561
562         sim_locked_cb(sim, FALSE);
563 }
564
565 static void sim_lock_cb(const struct ofono_error *error, void *data)
566 {
567         struct ofono_sim *sim = data;
568
569         if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
570                 DBusMessage *reply = __ofono_error_failed(sim->pending);
571                 __ofono_dbus_pending_reply(&sim->pending, reply);
572                 return;
573         }
574
575         sim_locked_cb(sim, TRUE);
576 }
577
578 static DBusMessage *sim_lock_or_unlock(struct ofono_sim *sim, int lock,
579                                         DBusConnection *conn, DBusMessage *msg)
580 {
581         enum ofono_sim_password_type type;
582         const char *typestr;
583         const char *pin;
584
585         if (!sim->driver->lock)
586                 return __ofono_error_not_implemented(msg);
587
588         if (sim->pending)
589                 return __ofono_error_busy(msg);
590
591         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &typestr,
592                                         DBUS_TYPE_STRING, &pin,
593                                         DBUS_TYPE_INVALID) == FALSE)
594                 return __ofono_error_invalid_args(msg);
595
596         type = sim_string_to_passwd(typestr);
597
598         /*
599          * SIM PIN2 cannot be locked / unlocked according to 27.007,
600          * however the PIN combination can be changed
601          */
602         if (password_is_pin(type) == FALSE ||
603                         type == OFONO_SIM_PASSWORD_SIM_PIN2)
604                 return __ofono_error_invalid_format(msg);
605
606         if (!is_valid_pin(pin, PIN_TYPE_PIN))
607                 return __ofono_error_invalid_format(msg);
608
609         sim->pending = dbus_message_ref(msg);
610
611         sim->driver->lock(sim, type, lock, pin,
612                                 lock ? sim_lock_cb : sim_unlock_cb, sim);
613
614         return NULL;
615 }
616
617 static DBusMessage *sim_lock_pin(DBusConnection *conn, DBusMessage *msg,
618                                         void *data)
619 {
620         struct ofono_sim *sim = data;
621
622         return sim_lock_or_unlock(sim, 1, conn, msg);
623 }
624
625 static DBusMessage *sim_unlock_pin(DBusConnection *conn, DBusMessage *msg,
626                                         void *data)
627 {
628         struct ofono_sim *sim = data;
629
630         return sim_lock_or_unlock(sim, 0, conn, msg);
631 }
632
633 static void sim_change_pin_cb(const struct ofono_error *error, void *data)
634 {
635         struct ofono_sim *sim = data;
636
637         if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
638                 __ofono_dbus_pending_reply(&sim->pending,
639                                 __ofono_error_failed(sim->pending));
640                 return;
641         }
642
643         __ofono_dbus_pending_reply(&sim->pending,
644                                 dbus_message_new_method_return(sim->pending));
645 }
646
647 static DBusMessage *sim_change_pin(DBusConnection *conn, DBusMessage *msg,
648                                         void *data)
649 {
650         struct ofono_sim *sim = data;
651         enum ofono_sim_password_type type;
652         const char *typestr;
653         const char *old;
654         const char *new;
655
656         if (!sim->driver->change_passwd)
657                 return __ofono_error_not_implemented(msg);
658
659         if (sim->pending)
660                 return __ofono_error_busy(msg);
661
662         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &typestr,
663                                         DBUS_TYPE_STRING, &old,
664                                         DBUS_TYPE_STRING, &new,
665                                         DBUS_TYPE_INVALID) == FALSE)
666                 return __ofono_error_invalid_args(msg);
667
668         type = sim_string_to_passwd(typestr);
669
670         if (password_is_pin(type) == FALSE)
671                 return __ofono_error_invalid_format(msg);
672
673         if (!is_valid_pin(old, PIN_TYPE_PIN))
674                 return __ofono_error_invalid_format(msg);
675
676         if (!is_valid_pin(new, PIN_TYPE_PIN))
677                 return __ofono_error_invalid_format(msg);
678
679         if (!strcmp(new, old))
680                 return dbus_message_new_method_return(msg);
681
682         sim->pending = dbus_message_ref(msg);
683         sim->driver->change_passwd(sim, type, old, new,
684                                         sim_change_pin_cb, sim);
685
686         return NULL;
687 }
688
689 static void sim_enter_pin_cb(const struct ofono_error *error, void *data)
690 {
691         struct ofono_sim *sim = data;
692         DBusMessage *reply;
693
694         if (error->type != OFONO_ERROR_TYPE_NO_ERROR)
695                 reply = __ofono_error_failed(sim->pending);
696         else
697                 reply = dbus_message_new_method_return(sim->pending);
698
699         __ofono_dbus_pending_reply(&sim->pending, reply);
700
701         sim_pin_check(sim);
702 }
703
704 static DBusMessage *sim_enter_pin(DBusConnection *conn, DBusMessage *msg,
705                                         void *data)
706 {
707         struct ofono_sim *sim = data;
708         const char *typestr;
709         enum ofono_sim_password_type type;
710         const char *pin;
711
712         if (!sim->driver->send_passwd)
713                 return __ofono_error_not_implemented(msg);
714
715         if (sim->pending)
716                 return __ofono_error_busy(msg);
717
718         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &typestr,
719                                         DBUS_TYPE_STRING, &pin,
720                                         DBUS_TYPE_INVALID) == FALSE)
721                 return __ofono_error_invalid_args(msg);
722
723         type = sim_string_to_passwd(typestr);
724
725         if (type == OFONO_SIM_PASSWORD_NONE || type != sim->pin_type)
726                 return __ofono_error_invalid_format(msg);
727
728         if (!is_valid_pin(pin, PIN_TYPE_PIN))
729                 return __ofono_error_invalid_format(msg);
730
731         sim->pending = dbus_message_ref(msg);
732         sim->driver->send_passwd(sim, pin, sim_enter_pin_cb, sim);
733
734         return NULL;
735 }
736
737 static void sim_get_image_cb(struct ofono_sim *sim,
738                                 unsigned char id, char *xpm, gboolean cache)
739 {
740         DBusMessage *reply;
741         DBusMessageIter iter, array;
742         int xpm_len;
743
744         if (xpm == NULL) {
745                 reply = __ofono_error_failed(sim->pending);
746                 __ofono_dbus_pending_reply(&sim->pending, reply);
747                 return;
748         }
749
750         xpm_len = strlen(xpm);
751
752         reply = dbus_message_new_method_return(sim->pending);
753         dbus_message_iter_init_append(reply, &iter);
754
755         dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
756                                         DBUS_TYPE_BYTE_AS_STRING, &array);
757
758         dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE,
759                                                 &xpm, xpm_len);
760         dbus_message_iter_close_container(&iter, &array);
761
762         __ofono_dbus_pending_reply(&sim->pending, reply);
763
764         if (cache)
765                 sim_fs_cache_image(sim->simfs, (const char *) xpm, id);
766
767         g_free(xpm);
768 }
769
770 static void sim_iidf_read_clut_cb(int ok, int length, int record,
771                                         const unsigned char *data,
772                                         int record_length, void *userdata)
773 {
774         struct ofono_sim *sim = userdata;
775         unsigned char id;
776         unsigned char *efimg;
777         unsigned short iidf_len;
778         unsigned short clut_len;
779         char *xpm;
780
781         DBG("ok: %d", ok);
782
783         dbus_message_get_args(sim->pending, NULL, DBUS_TYPE_BYTE, &id,
784                                         DBUS_TYPE_INVALID);
785         id -= 1;
786         efimg = &sim->efimg[id * 9];
787
788         if (!ok) {
789                 sim_get_image_cb(sim, id, NULL, FALSE);
790                 goto done;
791         }
792
793         iidf_len = efimg[7] << 8 | efimg[8];
794
795         if (sim->iidf_image[3] == 0)
796                 clut_len = 256 * 3;
797         else
798                 clut_len = sim->iidf_image[3] * 3;
799
800         xpm = stk_image_to_xpm(sim->iidf_image, iidf_len, efimg[2],
801                                         data, clut_len);
802         sim_get_image_cb(sim, id, xpm, TRUE);
803
804 done:
805         g_free(sim->iidf_image);
806         sim->iidf_image = NULL;
807 }
808
809 static void sim_iidf_read_cb(int ok, int length, int record,
810                                 const unsigned char *data,
811                                 int record_length, void *userdata)
812 {
813         struct ofono_sim *sim = userdata;
814         unsigned char id;
815         unsigned char *efimg;
816         unsigned short iidf_id;
817         unsigned short offset;
818         unsigned short clut_len;
819
820         DBG("ok: %d", ok);
821
822         dbus_message_get_args(sim->pending, NULL, DBUS_TYPE_BYTE, &id,
823                                         DBUS_TYPE_INVALID);
824         id -= 1;
825         efimg = &sim->efimg[id * 9];
826
827         if (!ok) {
828                 sim_get_image_cb(sim, id, NULL, FALSE);
829                 return;
830         }
831
832         if (efimg[2] == STK_IMG_SCHEME_BASIC) {
833                 char *xpm = stk_image_to_xpm(data, length, efimg[2], NULL, 0);
834                 sim_get_image_cb(sim, id, xpm, TRUE);
835                 return;
836         }
837
838         offset = data[4] << 8 | data[5];
839
840         if (data[3] == 0)
841                 clut_len = 256 * 3;
842         else
843                 clut_len = data[3] * 3;
844
845         iidf_id = efimg[3] << 8 | efimg[4];
846         sim->iidf_image = g_memdup(data, length);
847
848         /* read the clut data */
849         ofono_sim_read_bytes(sim, iidf_id, offset, clut_len,
850                                         sim_iidf_read_clut_cb, sim);
851 }
852
853 static void sim_get_image(struct ofono_sim *sim, unsigned char id,
854                                 gpointer user_data)
855 {
856         unsigned char *efimg;
857         char *image;
858         unsigned short iidf_id;
859         unsigned short iidf_offset;
860         unsigned short iidf_len;
861
862         image = sim_fs_get_cached_image(sim->simfs, id);
863
864         if (image != NULL) {
865                 sim_get_image_cb(sim, id, image, FALSE);
866                 return;
867         }
868
869         if (sim->efimg_length <= (id * 9)) {
870                 sim_get_image_cb(sim, id, NULL, FALSE);
871                 return;
872         }
873
874         efimg = &sim->efimg[id * 9];
875
876         iidf_id = efimg[3] << 8 | efimg[4];
877         iidf_offset = efimg[5] << 8 | efimg[6];
878         iidf_len = efimg[7] << 8 | efimg[8];
879
880         /* read the image data */
881         ofono_sim_read_bytes(sim, iidf_id, iidf_offset, iidf_len,
882                                 sim_iidf_read_cb, sim);
883 }
884
885 static DBusMessage *sim_get_icon(DBusConnection *conn,
886                                         DBusMessage *msg, void *data)
887 {
888         struct ofono_sim *sim = data;
889         unsigned char id;
890
891         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_BYTE, &id,
892                                         DBUS_TYPE_INVALID) == FALSE)
893                 return __ofono_error_invalid_args(msg);
894
895         /* zero means no icon */
896         if (id == 0)
897                 return __ofono_error_invalid_args(msg);
898
899         if (sim->pending)
900                 return __ofono_error_busy(msg);
901
902         if (sim->efimg == NULL)
903                 return __ofono_error_not_implemented(msg);
904
905         sim->pending = dbus_message_ref(msg);
906
907         sim_get_image(sim, id - 1, sim);
908
909         return NULL;
910 }
911
912 static DBusMessage *sim_reset_pin(DBusConnection *conn, DBusMessage *msg,
913                                         void *data)
914 {
915         struct ofono_sim *sim = data;
916         const char *typestr;
917         enum ofono_sim_password_type type;
918         const char *puk;
919         const char *pin;
920
921         if (!sim->driver->reset_passwd)
922                 return __ofono_error_not_implemented(msg);
923
924         if (sim->pending)
925                 return __ofono_error_busy(msg);
926
927         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &typestr,
928                                         DBUS_TYPE_STRING, &puk,
929                                         DBUS_TYPE_STRING, &pin,
930                                         DBUS_TYPE_INVALID) == FALSE)
931                 return __ofono_error_invalid_args(msg);
932
933         type = sim_string_to_passwd(typestr);
934
935         if (type == OFONO_SIM_PASSWORD_NONE || type != sim->pin_type)
936                 return __ofono_error_invalid_format(msg);
937
938         if (!is_valid_pin(puk, PIN_TYPE_PUK))
939                 return __ofono_error_invalid_format(msg);
940
941         if (!is_valid_pin(pin, PIN_TYPE_PIN))
942                 return __ofono_error_invalid_format(msg);
943
944         sim->pending = dbus_message_ref(msg);
945         sim->driver->reset_passwd(sim, puk, pin, sim_enter_pin_cb, sim);
946
947         return NULL;
948 }
949
950 static GDBusMethodTable sim_methods[] = {
951         { "GetProperties",      "",     "a{sv}",        sim_get_properties      },
952         { "SetProperty",        "sv",   "",             sim_set_property,
953                                                         G_DBUS_METHOD_FLAG_ASYNC },
954         { "ChangePin",          "sss",  "",             sim_change_pin,
955                                                         G_DBUS_METHOD_FLAG_ASYNC },
956         { "EnterPin",           "ss",   "",             sim_enter_pin,
957                                                         G_DBUS_METHOD_FLAG_ASYNC },
958         { "ResetPin",           "sss",  "",             sim_reset_pin,
959                                                         G_DBUS_METHOD_FLAG_ASYNC },
960         { "LockPin",            "ss",   "",             sim_lock_pin,
961                                                         G_DBUS_METHOD_FLAG_ASYNC },
962         { "UnlockPin",          "ss",   "",             sim_unlock_pin,
963                                                         G_DBUS_METHOD_FLAG_ASYNC },
964         { "GetIcon",            "y",    "ay",           sim_get_icon,
965                                                         G_DBUS_METHOD_FLAG_ASYNC },
966         { }
967 };
968
969 static GDBusSignalTable sim_signals[] = {
970         { "PropertyChanged",    "sv" },
971         { }
972 };
973
974 static gboolean numbers_list_equal(GSList *a, GSList *b)
975 {
976         struct ofono_phone_number *num_a, *num_b;
977
978         while (a || b) {
979                 if (!a || !b)
980                         return FALSE;
981
982                 num_a = a->data;
983                 num_b = b->data;
984
985                 if (!g_str_equal(num_a->number, num_b->number) ||
986                                 num_a->type != num_b->type)
987                         return FALSE;
988
989                 a = a->next;
990                 b = b->next;
991         }
992
993         return TRUE;
994 }
995
996 static void sim_msisdn_read_cb(int ok, int length, int record,
997                                 const unsigned char *data,
998                                 int record_length, void *userdata)
999 {
1000         struct ofono_sim *sim = userdata;
1001         int total;
1002         struct ofono_phone_number ph;
1003
1004         if (!ok)
1005                 goto check;
1006
1007         if (record_length < 14 || length < record_length)
1008                 return;
1009
1010         total = length / record_length;
1011
1012         sim->efmsisdn_length = record_length;
1013         sim->efmsisdn_records = total;
1014
1015         if (sim_adn_parse(data, record_length, &ph, NULL) == TRUE) {
1016                 struct ofono_phone_number *own;
1017
1018                 own = g_new(struct ofono_phone_number, 1);
1019                 memcpy(own, &ph, sizeof(struct ofono_phone_number));
1020                 sim->new_numbers = g_slist_prepend(sim->new_numbers, own);
1021         }
1022
1023         if (record != total)
1024                 return;
1025
1026 check:
1027         /* All records retrieved */
1028         if (sim->new_numbers)
1029                 sim->new_numbers = g_slist_reverse(sim->new_numbers);
1030
1031         if (!numbers_list_equal(sim->new_numbers, sim->own_numbers)) {
1032                 const char *path = __ofono_atom_get_path(sim->atom);
1033                 char **own_numbers;
1034                 DBusConnection *conn = ofono_dbus_get_connection();
1035
1036                 g_slist_foreach(sim->own_numbers, (GFunc) g_free, NULL);
1037                 g_slist_free(sim->own_numbers);
1038                 sim->own_numbers = sim->new_numbers;
1039
1040                 own_numbers = get_own_numbers(sim->own_numbers);
1041
1042                 ofono_dbus_signal_array_property_changed(conn, path,
1043                                                 OFONO_SIM_MANAGER_INTERFACE,
1044                                                 "SubscriberNumbers",
1045                                                 DBUS_TYPE_STRING, &own_numbers);
1046
1047                 g_strfreev(own_numbers);
1048         } else {
1049                 g_slist_foreach(sim->new_numbers, (GFunc) g_free, NULL);
1050                 g_slist_free(sim->new_numbers);
1051         }
1052
1053         sim->new_numbers = NULL;
1054 }
1055
1056 static gint service_number_compare(gconstpointer a, gconstpointer b)
1057 {
1058         const struct service_number *sdn = a;
1059         const char *id = b;
1060
1061         return strcmp(sdn->id, id);
1062 }
1063
1064 static void sim_sdn_read_cb(int ok, int length, int record,
1065                                 const unsigned char *data,
1066                                 int record_length, void *userdata)
1067 {
1068         struct ofono_sim *sim = userdata;
1069         DBusConnection *conn = ofono_dbus_get_connection();
1070         const char *path = __ofono_atom_get_path(sim->atom);
1071         int total;
1072         struct ofono_phone_number ph;
1073         char *alpha;
1074         struct service_number *sdn;
1075
1076         if (!ok)
1077                 goto check;
1078
1079         if (record_length < 14 || length < record_length)
1080                 return;
1081
1082         total = length / record_length;
1083
1084         if (sim_adn_parse(data, record_length, &ph, &alpha) == FALSE)
1085                 goto out;
1086
1087
1088         /* Use phone number if Id is unavailable */
1089         if (alpha && alpha[0] == '\0') {
1090                 g_free(alpha);
1091                 alpha = NULL;
1092         }
1093
1094         if (alpha == NULL)
1095                 alpha = g_strdup(phone_number_to_string(&ph));
1096
1097         if (sim->service_numbers &&
1098                         g_slist_find_custom(sim->service_numbers,
1099                                 alpha, service_number_compare)) {
1100                 ofono_error("Duplicate EFsdn entries for `%s'\n",
1101                                 alpha);
1102                 g_free(alpha);
1103
1104                 goto out;
1105         }
1106
1107         sdn = g_new(struct service_number, 1);
1108         sdn->id = alpha;
1109         memcpy(&sdn->ph, &ph, sizeof(struct ofono_phone_number));
1110
1111         sim->service_numbers = g_slist_prepend(sim->service_numbers, sdn);
1112
1113 out:
1114         if (record != total)
1115                 return;
1116
1117 check:
1118         /* All records retrieved */
1119         if (sim->service_numbers) {
1120                 char **service_numbers;
1121
1122                 sim->service_numbers = g_slist_reverse(sim->service_numbers);
1123                 sim->sdn_ready = TRUE;
1124
1125                 service_numbers = get_service_numbers(sim->service_numbers);
1126
1127                 ofono_dbus_signal_dict_property_changed(conn, path,
1128                                                 OFONO_SIM_MANAGER_INTERFACE,
1129                                                 "ServiceNumbers",
1130                                                 DBUS_TYPE_STRING,
1131                                                 &service_numbers);
1132                 g_strfreev(service_numbers);
1133         }
1134 }
1135
1136 static void sim_own_numbers_update(struct ofono_sim *sim)
1137 {
1138         ofono_sim_read(sim, SIM_EFMSISDN_FILEID, OFONO_SIM_FILE_STRUCTURE_FIXED,
1139                         sim_msisdn_read_cb, sim);
1140 }
1141
1142 static void sim_efimg_read_cb(int ok, int length, int record,
1143                                 const unsigned char *data,
1144                                 int record_length, void *userdata)
1145 {
1146         struct ofono_sim *sim = userdata;
1147         unsigned char *efimg;
1148         int num_records;
1149
1150         if (!ok)
1151                 return;
1152
1153         num_records = length / record_length;
1154
1155         /*
1156          * EFimg descriptors are 9 bytes long.
1157          * Byte 1 of the record is the number of descriptors per record.
1158          */
1159         if ((record_length < 10) ||
1160                         ((record_length % 9 != 2) && (record_length % 9 != 1)))
1161                 return;
1162
1163         if (sim->efimg == NULL) {
1164                 sim->efimg = g_try_malloc0(num_records * 9);
1165
1166                 if (sim->efimg == NULL)
1167                         return;
1168
1169                 sim->efimg_length = num_records * 9;
1170         }
1171
1172         /*
1173          * TBD - if we have more than one descriptor per record,
1174          * pick the nicest one.  For now we use the first one.
1175          */
1176
1177         /* copy descriptor into slot for this record */
1178         efimg = &sim->efimg[(record - 1) * 9];
1179
1180         memcpy(efimg, &data[1], 9);
1181 }
1182
1183 static void sim_ready(enum ofono_sim_state new_state, void *user)
1184 {
1185         struct ofono_sim *sim = user;
1186
1187         if (new_state != OFONO_SIM_STATE_READY)
1188                 return;
1189
1190         sim_own_numbers_update(sim);
1191
1192         ofono_sim_read(sim, SIM_EFSDN_FILEID, OFONO_SIM_FILE_STRUCTURE_FIXED,
1193                         sim_sdn_read_cb, sim);
1194         ofono_sim_read(sim, SIM_EFIMG_FILEID, OFONO_SIM_FILE_STRUCTURE_FIXED,
1195                         sim_efimg_read_cb, sim);
1196 }
1197
1198 static void sim_imsi_cb(const struct ofono_error *error, const char *imsi,
1199                 void *data)
1200 {
1201         struct ofono_sim *sim = data;
1202         DBusConnection *conn = ofono_dbus_get_connection();
1203         const char *path = __ofono_atom_get_path(sim->atom);
1204
1205         if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
1206                 ofono_error("Unable to read IMSI, emergency calls only");
1207                 return;
1208         }
1209
1210         sim->imsi = g_strdup(imsi);
1211
1212         ofono_dbus_signal_property_changed(conn, path,
1213                                                 OFONO_SIM_MANAGER_INTERFACE,
1214                                                 "SubscriberIdentity",
1215                                                 DBUS_TYPE_STRING, &sim->imsi);
1216
1217         if (sim->mnc_length) {
1218                 char mcc[OFONO_MAX_MCC_LENGTH + 1];
1219                 char mnc[OFONO_MAX_MNC_LENGTH + 1];
1220                 const char *str;
1221
1222                 strncpy(mcc, sim->imsi, OFONO_MAX_MCC_LENGTH);
1223                 mcc[OFONO_MAX_MCC_LENGTH] = '\0';
1224                 strncpy(mnc, sim->imsi + OFONO_MAX_MCC_LENGTH, sim->mnc_length);
1225                 mnc[sim->mnc_length] = '\0';
1226
1227                 str = mcc;
1228                 ofono_dbus_signal_property_changed(conn, path,
1229                                                 OFONO_SIM_MANAGER_INTERFACE,
1230                                                 "MobileCountryCode",
1231                                                 DBUS_TYPE_STRING, &str);
1232
1233                 str = mnc;
1234                 ofono_dbus_signal_property_changed(conn, path,
1235                                                 OFONO_SIM_MANAGER_INTERFACE,
1236                                                 "MobileNetworkCode",
1237                                                 DBUS_TYPE_STRING, &str);
1238         }
1239
1240         sim_set_ready(sim);
1241 }
1242
1243 static void sim_retrieve_imsi(struct ofono_sim *sim)
1244 {
1245         if (!sim->driver->read_imsi) {
1246                 ofono_error("IMSI retrieval not implemented,"
1247                                 " only emergency calls will be available");
1248                 return;
1249         }
1250
1251         sim->driver->read_imsi(sim, sim_imsi_cb, sim);
1252 }
1253
1254 static void sim_fdn_enabled(struct ofono_sim *sim)
1255 {
1256         DBusConnection *conn = ofono_dbus_get_connection();
1257         const char *path = __ofono_atom_get_path(sim->atom);
1258         dbus_bool_t val;
1259
1260         sim->fixed_dialing = TRUE;
1261
1262         val = sim->fixed_dialing;
1263         ofono_dbus_signal_property_changed(conn, path,
1264                                                 OFONO_SIM_MANAGER_INTERFACE,
1265                                                 "FixedDialing",
1266                                                 DBUS_TYPE_BOOLEAN, &val);
1267 }
1268
1269 static void sim_bdn_enabled(struct ofono_sim *sim)
1270 {
1271         DBusConnection *conn = ofono_dbus_get_connection();
1272         const char *path = __ofono_atom_get_path(sim->atom);
1273         dbus_bool_t val;
1274
1275         sim->barred_dialing = TRUE;
1276
1277         val = sim->barred_dialing;
1278         ofono_dbus_signal_property_changed(conn, path,
1279                                                 OFONO_SIM_MANAGER_INTERFACE,
1280                                                 "BarredDialing",
1281                                                 DBUS_TYPE_BOOLEAN, &val);
1282 }
1283
1284 static void sim_efbdn_info_read_cb(int ok, unsigned char file_status,
1285                                         int total_length, int record_length,
1286                                         void *userdata)
1287 {
1288         struct ofono_sim *sim = userdata;
1289
1290         if (!ok)
1291                 goto out;
1292
1293         if (file_status & SIM_FILE_STATUS_VALID)
1294                 sim_bdn_enabled(sim);
1295
1296 out:
1297         if (sim->fixed_dialing != TRUE &&
1298                         sim->barred_dialing != TRUE)
1299                 sim_retrieve_imsi(sim);
1300 }
1301
1302 static gboolean check_bdn_status(struct ofono_sim *sim)
1303 {
1304         /*
1305          * Check the status of Barred Dialing in the SIM-card
1306          * (TS 11.11/TS 51.011, Section 11.5.1: BDN capability request).
1307          * If BDN is allocated, activated in EFsst and EFbdn is validated,
1308          * halt the SIM initialization.
1309          */
1310         if (sim_sst_is_active(sim->efsst, sim->efsst_length,
1311                         SIM_SST_SERVICE_BDN)) {
1312                 sim_fs_read_info(sim->simfs, SIM_EFBDN_FILEID,
1313                                 OFONO_SIM_FILE_STRUCTURE_FIXED,
1314                                 sim_efbdn_info_read_cb, sim);
1315                 return TRUE;
1316         }
1317
1318         return FALSE;
1319 }
1320
1321 static void sim_efadn_info_read_cb(int ok, unsigned char file_status,
1322                                         int total_length, int record_length,
1323                                         void *userdata)
1324 {
1325         struct ofono_sim *sim = userdata;
1326
1327         if (!ok)
1328                 goto out;
1329
1330         if (!(file_status & SIM_FILE_STATUS_VALID))
1331                 sim_fdn_enabled(sim);
1332
1333 out:
1334         if (check_bdn_status(sim) != TRUE) {
1335                 if (sim->fixed_dialing != TRUE &&
1336                                 sim->barred_dialing != TRUE)
1337                         sim_retrieve_imsi(sim);
1338         }
1339 }
1340
1341 static void sim_efsst_read_cb(int ok, int length, int record,
1342                                 const unsigned char *data,
1343                                 int record_length, void *userdata)
1344 {
1345         struct ofono_sim *sim = userdata;
1346
1347         if (!ok)
1348                 goto out;
1349
1350         if (length < 2) {
1351                 ofono_error("EFsst shall contain at least two bytes");
1352                 goto out;
1353         }
1354
1355         sim->efsst = g_memdup(data, length);
1356         sim->efsst_length = length;
1357
1358         /*
1359          * Check if Fixed Dialing is enabled in the SIM-card
1360          * (TS 11.11/TS 51.011, Section 11.5.1: FDN capability request).
1361          * If FDN is activated and ADN is invalidated,
1362          * don't continue initialization routine.
1363          */
1364         if (sim_sst_is_active(sim->efsst, sim->efsst_length,
1365                                 SIM_SST_SERVICE_FDN)) {
1366                 sim_fs_read_info(sim->simfs, SIM_EFADN_FILEID,
1367                                         OFONO_SIM_FILE_STRUCTURE_FIXED,
1368                                         sim_efadn_info_read_cb, sim);
1369                 return;
1370         }
1371
1372         if (check_bdn_status(sim) == TRUE)
1373                 return;
1374
1375 out:
1376         sim_retrieve_imsi(sim);
1377 }
1378
1379 static void sim_efest_read_cb(int ok, int length, int record,
1380                                 const unsigned char *data,
1381                                 int record_length, void *userdata)
1382 {
1383         struct ofono_sim *sim = userdata;
1384
1385         if (!ok)
1386                 goto out;
1387
1388         if (length < 1) {
1389                 ofono_error("EFest shall contain at least one byte");
1390                 goto out;
1391         }
1392
1393         sim->efest = g_memdup(data, length);
1394         sim->efest_length = length;
1395
1396         /*
1397          * Check if Fixed Dialing is enabled in the USIM-card
1398          * (TS 31.102, Section 5.3.2: FDN capability request).
1399          * If FDN is activated, don't continue initialization routine.
1400          */
1401         if (sim_est_is_active(sim->efest, sim->efest_length,
1402                                 SIM_EST_SERVICE_FDN))
1403                 sim_fdn_enabled(sim);
1404
1405         /*
1406          * Check the status of Barred Dialing in the USIM-card
1407          * (TS 31.102, Section 5.3.2: BDN capability request).
1408          * If BDN service is enabled, halt the USIM initialization.
1409          */
1410         if (sim_est_is_active(sim->efest, sim->efest_length,
1411                                 SIM_EST_SERVICE_BDN))
1412                 sim_bdn_enabled(sim);
1413
1414 out:
1415         if (sim->fixed_dialing != TRUE &&
1416                         sim->barred_dialing != TRUE)
1417                 sim_retrieve_imsi(sim);
1418 }
1419
1420 static void sim_efust_read_cb(int ok, int length, int record,
1421                                 const unsigned char *data,
1422                                 int record_length, void *userdata)
1423 {
1424         struct ofono_sim *sim = userdata;
1425
1426         if (!ok)
1427                 goto out;
1428
1429         if (length < 1) {
1430                 ofono_error("EFust shall contain at least one byte");
1431                 goto out;
1432         }
1433
1434         sim->efust = g_memdup(data, length);
1435         sim->efust_length = length;
1436
1437         /*
1438          * Check whether the SIM provides EFest file
1439          * According to 31.102, section 4.2.24 and 4.2.44 the EFest file
1440          * must be present if EFfdn or EFbdn are present
1441          */
1442         if (sim_ust_is_available(sim->efust, sim->efust_length,
1443                                 SIM_UST_SERVICE_ENABLED_SERVICE_TABLE)) {
1444                 ofono_sim_read(sim, SIM_EFEST_FILEID,
1445                                 OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1446                                 sim_efest_read_cb, sim);
1447
1448                 return;
1449         }
1450
1451 out:
1452         sim_retrieve_imsi(sim);
1453 }
1454
1455 static void sim_cphs_information_read_cb(int ok, int length, int record,
1456                                 const unsigned char *data,
1457                                 int record_length, void *userdata)
1458 {
1459         struct ofono_sim *sim = userdata;
1460
1461         sim->cphs_phase = OFONO_SIM_CPHS_PHASE_NONE;
1462
1463         if (!ok || length < 3)
1464                 return;
1465
1466         if (data[0] == 0x01)
1467                 sim->cphs_phase = OFONO_SIM_CPHS_PHASE_1G;
1468         else if (data[0] >= 0x02)
1469                 sim->cphs_phase = OFONO_SIM_CPHS_PHASE_2G;
1470
1471         memcpy(sim->cphs_service_table, data + 1, 2);
1472 }
1473
1474 static void sim_ad_read_cb(int ok, int length, int record,
1475                                 const unsigned char *data,
1476                                 int record_length, void *userdata)
1477 {
1478         struct ofono_sim *sim = userdata;
1479         int new_mnc_length;
1480
1481         if (!ok)
1482                 return;
1483
1484         if (length < 4)
1485                 return;
1486
1487         new_mnc_length = data[3] & 0xf;
1488
1489         /* sanity check for potential invalid values */
1490         if (new_mnc_length < 2 || new_mnc_length > 3)
1491                 return;
1492
1493         sim->mnc_length = new_mnc_length;
1494 }
1495
1496 static void sim_efphase_read_cb(int ok, int length, int record,
1497                                 const unsigned char *data,
1498                                 int record_length, void *userdata)
1499 {
1500         struct ofono_sim *sim = userdata;
1501
1502         if (!ok || length != 1) {
1503                 sim->phase = OFONO_SIM_PHASE_3G;
1504
1505                 ofono_sim_read(sim, SIM_EFUST_FILEID,
1506                                 OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1507                                 sim_efust_read_cb, sim);
1508
1509                 return;
1510         }
1511
1512         switch (data[0]) {
1513         case 0:
1514                 sim->phase = OFONO_SIM_PHASE_1G;
1515                 break;
1516         case 2:
1517                 sim->phase = OFONO_SIM_PHASE_2G;
1518                 break;
1519         case 3:
1520                 sim->phase = OFONO_SIM_PHASE_2G_PLUS;
1521                 break;
1522         default:
1523                 ofono_error("Unknown phase");
1524                 return;
1525         }
1526
1527         ofono_sim_read(sim, SIM_EFSST_FILEID,
1528                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1529                         sim_efsst_read_cb, sim);
1530 }
1531
1532 static void sim_initialize_after_pin(struct ofono_sim *sim)
1533 {
1534         ofono_sim_read(sim, SIM_EFPHASE_FILEID,
1535                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1536                         sim_efphase_read_cb, sim);
1537
1538         ofono_sim_read(sim, SIM_EFAD_FILEID,
1539                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1540                         sim_ad_read_cb, sim);
1541
1542         /*
1543          * Read CPHS-support bits, this is still part of the SIM
1544          * initialisation but no order is specified for it.
1545          */
1546         ofono_sim_read(sim, SIM_EF_CPHS_INFORMATION_FILEID,
1547                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1548                         sim_cphs_information_read_cb, sim);
1549 }
1550
1551 static void sim_pin_query_cb(const struct ofono_error *error,
1552                                 enum ofono_sim_password_type pin_type,
1553                                 void *data)
1554 {
1555         struct ofono_sim *sim = data;
1556         DBusConnection *conn = ofono_dbus_get_connection();
1557         const char *path = __ofono_atom_get_path(sim->atom);
1558         const char *pin_name;
1559
1560         if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
1561                 ofono_error("Querying PIN authentication state failed");
1562
1563                 goto checkdone;
1564         }
1565
1566         if (sim->pin_type != pin_type) {
1567                 sim->pin_type = pin_type;
1568                 pin_name = sim_passwd_name(pin_type);
1569
1570                 if (pin_type != OFONO_SIM_PASSWORD_NONE &&
1571                                 password_is_pin(pin_type) == FALSE)
1572                         pin_type = puk2pin(pin_type);
1573
1574                 if (pin_type != OFONO_SIM_PASSWORD_INVALID)
1575                         sim->locked_pins[pin_type] = TRUE;
1576
1577                 ofono_dbus_signal_property_changed(conn, path,
1578                                                 OFONO_SIM_MANAGER_INTERFACE,
1579                                                 "PinRequired", DBUS_TYPE_STRING,
1580                                                 &pin_name);
1581         }
1582
1583 checkdone:
1584         if (pin_type == OFONO_SIM_PASSWORD_NONE)
1585                 sim_initialize_after_pin(sim);
1586 }
1587
1588 static void sim_pin_check(struct ofono_sim *sim)
1589 {
1590         if (!sim->driver->query_passwd_state) {
1591                 sim_initialize_after_pin(sim);
1592                 return;
1593         }
1594
1595         sim->driver->query_passwd_state(sim, sim_pin_query_cb, sim);
1596 }
1597
1598 static void sim_efli_read_cb(int ok, int length, int record,
1599                                 const unsigned char *data,
1600                                 int record_length, void *userdata)
1601 {
1602         struct ofono_sim *sim = userdata;
1603
1604         if (!ok)
1605                 return;
1606
1607         sim->efli = g_memdup(data, length);
1608         sim->efli_length = length;
1609 }
1610
1611 /* Detect whether the file is in EFli format, as opposed to 51.011 EFlp */
1612 static gboolean sim_efli_format(const unsigned char *ef, int length)
1613 {
1614         int i;
1615
1616         if (length & 1)
1617                 return FALSE;
1618
1619         for (i = 0; i < length; i += 2) {
1620                 if (ef[i] == 0xff && ef[i+1] == 0xff)
1621                         continue;
1622
1623                 /*
1624                  * ISO 639 country codes are each two lower-case SMS 7-bit
1625                  * characters while CB DCS language codes are in ranges
1626                  * (0 - 15) or (32 - 47), so the ranges don't overlap
1627                  */
1628                 if (g_ascii_isalpha(ef[i]) == 0)
1629                         return FALSE;
1630
1631                 if (g_ascii_isalpha(ef[i+1]) == 0)
1632                         return FALSE;
1633         }
1634
1635         return TRUE;
1636 }
1637
1638 static GSList *parse_language_list(const unsigned char *ef, int length)
1639 {
1640         int i;
1641         GSList *ret = NULL;
1642
1643         for (i = 0; i < length; i += 2) {
1644                 if (ef[i] > 0x7f || ef[i+1] > 0x7f)
1645                         continue;
1646
1647                 /*
1648                  * ISO 639 codes contain only characters that are coded
1649                  * identically in SMS 7 bit charset, ASCII or UTF8 so
1650                  * no conversion.
1651                  */
1652                 ret = g_slist_prepend(ret, g_ascii_strdown((char *)ef + i, 2));
1653         }
1654
1655         if (ret)
1656                 ret = g_slist_reverse(ret);
1657
1658         return ret;
1659 }
1660
1661 static GSList *parse_eflp(const unsigned char *eflp, int length)
1662 {
1663         int i;
1664         char code[3];
1665         GSList *ret = NULL;
1666
1667         for (i = 0; i < length; i++) {
1668                 if (iso639_2_from_language(eflp[i], code) == FALSE)
1669                         continue;
1670
1671                 ret = g_slist_prepend(ret, g_strdup(code));
1672         }
1673
1674         if (ret)
1675                 ret = g_slist_reverse(ret);
1676
1677         return ret;
1678 }
1679
1680 static char **concat_lang_prefs(GSList *a, GSList *b)
1681 {
1682         GSList *l, *k;
1683         char **ret;
1684         int i = 0;
1685         int total = g_slist_length(a) + g_slist_length(b);
1686
1687         if (total == 0)
1688                 return NULL;
1689
1690         ret = g_new0(char *, total + 1);
1691
1692         for (l = a; l; l = l->next)
1693                 ret[i++] = g_strdup(l->data);
1694
1695         for (l = b; l; l = l->next) {
1696                 gboolean duplicate = FALSE;
1697
1698                 for (k = a; k; k = k->next)
1699                         if (!strcmp(k->data, l->data))
1700                                 duplicate = TRUE;
1701
1702                 if (duplicate)
1703                         continue;
1704
1705                 ret[i++] = g_strdup(l->data);
1706         }
1707
1708         return ret;
1709 }
1710
1711 static void sim_efpl_read_cb(int ok, int length, int record,
1712                                 const unsigned char *data,
1713                                 int record_length, void *userdata)
1714 {
1715         struct ofono_sim *sim = userdata;
1716         const char *path = __ofono_atom_get_path(sim->atom);
1717         DBusConnection *conn = ofono_dbus_get_connection();
1718         gboolean efli_format = TRUE;
1719         GSList *efli = NULL;
1720         GSList *efpl = NULL;
1721
1722         if (!ok || length < 2)
1723                 goto skip_efpl;
1724
1725         efpl = parse_language_list(data, length);
1726
1727 skip_efpl:
1728         if (sim->efli && sim->efli_length > 0) {
1729                 efli_format = sim_efli_format(sim->efli, sim->efli_length);
1730
1731                 if (efli_format)
1732                         efli = parse_language_list(sim->efli, sim->efli_length);
1733                 else
1734                         efli = parse_eflp(sim->efli, sim->efli_length);
1735         }
1736
1737         /*
1738          * If efli_format is TRUE, make a list of languages in both files in
1739          * order of preference following TS 31.102.
1740          * Quoting 31.102 Section 5.1.1.2:
1741          * The preferred language selection shall always use the EFLI in
1742          * preference to the EFPL at the MF unless:
1743          * - if the EFLI has the value 'FFFF' in its highest priority position,
1744          *   then the preferred language selection shall be the language
1745          *   preference in the EFPL at the MF level
1746          * Otherwise in order of preference according to TS 51.011
1747          */
1748         if (efli_format) {
1749                 if (sim->efli_length >= 2 && sim->efli[0] == 0xff &&
1750                                 sim->efli[1] == 0xff)
1751                         sim->language_prefs = concat_lang_prefs(NULL, efpl);
1752                 else
1753                         sim->language_prefs = concat_lang_prefs(efli, efpl);
1754         } else {
1755                 sim->language_prefs = concat_lang_prefs(efpl, efli);
1756         }
1757
1758         if (sim->efli) {
1759                 g_free(sim->efli);
1760                 sim->efli = NULL;
1761                 sim->efli_length = 0;
1762         }
1763
1764         if (efli) {
1765                 g_slist_foreach(efli, (GFunc)g_free, NULL);
1766                 g_slist_free(efli);
1767         }
1768
1769         if (efpl) {
1770                 g_slist_foreach(efpl, (GFunc)g_free, NULL);
1771                 g_slist_free(efpl);
1772         }
1773
1774         if (sim->language_prefs != NULL)
1775                 ofono_dbus_signal_array_property_changed(conn, path,
1776                                                 OFONO_SIM_MANAGER_INTERFACE,
1777                                                 "PreferredLanguages",
1778                                                 DBUS_TYPE_STRING,
1779                                                 &sim->language_prefs);
1780
1781         sim_pin_check(sim);
1782 }
1783
1784 static void sim_iccid_read_cb(int ok, int length, int record,
1785                                 const unsigned char *data,
1786                                 int record_length, void *userdata)
1787 {
1788         struct ofono_sim *sim = userdata;
1789         const char *path = __ofono_atom_get_path(sim->atom);
1790         DBusConnection *conn = ofono_dbus_get_connection();
1791         char iccid[21]; /* ICCID max length is 20 + 1 for NULL */
1792
1793         if (!ok || length < 10)
1794                 return;
1795
1796         extract_bcd_number(data, length, iccid);
1797         iccid[20] = '\0';
1798         sim->iccid = g_strdup(iccid);
1799
1800         ofono_dbus_signal_property_changed(conn, path,
1801                                                 OFONO_SIM_MANAGER_INTERFACE,
1802                                                 "CardIdentifier",
1803                                                 DBUS_TYPE_STRING,
1804                                                 &sim->iccid);
1805 }
1806
1807 static void sim_initialize(struct ofono_sim *sim)
1808 {
1809         /*
1810          * Perform SIM initialization according to 3GPP 31.102 Section 5.1.1.2
1811          * The assumption here is that if sim manager is being initialized,
1812          * then sim commands are implemented, and the sim manager is then
1813          * responsible for checking the PIN, reading the IMSI and signaling
1814          * SIM ready condition.
1815          *
1816          * The procedure according to 31.102, 51.011, 11.11 and CPHS 4.2 is
1817          * roughly:
1818          *
1819          * Read EFecc
1820          * Read EFli and EFpl
1821          * SIM Pin check
1822          * Request SIM phase (only in 51.011)
1823          * Administrative information request (read EFad)
1824          * Request CPHS Information (only in CPHS 4.2)
1825          * Read EFsst (only in 11.11 & 51.011)
1826          * Read EFust (only in 31.102)
1827          * Read EFest (only in 31.102)
1828          * Read IMSI
1829          *
1830          * At this point we signal the SIM ready condition and allow
1831          * arbitrary files to be written or read, assuming their presence
1832          * in the EFust
1833          */
1834
1835         /* Grab the EFiccid which is always available */
1836         ofono_sim_read(sim, SIM_EF_ICCID_FILEID,
1837                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1838                         sim_iccid_read_cb, sim);
1839
1840         /* EFecc is read by the voicecall atom */
1841
1842         /*
1843          * According to 31.102 the EFli is read first and EFpl is then
1844          * only read if none of the EFli languages are supported by user
1845          * interface.  51.011 mandates the exact opposite, making EFpl/EFelp
1846          * preferred over EFlp (same EFid as EFli, different format).
1847          * However we don't depend on the user interface and so
1848          * need to read both files now.
1849          */
1850         ofono_sim_read(sim, SIM_EFLI_FILEID,
1851                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1852                         sim_efli_read_cb, sim);
1853         ofono_sim_read(sim, SIM_EFPL_FILEID,
1854                         OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1855                         sim_efpl_read_cb, sim);
1856 }
1857
1858 int ofono_sim_read_bytes(struct ofono_sim *sim, int id,
1859                         unsigned short offset, unsigned short num_bytes,
1860                         ofono_sim_file_read_cb_t cb, void *data)
1861 {
1862         if (sim == NULL)
1863                 return -1;
1864
1865         if (num_bytes == 0)
1866                 return -1;
1867
1868         return sim_fs_read(sim->simfs, id, OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
1869                                 offset, num_bytes, cb, data);
1870 }
1871
1872 int ofono_sim_read(struct ofono_sim *sim, int id,
1873                         enum ofono_sim_file_structure expected_type,
1874                         ofono_sim_file_read_cb_t cb, void *data)
1875 {
1876         if (sim == NULL)
1877                 return -1;
1878
1879         return sim_fs_read(sim->simfs, id, expected_type, 0, 0, cb, data);
1880 }
1881
1882 int ofono_sim_write(struct ofono_sim *sim, int id,
1883                         ofono_sim_file_write_cb_t cb,
1884                         enum ofono_sim_file_structure structure, int record,
1885                         const unsigned char *data, int length, void *userdata)
1886 {
1887         if (sim == NULL)
1888                 return -1;
1889
1890         return sim_fs_write(sim->simfs, id, cb, structure, record, data, length,
1891                                 userdata);
1892 }
1893
1894 const char *ofono_sim_get_imsi(struct ofono_sim *sim)
1895 {
1896         if (sim == NULL)
1897                 return NULL;
1898
1899         return sim->imsi;
1900 }
1901
1902 enum ofono_sim_phase ofono_sim_get_phase(struct ofono_sim *sim)
1903 {
1904         if (sim == NULL)
1905                 return 0;
1906
1907         return sim->phase;
1908 }
1909
1910 enum ofono_sim_cphs_phase ofono_sim_get_cphs_phase(struct ofono_sim *sim)
1911 {
1912         if (sim == NULL)
1913                 return OFONO_SIM_CPHS_PHASE_NONE;
1914
1915         return sim->cphs_phase;
1916 }
1917
1918 const unsigned char *ofono_sim_get_cphs_service_table(struct ofono_sim *sim)
1919 {
1920         if (sim == NULL)
1921                 return NULL;
1922
1923         return sim->cphs_service_table;
1924 }
1925
1926 static void sim_inserted_update(struct ofono_sim *sim)
1927 {
1928         DBusConnection *conn = ofono_dbus_get_connection();
1929         const char *path = __ofono_atom_get_path(sim->atom);
1930         dbus_bool_t present = sim->state != OFONO_SIM_STATE_NOT_PRESENT;
1931
1932         ofono_dbus_signal_property_changed(conn, path,
1933                                                 OFONO_SIM_MANAGER_INTERFACE,
1934                                                 "Present",
1935                                                 DBUS_TYPE_BOOLEAN, &present);
1936 }
1937
1938 static void sim_free_state(struct ofono_sim *sim)
1939 {
1940         if (sim->iccid) {
1941                 g_free(sim->iccid);
1942                 sim->iccid = NULL;
1943         }
1944
1945         if (sim->imsi) {
1946                 g_free(sim->imsi);
1947                 sim->imsi = NULL;
1948         }
1949
1950         if (sim->own_numbers) {
1951                 g_slist_foreach(sim->own_numbers, (GFunc)g_free, NULL);
1952                 g_slist_free(sim->own_numbers);
1953                 sim->own_numbers = NULL;
1954         }
1955
1956         if (sim->service_numbers) {
1957                 g_slist_foreach(sim->service_numbers,
1958                                 (GFunc)service_number_free, NULL);
1959                 g_slist_free(sim->service_numbers);
1960                 sim->service_numbers = NULL;
1961         }
1962
1963         if (sim->efli) {
1964                 g_free(sim->efli);
1965                 sim->efli = NULL;
1966                 sim->efli_length = 0;
1967         }
1968
1969         if (sim->language_prefs) {
1970                 g_strfreev(sim->language_prefs);
1971                 sim->language_prefs = NULL;
1972         }
1973
1974         if (sim->efust) {
1975                 g_free(sim->efust);
1976                 sim->efust = NULL;
1977                 sim->efust_length = 0;
1978         }
1979
1980         if (sim->efest) {
1981                 g_free(sim->efest);
1982                 sim->efest = NULL;
1983                 sim->efest_length = 0;
1984         }
1985
1986         if (sim->efsst) {
1987                 g_free(sim->efsst);
1988                 sim->efsst = NULL;
1989                 sim->efsst_length = 0;
1990         }
1991
1992         sim->mnc_length = 0;
1993
1994         if (sim->efimg) {
1995                 g_free(sim->efimg);
1996                 sim->efimg = NULL;
1997                 sim->efimg_length = 0;
1998         }
1999
2000         g_free(sim->iidf_image);
2001         sim->iidf_image = NULL;
2002
2003         sim->fixed_dialing = FALSE;
2004         sim->barred_dialing = FALSE;
2005 }
2006
2007 void ofono_sim_inserted_notify(struct ofono_sim *sim, ofono_bool_t inserted)
2008 {
2009         ofono_sim_state_event_cb_t notify;
2010         GSList *l;
2011
2012         if (inserted == TRUE && sim->state == OFONO_SIM_STATE_NOT_PRESENT)
2013                 sim->state = OFONO_SIM_STATE_INSERTED;
2014         else if (inserted == FALSE && sim->state != OFONO_SIM_STATE_NOT_PRESENT)
2015                 sim->state = OFONO_SIM_STATE_NOT_PRESENT;
2016         else
2017                 return;
2018
2019         if (!__ofono_atom_get_registered(sim->atom))
2020                 return;
2021
2022         sim_inserted_update(sim);
2023
2024         for (l = sim->state_watches->items; l; l = l->next) {
2025                 struct ofono_watchlist_item *item = l->data;
2026                 notify = item->notify;
2027
2028                 notify(sim->state, item->notify_data);
2029         }
2030
2031         if (inserted)
2032                 sim_initialize(sim);
2033         else
2034                 sim_free_state(sim);
2035 }
2036
2037 unsigned int ofono_sim_add_state_watch(struct ofono_sim *sim,
2038                                         ofono_sim_state_event_cb_t notify,
2039                                         void *data, ofono_destroy_func destroy)
2040 {
2041         struct ofono_watchlist_item *item;
2042
2043         DBG("%p", sim);
2044
2045         if (sim == NULL)
2046                 return 0;
2047
2048         if (notify == NULL)
2049                 return 0;
2050
2051         item = g_new0(struct ofono_watchlist_item, 1);
2052
2053         item->notify = notify;
2054         item->destroy = destroy;
2055         item->notify_data = data;
2056
2057         return __ofono_watchlist_add_item(sim->state_watches, item);
2058 }
2059
2060 void ofono_sim_remove_state_watch(struct ofono_sim *sim, unsigned int id)
2061 {
2062         __ofono_watchlist_remove_item(sim->state_watches, id);
2063 }
2064
2065 enum ofono_sim_state ofono_sim_get_state(struct ofono_sim *sim)
2066 {
2067         if (sim == NULL)
2068                 return OFONO_SIM_STATE_NOT_PRESENT;
2069
2070         return sim->state;
2071 }
2072
2073 static void sim_set_ready(struct ofono_sim *sim)
2074 {
2075         GSList *l;
2076         ofono_sim_state_event_cb_t notify;
2077
2078         if (sim == NULL)
2079                 return;
2080
2081         if (sim->state != OFONO_SIM_STATE_INSERTED)
2082                 return;
2083
2084         sim->state = OFONO_SIM_STATE_READY;
2085
2086         sim_fs_check_version(sim->simfs);
2087
2088         for (l = sim->state_watches->items; l; l = l->next) {
2089                 struct ofono_watchlist_item *item = l->data;
2090                 notify = item->notify;
2091
2092                 notify(sim->state, item->notify_data);
2093         }
2094 }
2095
2096 int ofono_sim_driver_register(const struct ofono_sim_driver *d)
2097 {
2098         DBG("driver: %p, name: %s", d, d->name);
2099
2100         if (d->probe == NULL)
2101                 return -EINVAL;
2102
2103         g_drivers = g_slist_prepend(g_drivers, (void *)d);
2104
2105         return 0;
2106 }
2107
2108 void ofono_sim_driver_unregister(const struct ofono_sim_driver *d)
2109 {
2110         DBG("driver: %p, name: %s", d, d->name);
2111
2112         g_drivers = g_slist_remove(g_drivers, (void *)d);
2113 }
2114
2115 static void sim_unregister(struct ofono_atom *atom)
2116 {
2117         DBusConnection *conn = ofono_dbus_get_connection();
2118         struct ofono_modem *modem = __ofono_atom_get_modem(atom);
2119         const char *path = __ofono_atom_get_path(atom);
2120         struct ofono_sim *sim = __ofono_atom_get_data(atom);
2121
2122         __ofono_watchlist_free(sim->state_watches);
2123         sim->state_watches = NULL;
2124
2125         g_dbus_unregister_interface(conn, path, OFONO_SIM_MANAGER_INTERFACE);
2126         ofono_modem_remove_interface(modem, OFONO_SIM_MANAGER_INTERFACE);
2127 }
2128
2129 static void sim_remove(struct ofono_atom *atom)
2130 {
2131         struct ofono_sim *sim = __ofono_atom_get_data(atom);
2132
2133         DBG("atom: %p", atom);
2134
2135         if (sim == NULL)
2136                 return;
2137
2138         if (sim->driver && sim->driver->remove)
2139                 sim->driver->remove(sim);
2140
2141         sim_free_state(sim);
2142
2143         if (sim->simfs) {
2144                 sim_fs_free(sim->simfs);
2145                 sim->simfs = NULL;
2146         }
2147
2148         g_free(sim);
2149 }
2150
2151 struct ofono_sim *ofono_sim_create(struct ofono_modem *modem,
2152                                         unsigned int vendor,
2153                                         const char *driver,
2154                                         void *data)
2155 {
2156         struct ofono_sim *sim;
2157         GSList *l;
2158
2159         if (driver == NULL)
2160                 return NULL;
2161
2162         sim = g_try_new0(struct ofono_sim, 1);
2163
2164         if (sim == NULL)
2165                 return NULL;
2166
2167         sim->phase = OFONO_SIM_PHASE_UNKNOWN;
2168         sim->atom = __ofono_modem_add_atom(modem, OFONO_ATOM_TYPE_SIM,
2169                                                 sim_remove, sim);
2170
2171         for (l = g_drivers; l; l = l->next) {
2172                 const struct ofono_sim_driver *drv = l->data;
2173
2174                 if (g_strcmp0(drv->name, driver))
2175                         continue;
2176
2177                 if (drv->probe(sim, vendor, data) < 0)
2178                         continue;
2179
2180                 sim->driver = drv;
2181                 break;
2182         }
2183
2184         return sim;
2185 }
2186
2187 void ofono_sim_register(struct ofono_sim *sim)
2188 {
2189         DBusConnection *conn = ofono_dbus_get_connection();
2190         struct ofono_modem *modem = __ofono_atom_get_modem(sim->atom);
2191         const char *path = __ofono_atom_get_path(sim->atom);
2192
2193         if (!g_dbus_register_interface(conn, path,
2194                                         OFONO_SIM_MANAGER_INTERFACE,
2195                                         sim_methods, sim_signals, NULL,
2196                                         sim, NULL)) {
2197                 ofono_error("Could not create %s interface",
2198                                 OFONO_SIM_MANAGER_INTERFACE);
2199
2200                 return;
2201         }
2202
2203         ofono_modem_add_interface(modem, OFONO_SIM_MANAGER_INTERFACE);
2204         sim->state_watches = __ofono_watchlist_new(g_free);
2205         sim->simfs = sim_fs_new(sim, sim->driver);
2206
2207         __ofono_atom_register(sim->atom, sim_unregister);
2208
2209         ofono_sim_add_state_watch(sim, sim_ready, sim, NULL);
2210
2211         if (sim->state > OFONO_SIM_STATE_NOT_PRESENT)
2212                 sim_initialize(sim);
2213 }
2214
2215 void ofono_sim_remove(struct ofono_sim *sim)
2216 {
2217         __ofono_atom_free(sim->atom);
2218 }
2219
2220 void ofono_sim_set_data(struct ofono_sim *sim, void *data)
2221 {
2222         sim->driver_data = data;
2223 }
2224
2225 void *ofono_sim_get_data(struct ofono_sim *sim)
2226 {
2227         return sim->driver_data;
2228 }