CRUX-ARM : Home

Home :: Documentation :: Download :: Development :: Community :: Ports :: Packages :: Bugs :: Links :: About :: Donors
Removed some dead (and buggy) code.
[pkgutils-cross.git] / pkgutil.cc
CommitLineData
9ac667e6
SR
1//
2// pkgutils
3//
4// Copyright (c) 2000-2005 Per Liden
5//
6// This program is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation; either version 2 of the License, or
9// (at your option) any later version.
10//
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with this program; if not, write to the Free Software
18// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
19// USA.
20//
21
22#include "pkgutil.h"
23#include <iostream>
24#include <fstream>
25#include <iterator>
26#include <algorithm>
27#include <cstdio>
28#include <cstring>
29#include <cerrno>
30#include <csignal>
31#include <ext/stdio_filebuf.h>
32#include <pwd.h>
33#include <grp.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/wait.h>
37#include <sys/file.h>
38#include <sys/param.h>
39#include <unistd.h>
40#include <fcntl.h>
9ac667e6 41#include <libgen.h>
c3434674
MCO
42#include <archive.h>
43#include <archive_entry.h>
9ac667e6
SR
44
45using __gnu_cxx::stdio_filebuf;
46
9ac667e6
SR
47pkgutil::pkgutil(const string& name)
48 : utilname(name)
49{
50 // Ignore signals
51 struct sigaction sa;
52 memset(&sa, 0, sizeof(sa));
53 sa.sa_handler = SIG_IGN;
54 sigaction(SIGHUP, &sa, 0);
55 sigaction(SIGINT, &sa, 0);
56 sigaction(SIGQUIT, &sa, 0);
57 sigaction(SIGTERM, &sa, 0);
58}
59
60void pkgutil::db_open(const string& path)
61{
62 // Read database
63 root = trim_filename(path + "/");
64 const string filename = root + PKG_DB;
65
66 int fd = open(filename.c_str(), O_RDONLY);
67 if (fd == -1)
68 throw runtime_error_with_errno("could not open " + filename);
69
70 stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
71 istream in(&filebuf);
72 if (!in)
73 throw runtime_error_with_errno("could not read " + filename);
74
75 while (!in.eof()) {
76 // Read record
77 string name;
78 pkginfo_t info;
79 getline(in, name);
80 getline(in, info.version);
81 for (;;) {
82 string file;
83 getline(in, file);
84
85 if (file.empty())
86 break; // End of record
87
88 info.files.insert(info.files.end(), file);
89 }
90 if (!info.files.empty())
91 packages[name] = info;
92 }
93
94#ifndef NDEBUG
95 cerr << packages.size() << " packages found in database" << endl;
96#endif
97}
98
99void pkgutil::db_commit()
100{
101 const string dbfilename = root + PKG_DB;
102 const string dbfilename_new = dbfilename + ".incomplete_transaction";
103 const string dbfilename_bak = dbfilename + ".backup";
104
105 // Remove failed transaction (if it exists)
106 if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
107 throw runtime_error_with_errno("could not remove " + dbfilename_new);
108
109 // Write new database
110 int fd_new = creat(dbfilename_new.c_str(), 0444);
111 if (fd_new == -1)
112 throw runtime_error_with_errno("could not create " + dbfilename_new);
113
114 stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
115 ostream db_new(&filebuf_new);
116 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
117 if (!i->second.files.empty()) {
118 db_new << i->first << "\n";
119 db_new << i->second.version << "\n";
120 copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
121 db_new << "\n";
122 }
123 }
124
125 db_new.flush();
126
127 // Make sure the new database was successfully written
128 if (!db_new)
129 throw runtime_error("could not write " + dbfilename_new);
130
131 // Synchronize file to disk
132 if (fsync(fd_new) == -1)
133 throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
134
135 // Relink database backup
136 if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
137 throw runtime_error_with_errno("could not remove " + dbfilename_bak);
138 if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
139 throw runtime_error_with_errno("could not create " + dbfilename_bak);
140
141 // Move new database into place
142 if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
143 throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
144
145#ifndef NDEBUG
146 cerr << packages.size() << " packages written to database" << endl;
147#endif
148}
149
150void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
151{
152 packages[name] = info;
153}
154
155bool pkgutil::db_find_pkg(const string& name)
156{
157 return (packages.find(name) != packages.end());
158}
159
160void pkgutil::db_rm_pkg(const string& name)
161{
162 set<string> files = packages[name].files;
163 packages.erase(name);
164
165#ifndef NDEBUG
166 cerr << "Removing package phase 1 (all files in package):" << endl;
167 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
168 cerr << endl;
169#endif
170
171 // Don't delete files that still have references
172 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
173 for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
174 files.erase(*j);
175
176#ifndef NDEBUG
177 cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
178 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
179 cerr << endl;
180#endif
181
182 // Delete the files
183 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
184 const string filename = root + *i;
185 if (file_exists(filename) && remove(filename.c_str()) == -1) {
186 const char* msg = strerror(errno);
187 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
188 }
189 }
190}
191
192void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
193{
194 set<string> files = packages[name].files;
195 packages.erase(name);
196
197#ifndef NDEBUG
198 cerr << "Removing package phase 1 (all files in package):" << endl;
199 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
200 cerr << endl;
201#endif
202
203 // Don't delete files found in the keep list
204 for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
205 files.erase(*i);
206
207#ifndef NDEBUG
208 cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
209 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
210 cerr << endl;
211#endif
212
213 // Don't delete files that still have references
214 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
215 for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
216 files.erase(*j);
217
218#ifndef NDEBUG
219 cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
220 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
221 cerr << endl;
222#endif
223
224 // Delete the files
225 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
226 const string filename = root + *i;
227 if (file_exists(filename) && remove(filename.c_str()) == -1) {
228 if (errno == ENOTEMPTY)
229 continue;
230 const char* msg = strerror(errno);
231 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
232 }
233 }
234}
235
236void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
237{
238 // Remove all references
239 for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
240 for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
241 i->second.files.erase(*j);
242
243#ifndef NDEBUG
244 cerr << "Removing files:" << endl;
245 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
246 cerr << endl;
247#endif
248
249 // Don't delete files found in the keep list
250 for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
251 files.erase(*i);
252
253 // Delete the files
254 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
255 const string filename = root + *i;
256 if (file_exists(filename) && remove(filename.c_str()) == -1) {
257 if (errno == ENOTEMPTY)
258 continue;
259 const char* msg = strerror(errno);
260 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
261 }
262 }
263}
264
265set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
266{
267 set<string> files;
268
269 // Find conflicting files in database
270 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
271 if (i->first != name) {
272 set_intersection(info.files.begin(), info.files.end(),
273 i->second.files.begin(), i->second.files.end(),
274 inserter(files, files.end()));
275 }
276 }
277
278#ifndef NDEBUG
279 cerr << "Conflicts phase 1 (conflicts in database):" << endl;
280 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
281 cerr << endl;
282#endif
283
284 // Find conflicting files in filesystem
285 for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
286 const string filename = root + *i;
287 if (file_exists(filename) && files.find(*i) == files.end())
288 files.insert(files.end(), *i);
289 }
290
291#ifndef NDEBUG
292 cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
293 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
294 cerr << endl;
295#endif
296
297 // Exclude directories
298 set<string> tmp = files;
299 for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
300 if ((*i)[i->length() - 1] == '/')
301 files.erase(*i);
302 }
303
304#ifndef NDEBUG
305 cerr << "Conflicts phase 3 (directories excluded):" << endl;
306 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
307 cerr << endl;
308#endif
309
310 // If this is an upgrade, remove files already owned by this package
311 if (packages.find(name) != packages.end()) {
312 for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
313 files.erase(*i);
314
315#ifndef NDEBUG
316 cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
317 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
318 cerr << endl;
319#endif
320 }
321
322 return files;
323}
324
325pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
326{
327 pair<string, pkginfo_t> result;
328 unsigned int i;
c3434674
MCO
329 struct archive* archive;
330 struct archive_entry* entry;
9ac667e6
SR
331
332 // Extract name and version from filename
333 string basename(filename, filename.rfind('/') + 1);
334 string name(basename, 0, basename.find(VERSION_DELIM));
335 string version(basename, 0, basename.rfind(PKG_EXT));
336 version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
337
338 if (name.empty() || version.empty())
339 throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
340
341 result.first = name;
342 result.second.version = version;
343
c3434674
MCO
344 archive = archive_read_new();
345 archive_read_support_compression_all(archive);
346 archive_read_support_format_all(archive);
347
348 if (archive_read_open_filename(archive,
349 const_cast<char*>(filename.c_str()),
350 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
25f9975c 351 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
9ac667e6 352
c3434674
MCO
353 for (i = 0; archive_read_next_header(archive, &entry) ==
354 ARCHIVE_OK; ++i) {
c3434674
MCO
355
356 result.second.files.insert(result.second.files.end(),
357 archive_entry_pathname(entry));
358
7f84e1cc 359 mode_t mode = archive_entry_mode(entry);
c3434674 360
7f84e1cc 361 if (S_ISREG(mode) &&
c3434674 362 archive_read_data_skip(archive) != ARCHIVE_OK)
25f9975c 363 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
9ac667e6
SR
364 }
365
366 if (i == 0) {
c3434674 367 if (archive_errno(archive) == 0)
9ac667e6
SR
368 throw runtime_error("empty package");
369 else
370 throw runtime_error("could not read " + filename);
371 }
372
c3434674 373 archive_read_finish(archive);
9ac667e6
SR
374
375 return result;
376}
377
3e5b7ed9 378void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
9ac667e6 379{
c3434674
MCO
380 struct archive* archive;
381 struct archive_entry* entry;
9ac667e6
SR
382 unsigned int i;
383
c3434674
MCO
384 archive = archive_read_new();
385 archive_read_support_compression_all(archive);
386 archive_read_support_format_all(archive);
387
388 if (archive_read_open_filename(archive,
389 const_cast<char*>(filename.c_str()),
390 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
25f9975c 391 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
9ac667e6 392
c3434674
MCO
393 chdir(root.c_str());
394
395 for (i = 0; archive_read_next_header(archive, &entry) ==
396 ARCHIVE_OK; ++i) {
397 string archive_filename = archive_entry_pathname(entry);
9ac667e6
SR
398 string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
399 string original_filename = trim_filename(root + string("/") + archive_filename);
400 string real_filename = original_filename;
401
3e5b7ed9
TS
402 // Check if file is filtered out via INSTALL
403 if (non_install_list.find(archive_filename) != non_install_list.end()) {
7f84e1cc 404 mode_t mode;
c3434674 405
22131995
TS
406 cout << utilname << ": ignoring " << archive_filename << endl;
407
7f84e1cc 408 mode = archive_entry_mode(entry);
c3434674 409
7f84e1cc 410 if (S_ISREG(mode))
c3434674 411 archive_read_data_skip(archive);
3e5b7ed9
TS
412
413 continue;
414 }
415
9ac667e6
SR
416 // Check if file should be rejected
417 if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
418 real_filename = trim_filename(reject_dir + string("/") + archive_filename);
419
c3434674
MCO
420 archive_entry_set_pathname(entry, const_cast<char*>
421 (real_filename.c_str()));
422
9ac667e6 423 // Extract file
2a62ed9a
TS
424 unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK;
425
426 if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
9ac667e6
SR
427 // If a file fails to install we just print an error message and
428 // continue trying to install the rest of the package.
c3434674 429 const char* msg = archive_error_string(archive);
9ac667e6
SR
430 cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
431 continue;
432 }
433
434 // Check rejected file
435 if (real_filename != original_filename) {
436 bool remove_file = false;
7f84e1cc 437 mode_t mode = archive_entry_mode(entry);
9ac667e6
SR
438
439 // Directory
7f84e1cc 440 if (S_ISDIR(mode))
9ac667e6
SR
441 remove_file = permissions_equal(real_filename, original_filename);
442 // Other files
443 else
444 remove_file = permissions_equal(real_filename, original_filename) &&
445 (file_empty(real_filename) || file_equal(real_filename, original_filename));
446
447 // Remove rejected file or signal about its existence
448 if (remove_file)
449 file_remove(reject_dir, real_filename);
450 else
451 cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
452 }
453 }
454
455 if (i == 0) {
c3434674 456 if (archive_errno(archive) == 0)
9ac667e6
SR
457 throw runtime_error("empty package");
458 else
459 throw runtime_error("could not read " + filename);
460 }
461
c3434674 462 archive_read_finish(archive);
9ac667e6
SR
463}
464
465void pkgutil::ldconfig() const
466{
467 // Only execute ldconfig if /etc/ld.so.conf exists
468 if (file_exists(root + LDCONFIG_CONF)) {
469 pid_t pid = fork();
470
471 if (pid == -1)
472 throw runtime_error_with_errno("fork() failed");
473
474 if (pid == 0) {
5401bd45 475 execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
9ac667e6
SR
476 const char* msg = strerror(errno);
477 cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
478 exit(EXIT_FAILURE);
479 } else {
480 if (waitpid(pid, 0, 0) == -1)
481 throw runtime_error_with_errno("waitpid() failed");
482 }
483 }
484}
485
486void pkgutil::pkg_footprint(string& filename) const
487{
fa6b0879 488 unsigned int i;
c3434674
MCO
489 struct archive* archive;
490 struct archive_entry* entry;
9ac667e6 491
80db05ef
TS
492 map<string, mode_t> hardlink_target_modes;
493
494 // We first do a run over the archive and remember the modes
495 // of regular files.
496 // In the second run, we print the footprint - using the stored
497 // modes for hardlinks.
498 //
499 // FIXME the code duplication here is butt ugly
500 archive = archive_read_new();
501 archive_read_support_compression_all(archive);
502 archive_read_support_format_all(archive);
503
504 if (archive_read_open_filename(archive,
505 const_cast<char*>(filename.c_str()),
506 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
507 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
508
509 for (i = 0; archive_read_next_header(archive, &entry) ==
510 ARCHIVE_OK; ++i) {
511
512 mode_t mode = archive_entry_mode(entry);
513
514 if (!archive_entry_hardlink(entry)) {
515 const char *s = archive_entry_pathname(entry);
516
517 hardlink_target_modes[s] = mode;
518 }
519
520 if (S_ISREG(mode) && archive_read_data_skip(archive))
521 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
522 }
523
524 archive_read_finish(archive);
525
526 // Too bad, there doesn't seem to be a way to reuse our archive
527 // instance
c3434674
MCO
528 archive = archive_read_new();
529 archive_read_support_compression_all(archive);
530 archive_read_support_format_all(archive);
531
532 if (archive_read_open_filename(archive,
533 const_cast<char*>(filename.c_str()),
534 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
25f9975c 535 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
9ac667e6 536
c3434674
MCO
537 for (i = 0; archive_read_next_header(archive, &entry) ==
538 ARCHIVE_OK; ++i) {
7f84e1cc 539 mode_t mode = archive_entry_mode(entry);
c3434674 540
9ac667e6 541 // Access permissions
7f84e1cc 542 if (S_ISLNK(mode)) {
9ac667e6
SR
543 // Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
544 // To avoid getting different footprints we always use "lrwxrwxrwx".
545 cout << "lrwxrwxrwx";
546 } else {
80db05ef
TS
547 const char *h = archive_entry_hardlink(entry);
548
549 if (h)
550 cout << mtos(hardlink_target_modes[h]);
551 else
552 cout << mtos(mode);
9ac667e6
SR
553 }
554
555 cout << '\t';
556
557 // User
c3434674 558 uid_t uid = archive_entry_uid(entry);
9ac667e6
SR
559 struct passwd* pw = getpwuid(uid);
560 if (pw)
561 cout << pw->pw_name;
562 else
563 cout << uid;
564
565 cout << '/';
566
567 // Group
c3434674 568 gid_t gid = archive_entry_gid(entry);
9ac667e6
SR
569 struct group* gr = getgrgid(gid);
570 if (gr)
571 cout << gr->gr_name;
572 else
573 cout << gid;
574
575 // Filename
c3434674 576 cout << '\t' << archive_entry_pathname(entry);
9ac667e6
SR
577
578 // Special cases
7f84e1cc 579 if (S_ISLNK(mode)) {
9ac667e6 580 // Symlink
c3434674 581 cout << " -> " << archive_entry_symlink(entry);
7f84e1cc
TS
582 } else if (S_ISCHR(mode) ||
583 S_ISBLK(mode)) {
9ac667e6 584 // Device
c3434674
MCO
585 cout << " (" << archive_entry_rdevmajor(entry)
586 << ", " << archive_entry_rdevminor(entry)
587 << ")";
7f84e1cc 588 } else if (S_ISREG(mode) &&
c3434674 589 archive_entry_size(entry) == 0) {
9ac667e6
SR
590 // Empty regular file
591 cout << " (EMPTY)";
592 }
593
594 cout << '\n';
595
7f84e1cc 596 if (S_ISREG(mode) && archive_read_data_skip(archive))
fa6b0879
TS
597 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
598 }
9ac667e6 599
fa6b0879 600 if (i == 0) {
c3434674 601 if (archive_errno(archive) == 0)
fa6b0879
TS
602 throw runtime_error("empty package");
603 else
604 throw runtime_error("could not read " + filename);
605 }
9ac667e6 606
c3434674 607 archive_read_finish(archive);
9ac667e6
SR
608}
609
610void pkgutil::print_version() const
611{
612 cout << utilname << " (pkgutils) " << VERSION << endl;
613}
614
615db_lock::db_lock(const string& root, bool exclusive)
616 : dir(0)
617{
618 const string dirname = trim_filename(root + string("/") + PKG_DIR);
619
620 if (!(dir = opendir(dirname.c_str())))
621 throw runtime_error_with_errno("could not read directory " + dirname);
622
623 if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
624 if (errno == EWOULDBLOCK)
625 throw runtime_error("package database is currently locked by another process");
626 else
627 throw runtime_error_with_errno("could not lock directory " + dirname);
628 }
629}
630
631db_lock::~db_lock()
632{
633 if (dir) {
634 flock(dirfd(dir), LOCK_UN);
635 closedir(dir);
636 }
637}
638
639void assert_argument(char** argv, int argc, int index)
640{
641 if (argc - 1 < index + 1)
642 throw runtime_error("option " + string(argv[index]) + " requires an argument");
643}
644
645string itos(unsigned int value)
646{
647 static char buf[20];
648 sprintf(buf, "%u", value);
649 return buf;
650}
651
652string mtos(mode_t mode)
653{
654 string s;
655
656 // File type
657 switch (mode & S_IFMT) {
658 case S_IFREG: s += '-'; break; // Regular
659 case S_IFDIR: s += 'd'; break; // Directory
660 case S_IFLNK: s += 'l'; break; // Symbolic link
661 case S_IFCHR: s += 'c'; break; // Character special
662 case S_IFBLK: s += 'b'; break; // Block special
663 case S_IFSOCK: s += 's'; break; // Socket
664 case S_IFIFO: s += 'p'; break; // Fifo
665 default: s += '?'; break; // Unknown
666 }
667
668 // User permissions
669 s += (mode & S_IRUSR) ? 'r' : '-';
670 s += (mode & S_IWUSR) ? 'w' : '-';
671 switch (mode & (S_IXUSR | S_ISUID)) {
672 case S_IXUSR: s += 'x'; break;
673 case S_ISUID: s += 'S'; break;
674 case S_IXUSR | S_ISUID: s += 's'; break;
675 default: s += '-'; break;
676 }
677
678 // Group permissions
679 s += (mode & S_IRGRP) ? 'r' : '-';
680 s += (mode & S_IWGRP) ? 'w' : '-';
681 switch (mode & (S_IXGRP | S_ISGID)) {
682 case S_IXGRP: s += 'x'; break;
683 case S_ISGID: s += 'S'; break;
684 case S_IXGRP | S_ISGID: s += 's'; break;
685 default: s += '-'; break;
686 }
687
688 // Other permissions
689 s += (mode & S_IROTH) ? 'r' : '-';
690 s += (mode & S_IWOTH) ? 'w' : '-';
691 switch (mode & (S_IXOTH | S_ISVTX)) {
692 case S_IXOTH: s += 'x'; break;
693 case S_ISVTX: s += 'T'; break;
694 case S_IXOTH | S_ISVTX: s += 't'; break;
695 default: s += '-'; break;
696 }
697
698 return s;
699}
700
9ac667e6
SR
701string trim_filename(const string& filename)
702{
703 string search("//");
704 string result = filename;
705
706 for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
707 result.replace(pos, search.size(), "/");
708
709 return result;
710}
711
712bool file_exists(const string& filename)
713{
714 struct stat buf;
715 return !lstat(filename.c_str(), &buf);
716}
717
718bool file_empty(const string& filename)
719{
720 struct stat buf;
721
722 if (lstat(filename.c_str(), &buf) == -1)
723 return false;
724
725 return (S_ISREG(buf.st_mode) && buf.st_size == 0);
726}
727
728bool file_equal(const string& file1, const string& file2)
729{
730 struct stat buf1, buf2;
731
732 if (lstat(file1.c_str(), &buf1) == -1)
733 return false;
734
735 if (lstat(file2.c_str(), &buf2) == -1)
736 return false;
737
738 // Regular files
739 if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
740 ifstream f1(file1.c_str());
741 ifstream f2(file2.c_str());
742
743 if (!f1 || !f2)
744 return false;
745
746 while (!f1.eof()) {
747 char buffer1[4096];
748 char buffer2[4096];
749 f1.read(buffer1, 4096);
750 f2.read(buffer2, 4096);
751 if (f1.gcount() != f2.gcount() ||
752 memcmp(buffer1, buffer2, f1.gcount()) ||
753 f1.eof() != f2.eof())
754 return false;
755 }
756
757 return true;
758 }
759 // Symlinks
760 else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
761 char symlink1[MAXPATHLEN];
762 char symlink2[MAXPATHLEN];
763
764 memset(symlink1, 0, MAXPATHLEN);
765 memset(symlink2, 0, MAXPATHLEN);
766
767 if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
768 return false;
769
770 if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
771 return false;
772
773 return !strncmp(symlink1, symlink2, MAXPATHLEN);
774 }
775 // Character devices
776 else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
777 return buf1.st_dev == buf2.st_dev;
778 }
779 // Block devices
780 else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
781 return buf1.st_dev == buf2.st_dev;
782 }
783
784 return false;
785}
786
787bool permissions_equal(const string& file1, const string& file2)
788{
789 struct stat buf1;
790 struct stat buf2;
791
792 if (lstat(file1.c_str(), &buf1) == -1)
793 return false;
794
795 if (lstat(file2.c_str(), &buf2) == -1)
796 return false;
797
798 return(buf1.st_mode == buf2.st_mode) &&
799 (buf1.st_uid == buf2.st_uid) &&
800 (buf1.st_gid == buf2.st_gid);
801}
802
803void file_remove(const string& basedir, const string& filename)
804{
805 if (filename != basedir && !remove(filename.c_str())) {
806 char* path = strdup(filename.c_str());
807 file_remove(basedir, dirname(path));
808 free(path);
809 }
810}