CRUX-ARM : Home

Home :: Documentation :: Download :: Development :: Community :: Ports :: Packages :: Bugs :: Links :: About :: Donors
Fixed the permission lookup problem for hardlinks.
[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 <zlib.h>
42 #include <libgen.h>
43 #include <archive.h>
44 #include <archive_entry.h>
45
46 using __gnu_cxx::stdio_filebuf;
47
48 pkgutil::pkgutil(const string& name)
49 : utilname(name)
50 {
51 // Ignore signals
52 struct sigaction sa;
53 memset(&sa, 0, sizeof(sa));
54 sa.sa_handler = SIG_IGN;
55 sigaction(SIGHUP, &sa, 0);
56 sigaction(SIGINT, &sa, 0);
57 sigaction(SIGQUIT, &sa, 0);
58 sigaction(SIGTERM, &sa, 0);
59 }
60
61 void pkgutil::db_open(const string& path)
62 {
63 // Read database
64 root = trim_filename(path + "/");
65 const string filename = root + PKG_DB;
66
67 int fd = open(filename.c_str(), O_RDONLY);
68 if (fd == -1)
69 throw runtime_error_with_errno("could not open " + filename);
70
71 stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
72 istream in(&filebuf);
73 if (!in)
74 throw runtime_error_with_errno("could not read " + filename);
75
76 while (!in.eof()) {
77 // Read record
78 string name;
79 pkginfo_t info;
80 getline(in, name);
81 getline(in, info.version);
82 for (;;) {
83 string file;
84 getline(in, file);
85
86 if (file.empty())
87 break; // End of record
88
89 info.files.insert(info.files.end(), file);
90 }
91 if (!info.files.empty())
92 packages[name] = info;
93 }
94
95 #ifndef NDEBUG
96 cerr << packages.size() << " packages found in database" << endl;
97 #endif
98 }
99
100 void pkgutil::db_commit()
101 {
102 const string dbfilename = root + PKG_DB;
103 const string dbfilename_new = dbfilename + ".incomplete_transaction";
104 const string dbfilename_bak = dbfilename + ".backup";
105
106 // Remove failed transaction (if it exists)
107 if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
108 throw runtime_error_with_errno("could not remove " + dbfilename_new);
109
110 // Write new database
111 int fd_new = creat(dbfilename_new.c_str(), 0444);
112 if (fd_new == -1)
113 throw runtime_error_with_errno("could not create " + dbfilename_new);
114
115 stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
116 ostream db_new(&filebuf_new);
117 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
118 if (!i->second.files.empty()) {
119 db_new << i->first << "\n";
120 db_new << i->second.version << "\n";
121 copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
122 db_new << "\n";
123 }
124 }
125
126 db_new.flush();
127
128 // Make sure the new database was successfully written
129 if (!db_new)
130 throw runtime_error("could not write " + dbfilename_new);
131
132 // Synchronize file to disk
133 if (fsync(fd_new) == -1)
134 throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
135
136 // Relink database backup
137 if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
138 throw runtime_error_with_errno("could not remove " + dbfilename_bak);
139 if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
140 throw runtime_error_with_errno("could not create " + dbfilename_bak);
141
142 // Move new database into place
143 if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
144 throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
145
146 #ifndef NDEBUG
147 cerr << packages.size() << " packages written to database" << endl;
148 #endif
149 }
150
151 void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
152 {
153 packages[name] = info;
154 }
155
156 bool pkgutil::db_find_pkg(const string& name)
157 {
158 return (packages.find(name) != packages.end());
159 }
160
161 void pkgutil::db_rm_pkg(const string& name)
162 {
163 set<string> files = packages[name].files;
164 packages.erase(name);
165
166 #ifndef NDEBUG
167 cerr << "Removing package phase 1 (all files in package):" << endl;
168 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
169 cerr << endl;
170 #endif
171
172 // Don't delete files that still have references
173 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
174 for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
175 files.erase(*j);
176
177 #ifndef NDEBUG
178 cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
179 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
180 cerr << endl;
181 #endif
182
183 // Delete the files
184 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
185 const string filename = root + *i;
186 if (file_exists(filename) && remove(filename.c_str()) == -1) {
187 const char* msg = strerror(errno);
188 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
189 }
190 }
191 }
192
193 void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
194 {
195 set<string> files = packages[name].files;
196 packages.erase(name);
197
198 #ifndef NDEBUG
199 cerr << "Removing package phase 1 (all files in package):" << endl;
200 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
201 cerr << endl;
202 #endif
203
204 // Don't delete files found in the keep list
205 for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
206 files.erase(*i);
207
208 #ifndef NDEBUG
209 cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
210 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
211 cerr << endl;
212 #endif
213
214 // Don't delete files that still have references
215 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
216 for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
217 files.erase(*j);
218
219 #ifndef NDEBUG
220 cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
221 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
222 cerr << endl;
223 #endif
224
225 // Delete the files
226 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
227 const string filename = root + *i;
228 if (file_exists(filename) && remove(filename.c_str()) == -1) {
229 if (errno == ENOTEMPTY)
230 continue;
231 const char* msg = strerror(errno);
232 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
233 }
234 }
235 }
236
237 void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
238 {
239 // Remove all references
240 for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
241 for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
242 i->second.files.erase(*j);
243
244 #ifndef NDEBUG
245 cerr << "Removing files:" << endl;
246 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
247 cerr << endl;
248 #endif
249
250 // Don't delete files found in the keep list
251 for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
252 files.erase(*i);
253
254 // Delete the files
255 for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
256 const string filename = root + *i;
257 if (file_exists(filename) && remove(filename.c_str()) == -1) {
258 if (errno == ENOTEMPTY)
259 continue;
260 const char* msg = strerror(errno);
261 cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
262 }
263 }
264 }
265
266 set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
267 {
268 set<string> files;
269
270 // Find conflicting files in database
271 for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
272 if (i->first != name) {
273 set_intersection(info.files.begin(), info.files.end(),
274 i->second.files.begin(), i->second.files.end(),
275 inserter(files, files.end()));
276 }
277 }
278
279 #ifndef NDEBUG
280 cerr << "Conflicts phase 1 (conflicts in database):" << endl;
281 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
282 cerr << endl;
283 #endif
284
285 // Find conflicting files in filesystem
286 for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
287 const string filename = root + *i;
288 if (file_exists(filename) && files.find(*i) == files.end())
289 files.insert(files.end(), *i);
290 }
291
292 #ifndef NDEBUG
293 cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
294 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
295 cerr << endl;
296 #endif
297
298 // Exclude directories
299 set<string> tmp = files;
300 for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
301 if ((*i)[i->length() - 1] == '/')
302 files.erase(*i);
303 }
304
305 #ifndef NDEBUG
306 cerr << "Conflicts phase 3 (directories excluded):" << endl;
307 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
308 cerr << endl;
309 #endif
310
311 // If this is an upgrade, remove files already owned by this package
312 if (packages.find(name) != packages.end()) {
313 for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
314 files.erase(*i);
315
316 #ifndef NDEBUG
317 cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
318 copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
319 cerr << endl;
320 #endif
321 }
322
323 return files;
324 }
325
326 pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
327 {
328 pair<string, pkginfo_t> result;
329 unsigned int i;
330 struct archive* archive;
331 struct archive_entry* entry;
332
333 // Extract name and version from filename
334 string basename(filename, filename.rfind('/') + 1);
335 string name(basename, 0, basename.find(VERSION_DELIM));
336 string version(basename, 0, basename.rfind(PKG_EXT));
337 version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
338
339 if (name.empty() || version.empty())
340 throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
341
342 result.first = name;
343 result.second.version = version;
344
345 archive = archive_read_new();
346 archive_read_support_compression_all(archive);
347 archive_read_support_format_all(archive);
348
349 if (archive_read_open_filename(archive,
350 const_cast<char*>(filename.c_str()),
351 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
352 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
353
354 for (i = 0; archive_read_next_header(archive, &entry) ==
355 ARCHIVE_OK; ++i) {
356
357 result.second.files.insert(result.second.files.end(),
358 archive_entry_pathname(entry));
359
360 mode_t mode = archive_entry_mode(entry);
361
362 if (S_ISREG(mode) &&
363 archive_read_data_skip(archive) != ARCHIVE_OK)
364 throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
365 }
366
367 if (i == 0) {
368 if (archive_errno(archive) == 0)
369 throw runtime_error("empty package");
370 else
371 throw runtime_error("could not read " + filename);
372 }
373
374 archive_read_finish(archive);
375
376 return result;
377 }
378
379 void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
380 {
381 struct archive* archive;
382 struct archive_entry* entry;
383 unsigned int i;
384
385 archive = archive_read_new();
386 archive_read_support_compression_all(archive);
387 archive_read_support_format_all(archive);
388
389 if (archive_read_open_filename(archive,
390 const_cast<char*>(filename.c_str()),
391 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
392 throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
393
394 chdir(root.c_str());
395
396 for (i = 0; archive_read_next_header(archive, &entry) ==
397 ARCHIVE_OK; ++i) {
398 string archive_filename = archive_entry_pathname(entry);
399 string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
400 string original_filename = trim_filename(root + string("/") + archive_filename);
401 string real_filename = original_filename;
402
403 // Check if file is filtered out via INSTALL
404 if (non_install_list.find(archive_filename) != non_install_list.end()) {
405 mode_t mode;
406
407 cout << utilname << ": ignoring " << archive_filename << endl;
408
409 mode = archive_entry_mode(entry);
410
411 if (S_ISREG(mode))
412 archive_read_data_skip(archive);
413
414 continue;
415 }
416
417 // Check if file should be rejected
418 if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
419 real_filename = trim_filename(reject_dir + string("/") + archive_filename);
420
421 archive_entry_set_pathname(entry, const_cast<char*>
422 (real_filename.c_str()));
423
424 // Extract file
425 if (archive_read_extract(archive, entry, 0) !=
426 ARCHIVE_OK) {
427 // If a file fails to install we just print an error message and
428 // continue trying to install the rest of the package.
429 const char* msg = archive_error_string(archive);
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;
437 mode_t mode = archive_entry_mode(entry);
438
439 // Directory
440 if (S_ISDIR(mode))
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) {
456 if (archive_errno(archive) == 0)
457 throw runtime_error("empty package");
458 else
459 throw runtime_error("could not read " + filename);
460 }
461
462 archive_read_finish(archive);
463 }
464
465 void 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) {
475 execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
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
486 void pkgutil::pkg_footprint(string& filename) const
487 {
488 unsigned int i;
489 struct archive* archive;
490 struct archive_entry* entry;
491
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
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)
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 int unistd_gzopen(char* pathname, int flags, mode_t mode)
702 {
703 char* gz_mode;
704
705 switch (flags & O_ACCMODE) {
706 case O_WRONLY:
707 gz_mode = "w";
708 break;
709
710 case O_RDONLY:
711 gz_mode = "r";
712 break;
713
714 case O_RDWR:
715 default:
716 errno = EINVAL;
717 return -1;
718 }
719
720 int fd;
721 gzFile gz_file;
722
723 if ((fd = open(pathname, flags, mode)) == -1)
724 return -1;
725
726 if ((flags & O_CREAT) && fchmod(fd, mode))
727 return -1;
728
729 if (!(gz_file = gzdopen(fd, gz_mode))) {
730 errno = ENOMEM;
731 return -1;
732 }
733
734 return (int)gz_file;
735 }
736
737 string trim_filename(const string& filename)
738 {
739 string search("//");
740 string result = filename;
741
742 for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
743 result.replace(pos, search.size(), "/");
744
745 return result;
746 }
747
748 bool file_exists(const string& filename)
749 {
750 struct stat buf;
751 return !lstat(filename.c_str(), &buf);
752 }
753
754 bool file_empty(const string& filename)
755 {
756 struct stat buf;
757
758 if (lstat(filename.c_str(), &buf) == -1)
759 return false;
760
761 return (S_ISREG(buf.st_mode) && buf.st_size == 0);
762 }
763
764 bool file_equal(const string& file1, const string& file2)
765 {
766 struct stat buf1, buf2;
767
768 if (lstat(file1.c_str(), &buf1) == -1)
769 return false;
770
771 if (lstat(file2.c_str(), &buf2) == -1)
772 return false;
773
774 // Regular files
775 if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
776 ifstream f1(file1.c_str());
777 ifstream f2(file2.c_str());
778
779 if (!f1 || !f2)
780 return false;
781
782 while (!f1.eof()) {
783 char buffer1[4096];
784 char buffer2[4096];
785 f1.read(buffer1, 4096);
786 f2.read(buffer2, 4096);
787 if (f1.gcount() != f2.gcount() ||
788 memcmp(buffer1, buffer2, f1.gcount()) ||
789 f1.eof() != f2.eof())
790 return false;
791 }
792
793 return true;
794 }
795 // Symlinks
796 else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
797 char symlink1[MAXPATHLEN];
798 char symlink2[MAXPATHLEN];
799
800 memset(symlink1, 0, MAXPATHLEN);
801 memset(symlink2, 0, MAXPATHLEN);
802
803 if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
804 return false;
805
806 if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
807 return false;
808
809 return !strncmp(symlink1, symlink2, MAXPATHLEN);
810 }
811 // Character devices
812 else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
813 return buf1.st_dev == buf2.st_dev;
814 }
815 // Block devices
816 else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
817 return buf1.st_dev == buf2.st_dev;
818 }
819
820 return false;
821 }
822
823 bool permissions_equal(const string& file1, const string& file2)
824 {
825 struct stat buf1;
826 struct stat buf2;
827
828 if (lstat(file1.c_str(), &buf1) == -1)
829 return false;
830
831 if (lstat(file2.c_str(), &buf2) == -1)
832 return false;
833
834 return(buf1.st_mode == buf2.st_mode) &&
835 (buf1.st_uid == buf2.st_uid) &&
836 (buf1.st_gid == buf2.st_gid);
837 }
838
839 void file_remove(const string& basedir, const string& filename)
840 {
841 if (filename != basedir && !remove(filename.c_str())) {
842 char* path = strdup(filename.c_str());
843 file_remove(basedir, dirname(path));
844 free(path);
845 }
846 }