summaryrefslogtreecommitdiff
path: root/src/generic/util/util.cc
blob: d7868143b936b0f0abe09b4d185094cb6182c6f0 (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
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
// util.cc
//
//   Copyright (C) 2005, 2007, 2009-2010 Daniel Burrows
//   Copyright (C) 2014 Daniel Hartwig
//
//   This program is free software; you can redistribute it and/or
//   modify it under the terms of the GNU General Public License as
//   published by the Free Software Foundation; either version 2 of
//   the License, or (at your option) any later version.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//   General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; see the file COPYING.  If not, write to
//   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
//   Boston, MA 02111-1307, USA.

#include "util.h"

#include "dirent_safe.h"

#include <aptitude.h>

#include <ctype.h>
#include <errno.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include <apt-pkg/error.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/strutl.h>

#include <cwidget/generic/util/eassert.h>

#include <sys/time.h>

using namespace std;

std::string backslash_escape_nonalnum(const std::string &s)
{
  std::string rval;
  for(std::string::const_iterator it = s.begin();
      it != s.end(); ++it)
    {
      if(isalnum(*it))
	rval.push_back(*it);
      else
	{
	  rval.push_back('\\');
	  rval.push_back(*it);
	}
    }

  return rval;
}

void stripws(string &s)
{
  size_t start = 0;
  while(start < s.size() && isspace(s[start]))
    ++start;

  size_t end = s.size();
  while(end > 0 && isspace(s[end-1]))
    --end;

  if(start >= end)
    s.clear();
  else
    s.assign(s, start, end-start);
}

void splitws(const string &s, vector<string> &output, int start, int length)
{
  while(start < length)
    {
      while(start < length && isspace(s[start]))
	++start;

      string tmp;
      // Could support quoting, etc?
      while(start < length && !isspace(s[start]))
	tmp += s[start++];

      if(!tmp.empty())
	output.push_back(tmp);
    }
}

void splitws(const string &s, vector<string> &output)
{
  return splitws(s, output, 0, s.size());
}

bool strempty(const char *s)
{
  return s == NULL || strcmp(s, "") == 0;
}

bool wcsempty(const wchar_t *s)
{
  return s == NULL || wcscmp(s, L"") == 0;
}

string ssprintf(const char *format, ...)
{
  va_list ap;

  va_start(ap, format);
  string rval = vssprintf(format, ap);
  va_end(ap);

  return rval;
}

const int initbufsize=512;

string vssprintf(const char *format, va_list ap)
{
  // We need to do this because you can't necessarily re-use a
  // va_list after stepping down it.
  va_list ap2;
  va_copy(ap2, ap);
  char buf[initbufsize];
  const int amt = vsnprintf(buf, initbufsize, format, ap);

  if(amt < initbufsize)
    return buf;
  else
    {
      const int buf2size = amt + 1;
      char *buf2 = new char[buf2size];

      const int amt2 = vsnprintf(buf2, buf2size, format, ap2);

      eassert(amt2 < buf2size);

      string rval(buf2, amt2);

      delete[] buf2;

      return rval;
    }
}

wstring swsprintf(const wchar_t *format, ...)
{
  va_list ap;

  va_start(ap, format);
  wstring rval = vswsprintf(format, ap);
  va_end(ap);

  return rval;
}

wstring vswsprintf(const wchar_t *format, va_list ap)
{
  wchar_t buf[initbufsize];
  int amt = vswprintf(buf, initbufsize, format, ap);

  if(amt < initbufsize)
    return buf;
  else
    {
      wchar_t *buf2 = new wchar_t[amt+1];

      int amt2 = vswprintf(buf2, initbufsize, format, ap);

      eassert(amt2 < amt+1);

      wstring rval(buf2, amt2);

      delete[] buf2;

      return rval;
    }
}

string sstrftime(const char *format, const tm *tm)
{
  size_t bufsize = 512;

  while(bufsize < 512 * 512)
    {
      char *buf = new char[bufsize];

      buf[0] = '\1';
      size_t result = strftime(buf, bufsize, format, tm);

      if(result == 0 && buf[0] != '\0')
	{
	  delete[] buf;
	  bufsize *= 2;
	}
      else
	{
	  // Could eliminate this with an "array smart pointer".
	  string rval(buf);
	  delete[] buf;
	  return rval;
	}
    }

  return "";
}

string sstrerror(int errnum)
{
  size_t bufsize = 512;

  while(bufsize < 512 * 512)
    {
      char *buf = new char[bufsize];

      char *result = strerror_r(errnum, buf, bufsize);

      if(result == NULL)
	{
	  int strerror_errno = errno;

	  delete[] buf;

	  if(strerror_errno == EINVAL)
	    return ssprintf("Invalid error code %d", errnum);
	  else if(strerror_errno != ERANGE)
	    return ssprintf("Unexpected error from strerror_r: %d", errnum);
	  else
	    bufsize *= 2;
	}
      else
	{
	  // We need to copy "result", not "buf", because some
	  // versions of strerror_r can return a static string and
	  // leave "buf" alone.
	  string rval(result);
	  delete[] buf;
	  return rval;
	}
    }

  return "";
}

string get_homedir()
{
  passwd pwbuf;
  passwd *useless;
  uid_t myuid = getuid();

#ifdef _SC_GETPW_R_SIZE_MAX
  long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
  char *buf = new char[bufsize];

  if(getpwuid_r(myuid, &pwbuf, buf, bufsize, &useless) != 0)
    {
      delete[] buf;
      return "";
    }
  else
    {
      string rval = pwbuf.pw_dir;
      delete[] buf;
      return rval;
    }
#else
  long bufsize = 512;
  bool done = false;

  // The 512 * 512 is an arbitrary cutoff to avoid allocating
  // unbounded amounts of memory when the system doesn't support a way
  // to directly determine the largest possible password structure.
  while(bufsize < 512 * 512)
    {
      char *buf = new char[bufsize];

      if(getpwuid_r(myuid, &pwbuf, buf, bufsize, &useless) == 0)
	{
	  string rval = pwbuf.pw_dir;
	  delete[] buf;
	  return rval;
	}
      else
	{
	  delete[] buf;
	  bufsize *= 2;
	}
    }

  return "";
#endif
}

string get_username()
{
  passwd pwbuf;
  passwd *useless;
  uid_t myuid = getuid();

#ifdef _SC_GETPW_R_SIZE_MAX
  long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
  char *buf = new char[bufsize];

  if(getpwuid_r(myuid, &pwbuf, buf, bufsize, &useless) != 0)
    {
      delete[] buf;
      return "";
    }
  else
    {
      string rval = pwbuf.pw_name;
      delete[] buf;
      return rval;
    }
#else
  long bufsize = 512;
  bool done = false;

  // The 512 * 512 is an arbitrary cutoff to avoid allocating
  // unbounded amounts of memory when the system doesn't support a way
  // to directly determine the largest possible password structure.
  while(bufsize < 512 * 512)
    {
      char *buf = new char[bufsize];

      if(getpwuid_r(myuid, &pwbuf, buf, bufsize, &useless) == 0)
	{
	  string rval = pwbuf.pw_name;
	  delete[] buf;
	  return rval;
	}
      else
	{
	  delete[] buf;
	  bufsize *= 2;
	}
    }

  return "";
#endif
}

namespace aptitude
{
  namespace util
  {
    timeval subtract_timevals(const timeval &a, const timeval &b)
    {
      timeval rval;

      rval.tv_sec = a.tv_sec - b.tv_sec;
      if(a.tv_usec < b.tv_usec)
        {
          --rval.tv_sec;
          rval.tv_usec = (a.tv_usec - b.tv_usec) + 1000000;
        }
      else
        rval.tv_usec = a.tv_usec - b.tv_usec;

      return rval;
    }

    bool recursive_remdir(const std::string &dirname)
    {
      struct stat stbuf;

      if(lstat(dirname.c_str(), &stbuf) != 0)
	_error->Errno("recursive_remdir", _("Unable to stat \"%s\""), dirname.c_str());

      if(S_ISLNK(stbuf.st_mode) || !S_ISDIR(stbuf.st_mode))
	{
	  if(unlink(dirname.c_str()) != 0)
	    {
	      _error->Errno("recursive_remdir", _("Unable to remove \"%s\""), dirname.c_str());
	      return false;
	    }
	  else
	    return true;
	}

      DIR *dir = opendir(dirname.c_str());
      if(dir == NULL)
	{
	  _error->Errno("recursive_remdir", _("Unable to list files in \"%s\""), dirname.c_str());
	  return false;
	}

      bool rval = true;

      dirent_safe dent;
      dirent *tmp;
      for(int dirent_result = readdir_r(dir, &dent.d, &tmp);
	  dirent_result == 0 && tmp != NULL;
	  dirent_result = readdir_r(dir, &dent.d, &tmp))
	if(strcmp(dent.d.d_name, ".") != 0 &&
	   strcmp(dent.d.d_name, "..") != 0)
	  rval = (rval && recursive_remdir(dirname + "/" + dent.d.d_name));

      if(closedir(dir) != 0)
	{
	  _error->Errno("recursive_remdir", _("Failure closing directory \"%s\""), dirname.c_str());
	  rval = false;
	}

      if(rmdir(dirname.c_str()) != 0)
	{
	  _error->Errno("recursive_remdir", _("Unable to remove directory \"%s\""), dirname.c_str());
	  rval = false;
	}

      return rval;
    }

    // From apt-pkg/contrib/fileutl.cc (CreateDirectory).
    bool mkdir_parents(const std::string &dirname, mode_t mode)
    {
      if(dirname.empty() == true)
        return false;

      const vector<string> dirs = VectorizeString(dirname, '/');
      string progress = "";
      for(vector<string>::const_iterator d = dirs.begin();
          d != dirs.end();
          ++d)
        {
          if(d->empty() == true)
            continue;

          progress.append("/").append(*d);
          if(DirectoryExists(progress) == true)
            continue;

          if(mkdir(progress.c_str(), mode) != 0)
            return false;
        }
      return true;
    }
  }
}