CRUX-ARM : Home

Home :: Documentation :: Download :: Development :: Community :: Ports :: Packages :: Bugs :: Links :: About :: Donors
Moved archive initialization code to INIT_ARCHIVE.
[pkgutils-cross.git] / pkgutil.cc
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>
41 #include <libgen.h>
42 #include <archive.h>
43 #include <archive_entry.h>
44
45 #define INIT_ARCHIVE(ar) \
46 archive_read_support_compression_all((ar)); \
47 archive_read_support_format_all((ar))
48
49 using __gnu_cxx::stdio_filebuf;
50
51 pkgutil::pkgutil(const string& name)
52 : utilname(name)
53 {
54 // Ignore signals
55 struct sigaction sa;
56 memset(&sa, 0, sizeof(sa));
57 sa.sa_handler = SIG_IGN;
58 sigaction(SIGHUP, &sa, 0);
59 sigaction(SIGINT, &sa, 0);
60 sigaction(SIGQUIT, &sa, 0);
61 sigaction(SIGTERM, &sa, 0);
62 }
63
64 void pkgutil::db_open(const string& path)
65 {
66 // Read database
67 root = trim_filename(path + "/");
68 const string filename = root + PKG_DB;
69
70 int fd = open(filename.c_str(), O_RDONLY);
71 if (fd == -1)
72 throw runtime_error_with_errno("could not open " + filename);
73
74 stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
75 istream in(&filebuf);
76 if (!in)
77 throw runtime_error_with_errno("could not read " + filename);
78
79 while (!in.eof()) {
80 // Read record
81 string name;
82 pkginfo_t info;
83 getline(in, name);
84 getline(in, info.version);
85 for (;;) {
86 string file;
87 getline(in, file);
88
89 if (file.empty())
90 break; // End of record
91
92 info.files.insert(info.files.end(), file);
93 }
94 if (!info.files.empty())
95 packages[name] = info;
96 }
97
98 #ifndef NDEBUG
99 cerr << packages.size() << " packages found in database" << endl;
100 #endif
101 }
102
103 void pkgutil::db_commit()
104 {
105 const string dbfilename = root + PKG_DB;
106 const string dbfilename_new = dbfilename + ".incomplete_transaction";
107 const string dbfilename_bak = dbfilename + ".backup";
108
109 // Remove failed transaction (if it exists)
110 if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
111 throw runtime_error_with_errno("could not remove " + dbfilename_new);
112
113 // Write new database
114 int fd_new = creat(dbfilename_new.c_str(), 0444);
115 if (fd_new == -1)
116 throw runtime_error_with_errno("could not create " + dbfilename_new);
117
118 stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
119 ostream db_new(&filebuf_new);
120 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
121 if (!i->second.files.empty()) {
122 db_new << i->first << "\n";
123 db_new << i->second.version << "\n";
124 copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
125 db_new << "\n";
126 }
127 }
128
129 db_new.flush();
130
131 // Make sure the new database was successfully written
132 if (!db_new)
133 throw runtime_error("could not write " + dbfilename_new);
134
135 // Synchronize file to disk
136 if (fsync(fd_new) == -1)
137 throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
138
139 // Relink database backup
140 if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
141 throw runtime_error_with_errno("could not remove " + dbfilename_bak);
142 if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
143 throw runtime_error_with_errno("could not create " + dbfilename_bak);
144
145 // Move new database into place
146 if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
147 throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
148
149 #ifndef NDEBUG
150 cerr << packages.size() << " packages written to database" << endl;
151 #endif
152 }
153
154 void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
155 {
156 packages[name] = info;
157 }
158
159 bool pkgutil::db_find_pkg(const string& name)
160 {
161 return (packages.find(name) != packages.end());
162 }
163
164 void pkgutil::db_rm_pkg(const string& name)
165 {
166 set<string> files = packages[name].files;
167 packages.erase(name);
168
169 #ifndef NDEBUG
170 cerr << "Removing package phase 1 (all files in package):" << endl;
171 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
172 cerr << endl;
173 #endif
174
175 // Don't delete files that still have references
176 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
177 for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
178 files.erase(*j);
179
180 #ifndef NDEBUG
181 cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
182 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
183 cerr << endl;
184 #endif
185
186 // Delete the files
187 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
188 const string filename = root + *i;
189 if (file_exists(filename) && remove(filename.c_str()) == -1) {
190 const char* msg = strerror(errno);
191 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
192 }
193 }
194 }
195
196 void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
197 {
198 set<string> files = packages[name].files;
199 packages.erase(name);
200
201 #ifndef NDEBUG
202 cerr << "Removing package phase 1 (all files in package):" << endl;
203 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
204 cerr << endl;
205 #endif
206
207 // Don't delete files found in the keep list
208 for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
209 files.erase(*i);
210
211 #ifndef NDEBUG
212 cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
213 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
214 cerr << endl;
215 #endif
216
217 // Don't delete files that still have references
218 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
219 for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
220 files.erase(*j);
221
222 #ifndef NDEBUG
223 cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
224 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
225 cerr << endl;
226 #endif
227
228 // Delete the files
229 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
230 const string filename = root + *i;
231 if (file_exists(filename) && remove(filename.c_str()) == -1) {
232 if (errno == ENOTEMPTY)
233 continue;
234 const char* msg = strerror(errno);
235 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
236 }
237 }
238 }
239
240 void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
241 {
242 // Remove all references
243 for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
244 for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
245 i->second.files.erase(*j);
246
247 #ifndef NDEBUG
248 cerr << "Removing files:" << endl;
249 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
250 cerr << endl;
251 #endif
252
253 // Don't delete files found in the keep list
254 for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
255 files.erase(*i);
256
257 // Delete the files
258 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
259 const string filename = root + *i;
260 if (file_exists(filename) && remove(filename.c_str()) == -1) {
261 if (errno == ENOTEMPTY)
262 continue;
263 const char* msg = strerror(errno);
264 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
265 }
266 }
267 }
268
269 set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
270 {
271 set<string> files;
272
273 // Find conflicting files in database
274 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
275 if (i->first != name) {
276 set_intersection(info.files.begin(), info.files.end(),
277 i->second.files.begin(), i->second.files.end(),
278 inserter(files, files.end()));
279 }
280 }
281
282 #ifndef NDEBUG
283 cerr << "Conflicts phase 1 (conflicts in database):" << endl;
284 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
285 cerr << endl;
286 #endif
287
288 // Find conflicting files in filesystem
289 for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
290 const string filename = root + *i;
291 if (file_exists(filename) && files.find(*i) == files.end())
292 files.insert(files.end(), *i);
293 }
294
295 #ifndef NDEBUG
296 cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
297 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
298 cerr << endl;
299 #endif
300
301 // Exclude directories
302 set<string> tmp = files;
303 for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
304 if ((*i)[i->length() - 1] == '/')
305 files.erase(*i);
306 }
307
308 #ifndef NDEBUG
309 cerr << "Conflicts phase 3 (directories excluded):" << endl;
310 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
311 cerr << endl;
312 #endif
313
314 // If this is an upgrade, remove files already owned by this package
315 if (packages.find(name) != packages.end()) {
316 for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
317 files.erase(*i);
318
319 #ifndef NDEBUG
320 cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
321 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
322 cerr << endl;
323 #endif
324 }
325
326 return files;
327 }
328
329 pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
330 {
331 pair<string, pkginfo_t> result;
332 unsigned int i;
333 struct archive* archive;
334 struct archive_entry* entry;
335
336 // Extract name and version from filename
337 string basename(filename, filename.rfind('/') + 1);
338 string name(basename, 0, basename.find(VERSION_DELIM));
339 string version(basename, 0, basename.rfind(PKG_EXT));
340 version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
341
342 if (name.empty() || version.empty())
343 throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
344
345 result.first = name;
346 result.second.version = version;
347
348 archive = archive_read_new();
349 INIT_ARCHIVE(archive);
350
351 if (archive_read_open_filename(archive,
352 const_cast<char*>(filename.c_str()),
353 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
354 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
355
356 for (i = 0; archive_read_next_header(archive, &entry) ==
357 ARCHIVE_OK; ++i) {
358
359 result.second.files.insert(result.second.files.end(),
360 archive_entry_pathname(entry));
361
362 mode_t mode = archive_entry_mode(entry);
363
364 if (S_ISREG(mode) &&
365 archive_read_data_skip(archive) != ARCHIVE_OK)
366 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
367 }
368
369 if (i == 0) {
370 if (archive_errno(archive) == 0)
371 throw runtime_error("empty package");
372 else
373 throw runtime_error("could not read " + filename);
374 }
375
376 archive_read_finish(archive);
377
378 return result;
379 }
380
381 void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
382 {
383 struct archive* archive;
384 struct archive_entry* entry;
385 unsigned int i;
386
387 archive = archive_read_new();
388 INIT_ARCHIVE(archive);
389
390 if (archive_read_open_filename(archive,
391 const_cast<char*>(filename.c_str()),
392 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
393 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
394
395 chdir(root.c_str());
396
397 for (i = 0; archive_read_next_header(archive, &entry) ==
398 ARCHIVE_OK; ++i) {
399 string archive_filename = archive_entry_pathname(entry);
400 string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
401 string original_filename = trim_filename(root + string("/") + archive_filename);
402 string real_filename = original_filename;
403
404 // Check if file is filtered out via INSTALL
405 if (non_install_list.find(archive_filename) != non_install_list.end()) {
406 mode_t mode;
407
408 cout << utilname << ": ignoring " << archive_filename << endl;
409
410 mode = archive_entry_mode(entry);
411
412 if (S_ISREG(mode))
413 archive_read_data_skip(archive);
414
415 continue;
416 }
417
418 // Check if file should be rejected
419 if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
420 real_filename = trim_filename(reject_dir + string("/") + archive_filename);
421
422 archive_entry_set_pathname(entry, const_cast<char*>
423 (real_filename.c_str()));
424
425 // Extract file
426 unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK;
427
428 if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
429 // If a file fails to install we just print an error message and
430 // continue trying to install the rest of the package.
431 const char* msg = archive_error_string(archive);
432 cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
433 continue;
434 }
435
436 // Check rejected file
437 if (real_filename != original_filename) {
438 bool remove_file = false;
439 mode_t mode = archive_entry_mode(entry);
440
441 // Directory
442 if (S_ISDIR(mode))
443 remove_file = permissions_equal(real_filename, original_filename);
444 // Other files
445 else
446 remove_file = permissions_equal(real_filename, original_filename) &&
447 (file_empty(real_filename) || file_equal(real_filename, original_filename));
448
449 // Remove rejected file or signal about its existence
450 if (remove_file)
451 file_remove(reject_dir, real_filename);
452 else
453 cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
454 }
455 }
456
457 if (i == 0) {
458 if (archive_errno(archive) == 0)
459 throw runtime_error("empty package");
460 else
461 throw runtime_error("could not read " + filename);
462 }
463
464 archive_read_finish(archive);
465 }
466
467 void pkgutil::ldconfig() const
468 {
469 // Only execute ldconfig if /etc/ld.so.conf exists
470 if (file_exists(root + LDCONFIG_CONF)) {
471 pid_t pid = fork();
472
473 if (pid == -1)
474 throw runtime_error_with_errno("fork() failed");
475
476 if (pid == 0) {
477 execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
478 const char* msg = strerror(errno);
479 cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
480 exit(EXIT_FAILURE);
481 } else {
482 if (waitpid(pid, 0, 0) == -1)
483 throw runtime_error_with_errno("waitpid() failed");
484 }
485 }
486 }
487
488 void pkgutil::pkg_footprint(string& filename) const
489 {
490 unsigned int i;
491 struct archive* archive;
492 struct archive_entry* entry;
493
494 map<string, mode_t> hardlink_target_modes;
495
496 // We first do a run over the archive and remember the modes
497 // of regular files.
498 // In the second run, we print the footprint - using the stored
499 // modes for hardlinks.
500 //
501 // FIXME the code duplication here is butt ugly
502 archive = archive_read_new();
503 INIT_ARCHIVE(archive);
504
505 if (archive_read_open_filename(archive,
506 const_cast<char*>(filename.c_str()),
507 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
508 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
509
510 for (i = 0; archive_read_next_header(archive, &entry) ==
511 ARCHIVE_OK; ++i) {
512
513 mode_t mode = archive_entry_mode(entry);
514
515 if (!archive_entry_hardlink(entry)) {
516 const char *s = archive_entry_pathname(entry);
517
518 hardlink_target_modes[s] = mode;
519 }
520
521 if (S_ISREG(mode) && archive_read_data_skip(archive))
522 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
523 }
524
525 archive_read_finish(archive);
526
527 // Too bad, there doesn't seem to be a way to reuse our archive
528 // instance
529 archive = archive_read_new();
530 INIT_ARCHIVE(archive);
531
532 if (archive_read_open_filename(archive,
533 const_cast<char*>(filename.c_str()),
534 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
535 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
536
537 for (i = 0; archive_read_next_header(archive, &entry) ==
538 ARCHIVE_OK; ++i) {
539 mode_t mode = archive_entry_mode(entry);
540
541 // Access permissions
542 if (S_ISLNK(mode)) {
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 {
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);
553 }
554
555 cout << '\t';
556
557 // User
558 uid_t uid = archive_entry_uid(entry);
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
568 gid_t gid = archive_entry_gid(entry);
569 struct group* gr = getgrgid(gid);
570 if (gr)
571 cout << gr->gr_name;
572 else
573 cout << gid;
574
575 // Filename
576 cout << '\t' << archive_entry_pathname(entry);
577
578 // Special cases
579 if (S_ISLNK(mode)) {
580 // Symlink
581 cout << " -> " << archive_entry_symlink(entry);
582 } else if (S_ISCHR(mode) ||
583 S_ISBLK(mode)) {
584 // Device
585 cout << " (" << archive_entry_rdevmajor(entry)
586 << ", " << archive_entry_rdevminor(entry)
587 << ")";
588 } else if (S_ISREG(mode) &&
589 archive_entry_size(entry) == 0) {
590 // Empty regular file
591 cout << " (EMPTY)";
592 }
593
594 cout << '\n';
595
596 if (S_ISREG(mode) && archive_read_data_skip(archive))
597 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
598 }
599
600 if (i == 0) {
601 if (archive_errno(archive) == 0)
602 throw runtime_error("empty package");
603 else
604 throw runtime_error("could not read " + filename);
605 }
606
607 archive_read_finish(archive);
608 }
609
610 void pkgutil::print_version() const
611 {
612 cout << utilname << " (pkgutils) " << VERSION << endl;
613 }
614
615 db_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
631 db_lock::~db_lock()
632 {
633 if (dir) {
634 flock(dirfd(dir), LOCK_UN);
635 closedir(dir);
636 }
637 }
638
639 void 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
645 string itos(unsigned int value)
646 {
647 static char buf[20];
648 sprintf(buf, "%u", value);
649 return buf;
650 }
651
652 string 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
701 string 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
712 bool file_exists(const string& filename)
713 {
714 struct stat buf;
715 return !lstat(filename.c_str(), &buf);
716 }
717
718 bool 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
728 bool 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
787 bool 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
803 void 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 }