summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/cros/sms_watcher.cc
blob: c5a43356820de7070f032ab55de1c5a875f68b1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/sms_watcher.h"

#include <algorithm>
#include <deque>
#include <string>
#include <vector>

#include "base/bind.h"
#include "base/values.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/shill_device_client.h"
#include "chromeos/dbus/gsm_sms_client.h"
#include "chromeos/dbus/modem_messaging_client.h"
#include "chromeos/dbus/sms_client.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace chromeos {

namespace {

int decode_bcd(const char *s) {
  return (s[0] - '0') * 10 + s[1] - '0';
}

void decode_timestamp(const std::string& sms_timestamp, SMS *sms) {
  base::Time::Exploded exp;
  exp.year = decode_bcd(&sms_timestamp[0]);
  if (exp.year > 95)
    exp.year += 1900;
  else
    exp.year += 2000;
  exp.month = decode_bcd(&sms_timestamp[2]);
  exp.day_of_month = decode_bcd(&sms_timestamp[4]);
  exp.hour = decode_bcd(&sms_timestamp[6]);
  exp.minute = decode_bcd(&sms_timestamp[8]);
  exp.second = decode_bcd(&sms_timestamp[10]);
  exp.millisecond = 0;
  sms->timestamp = base::Time::FromUTCExploded(exp);
  int hours = decode_bcd(&sms_timestamp[13]);
  if (sms_timestamp[12] == '-')
    hours = -hours;
  sms->timestamp -= base::TimeDelta::FromHours(hours);
}

// Callback for Delete() method.  This method does nothing.
void DeleteSMSCallback() {}

}  // namespace

const char SMSWatcher::kNumberKey[] = "number";
const char SMSWatcher::kTextKey[] = "text";
const char SMSWatcher::kTimestampKey[] = "timestamp";
const char SMSWatcher::kSmscKey[] = "smsc";
const char SMSWatcher::kValidityKey[] = "validity";
const char SMSWatcher::kClassKey[] = "class";
const char SMSWatcher::kIndexKey[] = "index";

const char SMSWatcher::kModemManager1NumberKey[] = "Number";
const char SMSWatcher::kModemManager1TextKey[] = "Text";
const char SMSWatcher::kModemManager1TimestampKey[] = "Timestamp";
const char SMSWatcher::kModemManager1SmscKey[] = "Smsc";
const char SMSWatcher::kModemManager1ValidityKey[] = "Validity";
const char SMSWatcher::kModemManager1ClassKey[] = "Class";
const char SMSWatcher::kModemManager1IndexKey[] = "Index";

class SMSWatcher::WatcherBase {
 public:
  WatcherBase(const std::string& device_path,
              MonitorSMSCallback callback,
              const std::string& dbus_connection,
              const dbus::ObjectPath& object_path) :
      device_path_(device_path),
      callback_(callback),
      dbus_connection_(dbus_connection),
      object_path_(object_path) {}

  virtual ~WatcherBase() {}

 protected:
  const std::string device_path_;
  MonitorSMSCallback callback_;
  const std::string dbus_connection_;
  const dbus::ObjectPath object_path_;

  DISALLOW_COPY_AND_ASSIGN(WatcherBase);
};

namespace {

class GsmWatcher : public SMSWatcher::WatcherBase {
 public:
  GsmWatcher(const std::string& device_path,
             MonitorSMSCallback callback,
             const std::string& dbus_connection,
             const dbus::ObjectPath& object_path)
      : WatcherBase(device_path, callback, dbus_connection, object_path),
        weak_ptr_factory_(this) {
    DBusThreadManager::Get()->GetGsmSMSClient()->SetSmsReceivedHandler(
        dbus_connection_,
        object_path_,
        base::Bind(&GsmWatcher::OnSmsReceived, weak_ptr_factory_.GetWeakPtr()));

    DBusThreadManager::Get()->GetGsmSMSClient()->List(
        dbus_connection_, object_path_,
        base::Bind(&GsmWatcher::ListSMSCallback,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  virtual ~GsmWatcher() {
    DBusThreadManager::Get()->GetGsmSMSClient()->ResetSmsReceivedHandler(
        dbus_connection_, object_path_);
  }

 private:
  // Callback for SmsReceived signal from ModemManager.Modem.Gsm.SMS
  void OnSmsReceived(uint32 index, bool complete) {
    // Only handle complete messages.
    if (!complete)
      return;
    DBusThreadManager::Get()->GetGsmSMSClient()->Get(
        dbus_connection_, object_path_, index,
        base::Bind(&GsmWatcher::GetSMSCallback,
                   weak_ptr_factory_.GetWeakPtr(),
                   index));
  }

  // Runs |callback_| with a SMS.
  void RunCallbackWithSMS(const base::DictionaryValue& sms_dictionary) {
    SMS sms;

    if (!sms_dictionary.GetStringWithoutPathExpansion(SMSWatcher::kNumberKey,
                                                      &sms.number))
      LOG(WARNING) << "SMS did not contain a number";

    if (!sms_dictionary.GetStringWithoutPathExpansion(SMSWatcher::kTextKey,
                                                      &sms.text))
      LOG(WARNING) << "SMS did not contain message text";

    std::string sms_timestamp;
    if (sms_dictionary.GetStringWithoutPathExpansion(SMSWatcher::kTimestampKey,
                                                     &sms_timestamp)) {
      decode_timestamp(sms_timestamp, &sms);
    } else {
      LOG(WARNING) << "SMS did not contain a timestamp";
      sms.timestamp = base::Time();
    }

    sms_dictionary.GetStringWithoutPathExpansion(SMSWatcher::kSmscKey,
                                                 &sms.smsc);

    double validity = 0;
    if (!sms_dictionary.GetDoubleWithoutPathExpansion(SMSWatcher::kValidityKey,
                                                      &validity)) {
      validity = -1;
    }
    sms.validity = validity;

    double msgclass = 0;
    if (!sms_dictionary.GetDoubleWithoutPathExpansion(SMSWatcher::kClassKey,
                                                      &msgclass)) {
      msgclass = -1;
    }
    sms.msgclass = msgclass;

    callback_.Run(device_path_, sms);
  }

  // Callback for Get() method from ModemManager.Modem.Gsm.SMS
  void GetSMSCallback(uint32 index,
                      const base::DictionaryValue& sms_dictionary) {
    RunCallbackWithSMS(sms_dictionary);

    DBusThreadManager::Get()->GetGsmSMSClient()->Delete(
        dbus_connection_, object_path_, index, base::Bind(&DeleteSMSCallback));
  }

  // Callback for List() method.
  void ListSMSCallback(const base::ListValue& result) {
    // List() is called only once; no one touches delete_queue_ before List().
    CHECK(delete_queue_.empty());
    for (size_t i = 0; i != result.GetSize(); ++i) {
      const base::DictionaryValue* sms_dictionary = NULL;
      if (!result.GetDictionary(i, &sms_dictionary)) {
        LOG(ERROR) << "result[" << i << "] is not a dictionary.";
        continue;
      }
      RunCallbackWithSMS(*sms_dictionary);
      double index = 0;
      if (sms_dictionary->GetDoubleWithoutPathExpansion(SMSWatcher::kIndexKey,
                                                        &index)) {
        delete_queue_.push_back(index);
      }
    }
    DeleteSMSInChain();
  }

  // Deletes SMSs in the queue.
  void DeleteSMSInChain() {
    if (!delete_queue_.empty()) {
      DBusThreadManager::Get()->GetGsmSMSClient()->Delete(
          dbus_connection_, object_path_, delete_queue_.back(),
          base::Bind(&GsmWatcher::DeleteSMSInChain,
                     weak_ptr_factory_.GetWeakPtr()));
      delete_queue_.pop_back();
    }
  }

  base::WeakPtrFactory<GsmWatcher> weak_ptr_factory_;
  std::vector<uint32> delete_queue_;

  DISALLOW_COPY_AND_ASSIGN(GsmWatcher);
};

class ModemManager1Watcher : public SMSWatcher::WatcherBase {
 public:
  ModemManager1Watcher(const std::string& device_path,
                       MonitorSMSCallback callback,
                       const std::string& dbus_connection,
                       const dbus::ObjectPath& object_path)
      : WatcherBase(device_path, callback, dbus_connection, object_path),
        weak_ptr_factory_(this),
        deleting_messages_(false),
        retrieving_messages_(false) {
    DBusThreadManager::Get()->GetModemMessagingClient()->SetSmsReceivedHandler(
        dbus_connection_,
        object_path_,
        base::Bind(&ModemManager1Watcher::OnSmsReceived,
                   weak_ptr_factory_.GetWeakPtr()));

    DBusThreadManager::Get()->GetModemMessagingClient()->List(
        dbus_connection_, object_path_,
        base::Bind(&ModemManager1Watcher::ListSMSCallback,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  virtual ~ModemManager1Watcher() {
    DBusThreadManager::Get()->GetModemMessagingClient()
        ->ResetSmsReceivedHandler(dbus_connection_, object_path_);
  }

 private:
  void ListSMSCallback(
      const std::vector<dbus::ObjectPath>& paths) {
    // This receives all messages, so clear any pending gets and deletes.
    retrieval_queue_.clear();
    delete_queue_.clear();

    retrieval_queue_.resize(paths.size());
    std::copy(paths.begin(), paths.end(), retrieval_queue_.begin());
    if (!retrieving_messages_)
      GetMessages();
  }

  // Messages must be deleted one at a time, since we can not
  // guarantee the order the deletion will be executed in. Delete
  // messages from the back of the list so that the indices are
  // valid.
  void DeleteMessages() {
    if (delete_queue_.empty()) {
      deleting_messages_ = false;
      return;
    }
    deleting_messages_ = true;
    dbus::ObjectPath sms_path = delete_queue_.back();
    delete_queue_.pop_back();
    DBusThreadManager::Get()->GetModemMessagingClient()->Delete(
        dbus_connection_, object_path_, sms_path,
        base::Bind(&ModemManager1Watcher::DeleteMessages,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  // Messages must be fetched one at a time, so that we do not queue too
  // many requests to a single threaded server.
  void GetMessages() {
    if (retrieval_queue_.empty()) {
      retrieving_messages_ = false;
      if (!deleting_messages_)
        DeleteMessages();
      return;
    }
    retrieving_messages_ = true;
    dbus::ObjectPath sms_path = retrieval_queue_.front();
    retrieval_queue_.pop_front();
    DBusThreadManager::Get()->GetSMSClient()->GetAll(
        dbus_connection_, sms_path,
        base::Bind(&ModemManager1Watcher::GetCallback,
                   weak_ptr_factory_.GetWeakPtr()));
    delete_queue_.push_back(sms_path);
  }

  // Handles arrival of a new SMS message.
  void OnSmsReceived(const dbus::ObjectPath& sms_path, bool complete) {
    // Only handle complete messages.
    if (!complete)
      return;
    retrieval_queue_.push_back(sms_path);
    if (!retrieving_messages_)
      GetMessages();
  }

  // Runs |callback_| with a SMS.
  void RunCallbackWithSMS(const base::DictionaryValue& sms_dictionary) {
    SMS sms;

    if (!sms_dictionary.GetStringWithoutPathExpansion(
            SMSWatcher::kModemManager1NumberKey, &sms.number))
      LOG(WARNING) << "SMS did not contain a number";

    if (!sms_dictionary.GetStringWithoutPathExpansion(
            SMSWatcher::kModemManager1TextKey, &sms.text))
      LOG(WARNING) << "SMS did not contain message text";

    std::string sms_timestamp;
    if (sms_dictionary.GetStringWithoutPathExpansion(
            SMSWatcher::kModemManager1TimestampKey, &sms_timestamp)) {
      decode_timestamp(sms_timestamp, &sms);
    } else {
      LOG(WARNING) << "SMS did not contain a timestamp";
      sms.timestamp = base::Time();
    }

    sms_dictionary.GetStringWithoutPathExpansion(
        SMSWatcher::kModemManager1SmscKey, &sms.smsc);

    double validity = 0;
    if (!sms_dictionary.GetDoubleWithoutPathExpansion(
            SMSWatcher::kModemManager1ValidityKey, &validity)) {
      validity = -1;
    }
    sms.validity = validity;

    double msgclass = 0;
    if (!sms_dictionary.GetDoubleWithoutPathExpansion(
            SMSWatcher::kModemManager1ClassKey, &msgclass)) {
      msgclass = -1;
    }
    sms.msgclass = msgclass;

    callback_.Run(device_path_, sms);
  }

  void GetCallback(const base::DictionaryValue& dictionary) {
    RunCallbackWithSMS(dictionary);
    GetMessages();
  }

  base::WeakPtrFactory<ModemManager1Watcher> weak_ptr_factory_;
  bool deleting_messages_;
  bool retrieving_messages_;
  std::vector<dbus::ObjectPath> delete_queue_;
  std::deque<dbus::ObjectPath> retrieval_queue_;

  DISALLOW_COPY_AND_ASSIGN(ModemManager1Watcher);
};

}  // namespace

SMSWatcher::SMSWatcher(const std::string& modem_device_path,
                       MonitorSMSCallback callback)
    : weak_ptr_factory_(this),
      device_path_(modem_device_path),
      callback_(callback) {
  DBusThreadManager::Get()->GetShillDeviceClient()->GetProperties(
      dbus::ObjectPath(modem_device_path),
      base::Bind(&SMSWatcher::DevicePropertiesCallback,
                 weak_ptr_factory_.GetWeakPtr()));
}

SMSWatcher::~SMSWatcher() {
}

void SMSWatcher::DevicePropertiesCallback(
    DBusMethodCallStatus call_status,
    const base::DictionaryValue& properties) {
  if (call_status != DBUS_METHOD_CALL_SUCCESS)
    return;

  std::string dbus_connection;
  if (!properties.GetStringWithoutPathExpansion(
          flimflam::kDBusConnectionProperty, &dbus_connection)) {
    LOG(WARNING) << "Modem device properties do not include DBus connection.";
    return;
  }

  std::string object_path_string;
  if (!properties.GetStringWithoutPathExpansion(
          flimflam::kDBusObjectProperty, &object_path_string)) {
    LOG(WARNING) << "Modem device properties do not include DBus object.";
    return;
  }

  if (object_path_string.compare(
          0, sizeof(modemmanager::kModemManager1ServicePath) - 1,
          modemmanager::kModemManager1ServicePath) == 0) {
    watcher_.reset(
        new ModemManager1Watcher(device_path_, callback_, dbus_connection,
                                 dbus::ObjectPath(object_path_string)));
  } else {
    watcher_.reset(
        new GsmWatcher(device_path_, callback_, dbus_connection,
                       dbus::ObjectPath(object_path_string)));
  }
}

}  // namespace chromeos