File: gsm_sorted_sms_store.cc

package info (click to toggle)
gsmlib 1.10+20120414.gita5e5ae9a-0.3
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 3,468 kB
  • ctags: 1,907
  • sloc: cpp: 12,315; sh: 11,376; ansic: 2,366; makefile: 263; sed: 93
file content (504 lines) | stat: -rw-r--r-- 13,860 bytes parent folder | download | duplicates (2)
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// *************************************************************************
// * GSM TA/ME library
// *
// * File:    gsm_sorted_sms_store.cc
// *
// * Purpose: Sorted SMS store (residing in files or in the ME)
// *
// * Author:  Peter Hofmann (software@pxh.de)
// *
// * Created: 14.8.1999
// *************************************************************************

#ifdef HAVE_CONFIG_H
#include <gsm_config.h>
#endif
#include <gsmlib/gsm_nls.h>
#include <gsmlib/gsm_sysdep.h>
#include <gsmlib/gsm_sorted_sms_store.h>
#include <iostream>
#include <fstream>
#include <cstring>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif

using namespace gsmlib;

// SMS message file format:
// version number of file format, unsigned short int, 2 bytes in network byte
// order
// then comes the message:
// 1. length of PDU (see 4. below): unsigned short int,
//    2 bytes in network byte order
// 2. index of message, unique for this file: unsigned long,
//    4 bytes in network byte order
// 3. MessageType (1 byte), any of:
//    0 SMS_DELIVER
//    1 SMS_SUBMIT
//    2 SMS_STATUS_REPORT
// 4. PDU in hexadecimal format

static const unsigned short int SMS_STORE_FILE_FORMAT_VERSION = 1;

// SortedSMSStore members

// aux function read bytes with error handling
// return false if EOF
static bool readnbytes(std::string &filename,
                       std::istream &is, int len, char *buf,
                       bool eofIsError = true) throw(GsmException)
{
  is.read(buf, len);
  if (is.bad() || (is.eof() && eofIsError))
    throw GsmException(stringPrintf(_("error reading from file '%s'"),
                                    (filename == "" ? _("<STDIN>") :
                                     filename.c_str())), OSError);
  return ! is.eof();
}

// aux function write bytes with error handling
static void writenbytes(std::string &filename, std::ostream &os,
                        int len, const char *buf) throw(GsmException)
{
  os.write(buf, len);
  if (os.bad())
    throw GsmException(stringPrintf(_("error writing to file '%s'"),
                                    (filename == "" ? _("<STDOUT>") :
                                     filename.c_str())), OSError);
}

void SortedSMSStore::readSMSFile(std::istream &pbs, std::string filename)
  throw(GsmException)
{
  char numberBuf[4];

  // check the version
  try
    {
      readnbytes(filename, pbs, 2, numberBuf);
    }
  catch (GsmException &ge)
    {
      // ignore error, file might be empty initially
    }
  unsigned_int_2 version;
  memcpy(&version, numberBuf, sizeof(*numberBuf));
  version = ntohs(version);
  if (!pbs.eof() && version != SMS_STORE_FILE_FORMAT_VERSION)
    throw GsmException(stringPrintf(_("file '%s' has wrong version"),
                                    filename.c_str()), ParameterError);

  // read entries
  while (1)
    {
      // read PDU length and exit loop if EOF
      if (! readnbytes(filename, pbs, 2, numberBuf, false))
	break;

      unsigned_int_2 pduLen;
      memcpy(&pduLen, numberBuf, sizeof(*numberBuf));
      pduLen = ntohs(pduLen);

      if (pduLen > 500)
	throw GsmException(stringPrintf(_("corrupt SMS store file '%s'"),
					filename.c_str()), ParameterError);

      // read reserved integer field of message (was formerly index)
      readnbytes(filename, pbs, 4, numberBuf);
      //unsigned_int_4 reserved = ntohl(*((unsigned_int_4*)numberBuf));
    
      // read message type
      readnbytes(filename, pbs, 1, numberBuf);
      SMSMessage::MessageType messageType =
	(SMSMessage::MessageType)numberBuf[0];
      if (messageType > 2)
	throw GsmException(stringPrintf(_("corrupt SMS store file '%s'"),
					filename.c_str()), ParameterError);

      char *pduBuf = (char*)alloca(sizeof(char) * pduLen);

      // read pdu
      readnbytes(filename, pbs, pduLen, pduBuf);
      SMSMessageRef message =
	SMSMessage::decode(std::string(pduBuf, pduLen),
			   (messageType != SMSMessage::SMS_SUBMIT));
    
      SMSStoreEntry *newEntry = new SMSStoreEntry(message, _nextIndex++);
      _sortedSMSStore.insert(
			     SMSStoreMap::value_type(
						     SMSMapKey(*this, message->serviceCentreTimestamp()),
						     newEntry)
			     );
    }
}

void SortedSMSStore::sync(bool fromDestructor) throw(GsmException)
{
  if (_fromFile && _changed)
  {
    checkReadonly();

    // if writing to stdout and not called from destructor ignore
    // (avoids writing to stdout multiple times)
    if (_filename == "" && ! fromDestructor) return;

    // create backup file - but only once
    if (! _madeBackupFile && _filename != "") // don't make backup of stdout
    {
      renameToBackupFile(_filename);
      _madeBackupFile = true;
    }

    // open stream
    std::ostream *pbs = NULL;
    try
    {
      if (_filename == "")
        pbs = &std::cout;
      else
	pbs = new std::ofstream(_filename.c_str(), std::ios::out | std::ios::binary);
      
      if (pbs->bad())
        throw GsmException(
          stringPrintf(_("error opening file '%s' for writing"),
                       (_filename == "" ? _("<STDOUT>") :
                        _filename.c_str())),
          OSError);

      // write version number
      unsigned_int_2 version = htons(SMS_STORE_FILE_FORMAT_VERSION);
      writenbytes(_filename, *pbs, 2, (char*)&version);

      // and write the entries
      for (SMSStoreMap::iterator i = _sortedSMSStore.begin();
           i != _sortedSMSStore.end(); ++i)
      {
        // create PDU and write length
        std::string pdu = i->second->message()->encode();
        unsigned_int_2 pduLen = htons(pdu.length());
        writenbytes(_filename, *pbs, 2, (char*)&pduLen);

        // write reserved field (was formerly index)
        unsigned_int_4 reserved = htonl(0);
        writenbytes(_filename, *pbs, 4, (char*)&reserved);
        
        // write message type
        char messageType = i->second->message()->messageType();
        writenbytes(_filename, *pbs, 1, (char*)&messageType);

        // write PDU
        writenbytes(_filename, *pbs, pdu.length(), pdu.data());
      }
    }
    catch(GsmException &e)
    {
      if (pbs != &std::cout) delete pbs;
      throw;
    }
    // close file
    if (pbs != &std::cout) delete pbs;

    _changed = false;
  }
}

void SortedSMSStore::checkReadonly() throw(GsmException)
{
  if (_readonly) throw GsmException(
    _("attempt to change SMS store read from <STDIN>"),
    ParameterError);
}

SortedSMSStore::SortedSMSStore(std::string filename) throw(GsmException) :
  _changed(false), _fromFile(true), _madeBackupFile(false),
  _sortOrder(ByDate), _readonly(false), _filename(filename), _nextIndex(0)
{
  // open the file
  std::ifstream pbs(filename.c_str(), std::ios::in | std::ios::binary);
  if (pbs.bad())
    throw GsmException(stringPrintf(_("cannot open file '%s'"),
                                    filename.c_str()), OSError);
  // and read the file
  readSMSFile(pbs, filename);
}

SortedSMSStore::SortedSMSStore(bool fromStdin) throw(GsmException) :
  _changed(false), _fromFile(true), _madeBackupFile(false),
  _sortOrder(ByDate), _readonly(fromStdin), _nextIndex(0)
  // _filename is "" - this means stdout
{
  // read from stdin
  if (fromStdin)
    readSMSFile(std::cin, (std::string)_("<STDIN>"));
}

SortedSMSStore::SortedSMSStore(SMSStoreRef meSMSStore)
  throw(GsmException) :
  _changed(false), _fromFile(false), _madeBackupFile(false),
  _sortOrder(ByDate), _readonly(false), _meSMSStore(meSMSStore)
{
  // It is necessary to count the entries read because
  // the maximum index into the SMS store may be larger than smsStore.size()
  int entriesRead = 0;
  reportProgress(0, _meSMSStore->size());

  for (int i = 0;; ++i)
  {
    if (entriesRead == _meSMSStore->size())
      break;                 // ready
    if (! _meSMSStore()[i].empty())
    {
      _sortedSMSStore.insert(
        SMSStoreMap::value_type(
          SMSMapKey(*this,
                    _meSMSStore()[i].message()->serviceCentreTimestamp()),
          &_meSMSStore()[i])
        );
      ++entriesRead;
      reportProgress(entriesRead);
    }
  }
}

void SortedSMSStore::setSortOrder(SortOrder newOrder)
{
  if (_sortOrder == newOrder) return; // nothing to be done

  SMSStoreMap savedSMSStore = _sortedSMSStore;
  _sortedSMSStore = SMSStoreMap();
  _sortOrder = newOrder;

  switch (newOrder)
  {
  case ByIndex:
  {
    for (SMSStoreMap::iterator i = savedSMSStore.begin();
         i != savedSMSStore.end(); ++i)
      _sortedSMSStore.insert(
        SMSStoreMap::value_type(SMSMapKey(*this, (i->second->index())),
                                i->second));
    break;
  }
  case ByDate:
  {
    for (SMSStoreMap::iterator i = savedSMSStore.begin();
         i != savedSMSStore.end(); ++i)
      _sortedSMSStore.insert(
        SMSStoreMap::value_type(
          SMSMapKey(*this, (i->second->message()->serviceCentreTimestamp())),
          i->second));
    break;
  }
  case ByAddress:
  {
    for (SMSStoreMap::iterator i = savedSMSStore.begin();
         i != savedSMSStore.end(); ++i)
      _sortedSMSStore.insert(
        SMSStoreMap::value_type(
          SMSMapKey(*this, (i->second->message()->address())),
          i->second));
    break;
  }
  case ByType:
  {
    for (SMSStoreMap::iterator i = savedSMSStore.begin();
         i != savedSMSStore.end(); ++i)
      _sortedSMSStore.insert(
        SMSStoreMap::value_type(
          SMSMapKey(*this, (i->second->message()->messageType())),
          i->second));
    break;
  }
  default:
    assert(0);
    break;
  }
}

int SortedSMSStore::max_size() const
{
  if (_fromFile)
    return _sortedSMSStore.max_size();
  else
    return _meSMSStore->max_size();
}

int SortedSMSStore::capacity() const
{
  if (_fromFile)
    return _sortedSMSStore.max_size();
  else
    return _meSMSStore->capacity();
}

SortedSMSStore::iterator
SortedSMSStore::insert(const SMSStoreEntry& x) throw(GsmException)
{
  checkReadonly();
  _changed = true;
  SMSStoreEntry *newEntry;

  if (_fromFile)
    newEntry = new SMSStoreEntry(x.message(), _nextIndex++);
  else
  {
    SMSStoreEntry newMEEntry(x.message());
    newEntry = _meSMSStore->insert(newMEEntry);
  }
  
  switch (_sortOrder)
  {
  case ByIndex:
    return
      _sortedSMSStore.
      insert(SMSStoreMap::value_type(SMSMapKey(*this, newEntry->index()),
                                     newEntry));
    break;
  case ByDate:
    return
      _sortedSMSStore.
      insert(SMSStoreMap::value_type(
        SMSMapKey(*this, newEntry->message()->serviceCentreTimestamp()),
        newEntry));
    break;
  case ByAddress:
    return
      _sortedSMSStore.
      insert(SMSStoreMap::value_type(
        SMSMapKey(*this, newEntry->message()->address()),
        newEntry));
    break;
  case ByType:
    return
      _sortedSMSStore.
      insert(SMSStoreMap::value_type(
        SMSMapKey(*this, newEntry->message()->messageType()),
        newEntry));
    break;
  default:
    assert(0);
    break;
  }
  return SortedSMSStore::iterator();
}

SortedSMSStore::iterator
SortedSMSStore::insert(iterator position, const SMSStoreEntry& x)
  throw(GsmException)
{
  return insert(x);
}

SortedSMSStore::size_type SortedSMSStore::erase(Address &key)
  throw(GsmException)
{
  assert(_sortOrder == ByAddress);

  SMSMapKey mapKey(*this, key);

  // deallocate memory or remove from underlying ME SMS store
  for (SMSStoreMap::iterator i = _sortedSMSStore.find(mapKey);
       i != _sortedSMSStore.end() && i->first == mapKey; ++i)
  {
    checkReadonly();
    _changed = true;
    if (_fromFile)
      delete i->second;
    else
      _meSMSStore->erase((SMSStore::iterator)i->second);
  }

  return _sortedSMSStore.erase(mapKey);
}

SortedSMSStore::size_type SortedSMSStore::erase(int key)
  throw(GsmException)
{
  assert(_sortOrder == ByIndex || _sortOrder == ByType);

  SMSMapKey mapKey(*this, key);

  // deallocate memory or remove from underlying ME SMS store
  for (SMSStoreMap::iterator i = _sortedSMSStore.find(mapKey);
       i != _sortedSMSStore.end() && i->first == mapKey; ++i)
  {
    checkReadonly();
    _changed = true;
    if (_fromFile)
      delete i->second;
    else
      _meSMSStore->erase((SMSStore::iterator)i->second);
  }

  return _sortedSMSStore.erase(mapKey);
}

SortedSMSStore::size_type SortedSMSStore::erase(Timestamp &key)
  throw(GsmException)
{
  assert(_sortOrder == ByDate);

  SMSMapKey mapKey(*this, key);

  // deallocate memory or remove from underlying ME SMS store
  for (SMSStoreMap::iterator i = _sortedSMSStore.find(mapKey);
       i != _sortedSMSStore.end() && i->first == mapKey; ++i)
  {
    checkReadonly();
    _changed = true;
    if (_fromFile)
      delete i->second;
    else
      _meSMSStore->erase((SMSStore::iterator)i->second);
  }

  return _sortedSMSStore.erase(mapKey);
}

void SortedSMSStore::erase(iterator position)
  throw(GsmException)
{
  checkReadonly();
  _changed = true;
  // deallocate memory or remove from underlying ME SMS store
  if (_fromFile)
    delete ((SMSStoreMap::iterator)position)->second;
  else
    _meSMSStore->erase((SMSStore::iterator)
                       ((SMSStoreMap::iterator)position)->second);
  _sortedSMSStore.erase(position);
}

void SortedSMSStore::erase(iterator first, iterator last)
  throw(GsmException)
{
  checkReadonly();
  _changed = true;
  for (SMSStoreMap::iterator i = first; i != last; ++i)
    if (_fromFile)
      delete i->second;
    else
      _meSMSStore->erase((SMSStore::iterator)i->second);
  _sortedSMSStore.erase(first, last);
}

void SortedSMSStore::clear() throw(GsmException)
{
  checkReadonly();
  _changed = true;
  for (iterator i = begin(); i != end(); i++)
    erase(i);
}

SortedSMSStore::~SortedSMSStore()
{
  if (_fromFile)
  {
    sync(true);
    for (SMSStoreMap::iterator i = _sortedSMSStore.begin();
         i != _sortedSMSStore.end(); ++i)
      delete i->second;
  }
}