File: gsm_util.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 (386 lines) | stat: -rw-r--r-- 10,063 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
// *************************************************************************
// * GSM TA/ME library
// *
// * File:    gsm_util.h
// *
// * Purpose: Various utilities
// *
// * Author:  Peter Hofmann (software@pxh.de)
// *
// * Created: 4.5.1999
// *************************************************************************

#ifdef HAVE_CONFIG_H
  #include <gsm_config.h>
#endif
#include <gsmlib/gsm_nls.h>
#include <gsmlib/gsm_util.h>
#include <gsmlib/gsm_sysdep.h>
#include <sys/stat.h>
#include <assert.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <ctype.h>
#include <errno.h>
#if !defined(HAVE_CONFIG_H) || defined(HAVE_UNISTD_H)
  #include <unistd.h>
#endif
#if !defined(HAVE_CONFIG_H) || defined(HAVE_MALLOC_H)
  #include <malloc.h>
#endif
#include <stdarg.h>
#ifdef HAVE_VSNPRINTF
// switch on vsnprintf() prototype in stdio.h
  #ifndef __USE_GNU
    #define __USE_GNU
  #endif
  #ifndef _GNU_SOURCE
    #define _GNU_SOURCE
  #endif
#endif
#include <cstdlib>
#include <stdio.h>
#include <sys/stat.h>

using namespace gsmlib;

// Latin-1 undefined character (code 172 (Latin-1 boolean not, "�"))
const int NOP = 172;

// GSM undefined character (code 16 (GSM Delta))
const int GSM_NOP = 16;

// conversion tables, Latin1 to GSM and GSM to Latin1

static unsigned char gsmToLatin1Table[] =
{
  //  0 '@', '�', '$', '�', '�', '�', '�', '�', 
        '@', 163, '$', 165, 232, 233, 249, 236,
  //  8 '�', '�',  LF, '�', '�',  CR, '�', '�', 
        242, 199,  10, 216, 248,  13, 197, 229,
  // 16 '�', '_', '�', '�', '�', '�', '�', '�',
        NOP, '_', NOP, NOP, NOP, NOP, NOP, NOP, 
  // 24 '�', '�', '�', '�', '�', '�', '�', '�',
        NOP, NOP, NOP, NOP, 198, 230, 223, 201, 
  // 32 ' ', '!', '"', '#', '�', '%', '&', ''',
        ' ', '!', '"', '#', 164, '%', '&', '\'',
  // 40 '(', ')', '*', '+', ',', '-', '.', '/',
        '(', ')', '*', '+', ',', '-', '.', '/',
  // 48 '0', '1', '2', '3', '4', '5', '6', '7',
         '0', '1', '2', '3', '4', '5', '6', '7',
  // 56 '8', '9', ':', ';', '<', '=', '>', '?', 
        '8', '9', ':', ';', '<', '=', '>', '?', 
  // 64 '�', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 
        161, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 
  // 72 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 
        'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  // 80 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
         'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  // 88 'X', 'Y', 'Z', '�', '�', '�', '�', '�', 
        'X', 'Y', 'Z', 196, 214, 209, 220, 167,
  // 96 '�', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
        191, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  // 104 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
         'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
  // 112 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 
         'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 
  // 120 'x', 'y', 'z', '�', '�', '�', '�', '�', 
         'x', 'y', 'z', 228, 246, 241, 252, 224
};

static unsigned char latin1ToGsmTable[256];

static class Latin1ToGsmTableInit
{
public:
  Latin1ToGsmTableInit()
  {
    memset((void*)latin1ToGsmTable, GSM_NOP, 256);
    for (int i = 0; i < 128; i++)
      if (gsmToLatin1Table[i] != NOP)
        latin1ToGsmTable[gsmToLatin1Table[i]] = i;
  }
} latin1ToGsmTableInit;

std::string gsmlib::gsmToLatin1(std::string s)
{
  std::string result(s.length(), 0);
  for (std::string::size_type i = 0; i < s.length(); i++)
    result[i] = (unsigned char)s[i] > 127 ? NOP : gsmToLatin1Table[static_cast<unsigned int>(s[i])];
  return result;
}

std::string gsmlib::latin1ToGsm(std::string s)
{
  std::string result(s.length(), 0);
  for (std::string::size_type i = 0; i < s.length(); i++)
    result[i] = latin1ToGsmTable[(unsigned char)s[i]];
  return result;
}

static unsigned char byteToHex[] =
{
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  'A', 'B', 'C', 'D', 'E', 'F'
};

std::string gsmlib::bufToHex(const unsigned char *buf, unsigned long length)
{
  const unsigned char *bb = buf;
  std::string result;
  result.reserve(length * 2);

  for (unsigned long i = 0; i < length; ++i)
  {
    result += byteToHex[*bb >> 4];
    result += byteToHex[*bb++ & 0xf];
  }
  return result;
}

bool gsmlib::hexToBuf(const std::string &hexString, unsigned char *buf)
{
  if (hexString.length() % 2 != 0)
    return false;

  unsigned char *bb = buf;
  for (unsigned int i = 0; i < hexString.length(); i += 2)
  {
    unsigned char c = hexString[i];
    if (! isdigit(c) && ! ('a' <= c && c <= 'f') && ! ('A' <= c && c <= 'F'))
      return false;
    *bb = (isdigit(c) ? c - '0' :
           ((('a' <= c && c <= 'f') ? c - 'a' : c - 'A')) + 10) << 4;
    c = hexString[i + 1];
    if (! isdigit(c) && ! ('a' <= c && c <= 'f') && ! ('A' <= c && c <= 'F'))
      return false;
    *bb++ |= isdigit(c) ? c - '0' :
      ((('a' <= c && c <= 'f') ? c - 'a' : c - 'A') + 10);
  }
  return true;
}

std::string gsmlib::intToStr(int i)
{
  std::ostringstream os;
  os << i << std::ends;
  return os.str();
}

std::string gsmlib::removeWhiteSpace(std::string s)
{
  std::string result;
  for (unsigned int i = 0; i < s.length(); ++i)
    if (!std::isspace(s[i]))
      result += s[i];
  return result;
}

#ifdef WIN32

// helper routine, find out whether filename starts with "COM"
static bool isCom(std::string filename)
{
  filename = removeWhiteSpace(lowercase(filename));
  // remove UNC begin
  if (filename.compare(0, 4, "\\\\.\\") == 0)
    filename.erase(0, 4);
  return filename.length() < 3 || filename.substr(0, 3) == "com";
}
#endif

bool gsmlib::isFile(std::string filename)
{
#ifdef WIN32
  // stat does not work reliably under Win32 to indicate devices
  if (isCom(filename))
    return false;
#endif

  struct stat statBuf;
  int retries = 0;

  while (retries < 10)
  {
    if (stat(filename.c_str(), &statBuf) != 0)
      throw GsmException(
        stringPrintf(_("error when calling stat('%s') (errno: %d/%s)"), 
                     filename.c_str(), errno, strerror(errno)),
        OSError);
    
#ifndef WIN32
    if (S_ISLNK(statBuf.st_mode))
    {
      int size = 100;
      while (1)
      {
        char *buffer = (char*)malloc(size);
        int nchars = readlink(filename.c_str(), buffer, size);
        if (nchars < size)
        {
          filename.assign(buffer, nchars);
          free(buffer);
          break;
        }
        free(buffer);
        size *= 2;
      }
      ++retries;
    }
    else if (S_ISCHR(statBuf.st_mode))
      return false;
    else 
#endif
    if (S_ISREG(statBuf.st_mode))
      return true;
    else
      throw GsmException(
        stringPrintf(_("file '%s' is neither file nor character device"),
                     filename.c_str()),
        ParameterError);
  }
  throw GsmException(_("maxmimum number of symbolic links exceeded"),
                     ParameterError);
}

void gsmlib::renameToBackupFile(std::string filename) throw(GsmException)
{
  std::string backupFilename = filename + "~";
  unlink(backupFilename.c_str());
  if (rename(filename.c_str(), backupFilename.c_str()) < 0)
    throw GsmException(
      stringPrintf(_("error renaming '%s' to '%s'"),
                   filename.c_str(), backupFilename.c_str()),
      OSError, errno);
}

// NoCopy members

#ifndef NDEBUG

gsmlib::NoCopy::NoCopy(NoCopy &n)
{
  std::cerr << "ABORT: NoCopy copy constructor used" << std::endl;
  abort();
}

gsmlib::NoCopy &gsmlib::NoCopy::operator=(NoCopy &n)
{
  std::cerr << "ABORT: NoCopy::operator= used" << std::endl;
  abort();
}

#endif // NDEBUG

std::string gsmlib::lowercase(std::string s)
{
  std::string result;
  for (unsigned int i = 0; i < s.length(); ++i)
    result += tolower(s[i]);
  return result;
}

int gsmlib::checkNumber(std::string s) throw(GsmException)
{
  for (unsigned int i = 0; i < s.length(); ++i)
    if (! isdigit(s[i]))
      throw GsmException(stringPrintf(_("expected number, got '%s'"),
                                      s.c_str()), ParameterError);
  int result;
  std::istringstream is(s.c_str());
  is >> result;
  return result;
}

#ifdef HAVE_VSNPRINTF
std::string gsmlib::stringPrintf(const char *format, ...)
{
  va_list args;
  va_start(args, format);
  int size = 1024;
  while (1)
  {
    char *buf = (char*)alloca(sizeof(char) * size);
    int nchars = vsnprintf(buf, size, format, args);
    if (nchars < size)
    {
      va_end(args);
      return std::string(buf, nchars);
    }
    size *= 2;
  }
  return "";
}

#else
char gsmlib::__s[20000];        // buffer for the replacement macro
#endif // HAVE_VSNPRINTF

#ifndef NDEBUG
int gsmlib::debugLevel()
{
  char *s = getenv("GSMLIB_DEBUG");
  if (s == NULL) return 0;
  return checkNumber(s);
}
#endif

// interrupt interface

namespace gsmlib
{
  static InterruptBase *interruptObject = NULL;
}

void gsmlib::setInterruptObject(InterruptBase *intObject)
{
  interruptObject = intObject;
}
  
bool gsmlib::interrupted()
{
  return interruptObject != NULL && interruptObject->interrupted();
}

void gsmlib::checkTextAndTelephone(std::string text, std::string telephone)
  throw(GsmException)
{
  if (text.find('"') != std::string::npos)
    throw GsmException(
      stringPrintf(_("text '%s' contains illegal character '\"'"),
                   text.c_str()),
      ParameterError);

  for (unsigned int i = 0; i < telephone.length(); ++i)
    if (! isdigit(telephone[i]) && ! (telephone[i] == '+') &&
        ! (telephone[i] == '*') && ! (telephone[i] == '#') &&
        ! (telephone[i] == 'p') && ! (telephone[i] == 'w') &&
        ! (telephone[i] == 'P') && ! (telephone[i] == 'W'))
      throw GsmException(
        stringPrintf(_("illegal character in telephone number '%s'"),
                     telephone.c_str()), ParameterError);
}

// progress interface

namespace gsmlib
{
  static ProgressBase *progressObject = NULL;
}

void gsmlib::setProgressObject(ProgressBase *progObject)
{
  progressObject = progObject;
}

void gsmlib::reportProgress(int part, int total)
{
  if (progressObject != NULL)
    progressObject->reportProgress(part, total);
}

bool gsmlib::isSet(std::vector<bool> &b, unsigned int bit)
{
  return b.size() > bit && b[bit];
}