summaryrefslogtreecommitdiff
path: root/sbuild/sbuild-util.cc
blob: dc9e7a23b35a4edb4a6d4e5ed20a875c91e6cf75 (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
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
/* Copyright © 2005-2007  Roger Leigh <rleigh@debian.org>
 *
 * schroot 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 3 of the License, or
 * (at your option) any later version.
 *
 * schroot 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.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 *********************************************************************/

#include <config.h>

#include "sbuild-chroot.h"
#include "sbuild-error.h"
#include "sbuild-util.h"

#include <cerrno>
#include <cstring>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace sbuild;

namespace
{

  /**
   * Remove duplicate adjacent characters from a string.
   *
   * @param str the string to check.
   * @param dup the duplicate character to check for.
   * @returns a string with any duplicates removed.
   */
  std::string remove_duplicates (std::string const& str,
				 char               dup)
  {
    std::string ret;

    for (std::string::size_type pos = 0;
	 pos < str.length();
	 ++pos)
      {
	ret += str[pos];
	if (str[pos] == dup)
	  {
	    while (pos + 1 < str.length() &&
		   str[pos + 1] == dup)
	      ++pos;
	  }
      }

    return ret;
  }

  typedef std::pair<sbuild::stat::error_code,const char *> emap;

  /**
   * This is a list of the supported error codes.  It's used to
   * construct the real error codes map.
   */
  emap init_errors[] =
    {
      emap(sbuild::stat::FILE, N_("Failed to stat file")),
      emap(sbuild::stat::FD,   N_("Failed to stat file descriptor"))
    };

  bool chroot_alphasort (sbuild::chroot::ptr const& c1,
			 sbuild::chroot::ptr const& c2)
  {
    return c1->get_name() < c2->get_name();
  }

}

template<>
error<sbuild::stat::error_code>::map_type
error<sbuild::stat::error_code>::error_strings
(init_errors,
 init_errors + (sizeof(init_errors) / sizeof(init_errors[0])));

std::string
sbuild::basename (std::string name,
		  char        separator)
{
  // Remove trailing separators
  std::string::size_type cur = name.length();
  while (cur - 1 != 0 && name[cur - 1] == separator)
    --cur;
  name.resize(cur);

  // Find last separator
  std::string::size_type pos = name.rfind(separator);

  std::string ret;
  if (pos == std::string::npos)
    ret = name; // No separators
  else if (pos == 0 && name.length() == 1 && name[0] == separator)
    ret = separator; // Only separators
  else
    ret = name.substr(pos + 1); // Basename only

  return remove_duplicates(ret, separator);
}

std::string
sbuild::dirname (std::string name,
		 char        separator)
{
  // Remove trailing separators
  std::string::size_type cur = name.length();
  while (cur - 1 != 0 && name[cur - 1] == separator)
    --cur;
  name.resize(cur);

  // Find last separator
  std::string::size_type pos = name.rfind(separator);

  std::string ret;
  if (pos == std::string::npos)
    ret = "."; // No directory components
  else if (pos == 0)
    ret = separator;
  else
    ret = name.substr(0, pos); // Dirname part

  return remove_duplicates(ret, separator);
}

std::string
sbuild::normalname (std::string name,
		    char        separator)
{
  // Remove trailing separators
  std::string::size_type cur = name.length();
  while (cur - 1 != 0 && name[cur - 1] == separator)
    --cur;
  name.resize(cur);

  return remove_duplicates(name, separator);
}

bool
sbuild::is_absname (std::string const& name)
{
  if (name.empty() || name[0] != '/')
    return false;
  else
    return true;
}

bool
sbuild::is_valid_filename (std::string const& name,
			   bool               lsb_mode)
{
  bool match = false;

  if (lsb_mode)
    {
      static regex lanana_namespace("^[a-z0-9]+$");
      static regex lsb_namespace("^_?([a-z0-9_.]+-)+[a-z0-9]+$");
      static regex debian_cron_namespace("^[a-z0-9][a-z0-9-]*$");
      static regex debian_dpkg_conffile_cruft("dpkg-(old|dist|new|tmp)$");

      if ((regex_search(name, lanana_namespace) ||
	   regex_search(name, lsb_namespace) ||
	   regex_search(name, debian_cron_namespace)) &&
	  !regex_search(name, debian_dpkg_conffile_cruft))
	match = true;
    }
  else
    {
      static regex traditional_namespace("^[a-zA-Z0-9_-]$");
      if (regex_search(name, traditional_namespace))
	match = true;
    }

  return match;
}

std::string
sbuild::getcwd ()
{
  std::string cwd;

  char *raw_cwd = ::getcwd (0, 0);
  if (raw_cwd)
    cwd = raw_cwd;
  else
    cwd = "/";
  free(raw_cwd);

  return cwd;
}

std::string
sbuild::string_list_to_string (sbuild::string_list const& list,
			       std::string const&         separator)
{
  std::string ret;

  for (string_list::const_iterator cur = list.begin();
       cur != list.end();
       ++cur)
    {
      ret += *cur;
      if (cur + 1 != list.end())
	ret += separator;
    }

  return ret;
}

string_list
sbuild::split_string (std::string const& value,
		      std::string const& separator)
{
  string_list ret;

  // Skip any separators at the start
  std::string::size_type last_pos =
    value.find_first_not_of(separator, 0);
  // Find first separator.
  std::string::size_type pos = value.find_first_of(separator, last_pos);

  while (pos !=std::string::npos || last_pos != std::string::npos)
    {
      // Add to list
      if (pos == std::string::npos)
	// Entire string from last_pos
	ret.push_back(value.substr(last_pos, pos));
      else
	// Between pos and last_pos
	ret.push_back(value.substr(last_pos, pos - last_pos));

      // Find next
      last_pos = value.find_first_not_of(separator, pos);
      pos = value.find_first_of(separator, last_pos);
    }

  return ret;
}

string_list
sbuild::split_string_strict (std::string const& value,
			     std::string const& separator)
{
  string_list ret;

  std::string::size_type last_pos = 0;
  // Find first separator.
  std::string::size_type pos = value.find_first_of(separator, last_pos);

  while (pos !=std::string::npos)
    {
      // Add to list
      if (pos == std::string::npos)
	// Entire string from last_pos
	ret.push_back(value.substr(last_pos, pos));
      else
	// Between pos and last_pos
	ret.push_back(value.substr(last_pos, pos - last_pos));

      // Find next
      last_pos = pos + separator.length();
      pos = value.find_first_of(separator, last_pos);
    }

  return ret;
}

std::wstring
sbuild::widen_string (std::string const& str,
		      std::locale        locale)
{
  typedef std::codecvt<wchar_t, char, mbstate_t> codecvt_type;
  codecvt_type const& cvt = std::use_facet<codecvt_type>(locale);
  mbstate_t state;
  const char *cbegin = str.data(), *cend = str.data() + str.size(), *cnext;
  wchar_t *wcnext;
  wchar_t wcbuf[80];
  std::wstring ret;

  std::memset(&state, 0, sizeof(mbstate_t));

  while (1)
    {
      std::codecvt_base::result res =
	cvt.in(state,
	       cbegin, cend, cnext,
	       wcbuf, wcbuf + (sizeof(wcbuf) / sizeof(wcbuf[0])), wcnext);

      if (res == std::codecvt_base::ok || res == std::codecvt_base::partial)
	{
	  ret += std::wstring(wcbuf, wcnext);
	  if (cend == cnext)
	    break;
	}
      else if (res == std::codecvt_base::noconv)
	{
	  ret += std::wstring(cbegin, cend);
	  break;
	}
      else if (res == std::codecvt_base::error)
	{
	  throw std::runtime_error
	    ("A character set conversion failed.  Please report this bug.");
	  break;
	}
      else
	break;

      cbegin = cnext;
    }

  return ret;
}

std::string
sbuild::narrow_string (std::wstring const& str,
		       std::locale         locale)
{
  typedef std::codecvt<wchar_t, char, mbstate_t> codecvt_type;
  codecvt_type const& cvt = std::use_facet<codecvt_type>(locale);
  mbstate_t state;
  const wchar_t *wcbegin = str.data(), *wcend = str.data() + str.size(), *wcnext;
  char *cnext;
  char cbuf[80];
  std::string ret;

  std::memset(&state, 0, sizeof(mbstate_t));

  while (1)
    {
      std::codecvt_base::result res =
	cvt.out(state,
		wcbegin, wcend, wcnext,
		cbuf, cbuf + (sizeof(cbuf) / sizeof(cbuf[0])), cnext);

      if (res == std::codecvt_base::ok || res == std::codecvt_base::partial)
	{
	  ret += std::string(cbuf, cnext);
	  if (wcend == wcnext)
	    break;
	}
      else if (res == std::codecvt_base::noconv)
	{
	  ret += std::string(wcbegin, wcend);
	  break;
	}
      else if (res == std::codecvt_base::error)
	{
	  throw std::runtime_error
	    ("A character set conversion failed.  Please report this bug.");
	  break;
	}
      else
	break;

      wcbegin = wcnext;
    }

  return ret;
}

std::string
sbuild::find_program_in_path (std::string const& program,
			      std::string const& path,
			      std::string const& prefix)
{
  if (program.find_first_of('/') != std::string::npos)
    return program;

  string_list dirs = split_string(path, std::string(1, ':'));

  for (string_list::const_iterator dir = dirs.begin();
       dir != dirs.end();
       ++dir)
    {
      std::string realname = *dir + '/' + program;
      std::string absname;
      if (prefix.length() > 0)
	{
	  absname = prefix;
	  if (dir->length() > 0 && (*dir)[0] != '/')
	    absname += '/';
	}
      absname += realname;

      try
	{
	  if (stat(absname).is_regular() &&
	      access (absname.c_str(), X_OK) == 0)
	    return realname;
	}
      catch (std::runtime_error const& e)
	{
	}
    }

  return "";
}

char **
sbuild::string_list_to_strv (string_list const& str)
{
  char **ret = new char *[str.size() + 1];

  for (string_list::size_type i = 0;
       i < str.size();
       ++i)
    {
      ret[i] = new char[str[i].length() + 1];
      std::strcpy(ret[i], str[i].c_str());
    }
  ret[str.size()] = 0;

  return ret;
}


void
sbuild::strv_delete (char **strv)
{
  for (char **pos = strv; pos != 0 && *pos != 0; ++pos)
    delete *pos;
  delete[] strv;
}

int
sbuild::exec (std::string const& file,
	      string_list const& command,
	      environment const& env)
{
  char **argv = string_list_to_strv(command);
  char **envp = env.get_strv();
  int status;

  if ((status = execve(file.c_str(), argv, envp)) != 0)
    {
      strv_delete(argv);
      strv_delete(envp);
    }

  return status;
}

sbuild::stat::stat (std::string const& file):
  file(file),
  fd(0),
  errorno(0),
  status()
{
  if (::stat(file.c_str(), &this->status) < 0)
    this->errorno = errno;
}

sbuild::stat::stat (std::string const& file,
		    int                fd):
  file(file),
  fd(fd),
  errorno(0),
  status()
{
  if (::fstat(fd, &this->status) < 0)
    this->errorno = errno;
}

sbuild::stat::stat (int fd):
  file(),
  fd(fd),
  errorno(0),
  status()
{
  if (::fstat(fd, &this->status) < 0)
    this->errorno = errno;
}

sbuild::stat::~stat ()
{
}