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 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
|
/* Copyright © 2007, 2008, 2009, 2010 Jakub Wilk
* Copyright © 2009 Mateusz Turcza
*
* This package 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; version 2 dated June, 1991.
*/
#include <cassert>
#include <cerrno>
#include <cstdarg>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <fcntl.h>
#include <dirent.h>
#include <libgen.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#if WIN32
#include <climits>
#include <windows.h>
#endif
#include "system.hh"
#include "debug.hh"
#include "i18n.hh"
#if !HAVE_PSTREAMS && HAVE_FORK
#include <sys/wait.h>
#include <unistd.h>
#endif
/* constants
* =========
*/
static const char unix_path_separator = '/';
#if !WIN32
static const char path_separator = unix_path_separator;
#else
static const char path_separator = '\\';
#endif
/* class POSIXError : OSError
* ==========================
*/
std::string POSIXError::error_message(const std::string &context)
{
std::string message;
#if WIN32
/* Win32 systems tends to return POSIX-style error messages in English.
* Translation is required.
*/
N_("Operation not permitted");
N_("No such file or directory");
N_("No such process");
N_("Interrupted function call");
N_("Interrupted system call");
N_("Input/output error");
N_("No such device or address");
N_("Arg list too long");
N_("Argument list too long");
N_("Exec format error");
N_("Bad file descriptor");
N_("No child processes");
N_("Resource temporarily unavailable");
N_("Not enough space");
N_("Cannot allocate memory");
N_("Permission denied");
N_("Bad address");
N_("Resource device");
N_("Device or resource busy");
N_("File exists");
N_("Improper link");
N_("Invalid cross-device link");
N_("No such device");
N_("Not a directory");
N_("Is a directory");
N_("Invalid argument");
N_("Too many open files in system");
N_("Too many open files");
N_("Inappropriate I/O control operation");
N_("Inappropriate ioctl for device");
N_("File too large");
N_("No space left on device");
N_("Invalid seek");
N_("Illegal seek");
N_("Read-only file system");
N_("Too many links");
N_("Broken pipe");
N_("Domain error");
N_("Numerical argument out of domain");
N_("Result too large");
N_("Numerical result out of range");
N_("Resource deadlock avoided");
N_("Filename too long");
N_("File name too long");
N_("No locks available");
N_("Function not implemented");
N_("Directory not empty");
N_("Illegal byte sequence");
N_("Invalid or incomplete multibyte or wide character");
message = _(strerror(errno));
#else
/* POSIX says that ``strerror()`` returns a locale-dependent error message.
* No need to translate. */
message = strerror(errno);
#endif
if (context.length())
message = context + ": " + message;
return message;
}
static void throw_posix_error(const std::string &context)
{
switch (errno)
{
case ENOTDIR:
throw NotADirectory(context);
case ENOENT:
throw NoSuchFileOrDirectory(context);
default:
throw POSIXError(context);
}
}
static void warn_posix_error(const std::string &context)
{
try
{
throw_posix_error(context);
}
catch (const POSIXError &e)
{
error_log << string_printf(_("Warning: %s"), e.what()) << std::endl;
}
}
#if WIN32
/* class Win32Error : OSError
* ==========================
*/
class Win32Error : public OSError
{
protected:
static std::string error_message(const std::string &context);
public:
explicit Win32Error(const std::string &context)
: OSError(error_message(context))
{ };
};
std::string Win32Error::error_message(const std::string &context)
{
char *buffer;
std::string message = context + ": ";
unsigned long error_code = GetLastError();
unsigned long nbytes = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*) &buffer,
0,
NULL
);
if (nbytes == 0)
message.append(_("possibly memory allocation error"));
else
{
message.append(buffer);
LocalFree(buffer);
}
return message;
}
static void throw_win32_error(const std::string &context)
{
throw Win32Error(context);
}
#endif
/* class Command
* =============
*/
Command::Command(const std::string& command) : command(command)
{
if (this->argv.size() == 0 && path_separator != unix_path_separator)
{
/* Convert path separators: */
std::ostringstream stream;
for (std::string::const_iterator it = command.begin(); it != command.end(); it++)
{
if (*it == unix_path_separator)
stream << path_separator;
else
stream << *it;
}
this->argv.push_back(stream.str());
}
else
this->argv.push_back(command);
}
Command &Command::operator <<(const std::string& arg)
{
this->argv.push_back(arg);
return *this;
}
Command &Command::operator <<(int i)
{
std::ostringstream stream;
stream << i;
return *this << stream.str();
}
void Command::operator()(std::ostream &my_stdout, bool quiet)
{
this->call(&my_stdout, quiet);
}
void Command::operator()(bool quiet)
{
this->call(NULL, quiet);
}
#if !HAVE_PSTREAMS
static const std::string argv_to_command_line(const std::vector<std::string> &argv)
/* Translate a sequence of arguments into a command line string. */
{
std::ostringstream buffer;
#if WIN32
/* Using the same rules as the MS C runtime:
*
* 1) Arguments are delimited by white space, which is either a space or a
* tab.
*
* 2) A string surrounded by double quotation marks is interpreted as a
* single argument, regardless of white space contained within. A
* quoted string can be embedded in an argument.
*
* 3) A double quotation mark preceded by a backslash is interpreted as a
* literal double quotation mark.
*
* 4) Backslashes are interpreted literally, unless they immediately
* precede a double quotation mark.
*
* 5) If backslashes immediately precede a double quotation mark, every
* pair of backslashes is interpreted as a literal backslash. If the
* number of backslashes is odd, the last backslash escapes the next
* double quotation mark as described in rule 3.
*
* See <http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp>.
*/
for (std::vector<std::string>::const_iterator parg = argv.begin(); parg != argv.end(); parg++)
{
int backslashed = 0;
bool need_quote = parg->find_first_of(" \t") != std::string::npos;
if (need_quote)
buffer << '"';
for (std::string::const_iterator pch = parg->begin(); pch != parg->end(); pch++)
{
if (*pch == '\\')
{
backslashed++;
}
else if (*pch == '"')
{
for (int i = 0; i < backslashed; i++)
buffer << "\\\\";
backslashed = 0;
buffer << "\\\"";
}
else
{
for (int i = 0; i < backslashed; i++)
buffer << '\\';
backslashed = 0;
buffer << *pch;
}
}
for (int i = 0; i < backslashed; i++)
buffer << '\\';
if (need_quote)
buffer << '"';
buffer << ' ';
}
#else
/* Assume POSIX shell. */
for (std::vector<std::string>::const_iterator parg = argv.begin(); parg != argv.end(); parg++)
{
buffer << "'";
if (parg->find_first_of("\\\'") == std::string::npos)
buffer << *parg;
else
for (std::string::const_iterator pch = parg->begin(); pch != parg->end(); pch++)
{
if (*pch == '\\' || *pch == '\'')
buffer << "'\"\\" << *pch << "\"'";
else
buffer << *pch;
}
buffer << "' ";
}
#endif
return buffer.str();
}
#endif
#if HAVE_PSTREAMS
void Command::call(std::ostream *my_stdout, bool quiet)
{
int status;
redi::ipstream xsystem(this->command, this->argv, redi::pstream::pstdout | redi::pstream::pstderr);
if (!xsystem.rdbuf()->error())
{
if (my_stdout != NULL)
{
xsystem.out();
copy_stream(xsystem, *my_stdout, false);
}
{
xsystem.err();
copy_stream(xsystem, quiet ? dev_null : std::cerr, false);
}
xsystem.close();
}
status = xsystem.rdbuf()->status();
if (status != 0)
{
std::ostringstream message;
message
<< "system(\""
<< this->command
<< " ...\") failed";
if (WIFEXITED(status))
message << " with exit code " << WEXITSTATUS(status);
throw CommandFailed(message.str());
}
}
#elif WIN32
void Command::call(std::ostream *my_stdout, bool quiet)
{
int status = 0;
unsigned long rc;
HANDLE read_end, write_end, error_handle;
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof (SECURITY_ATTRIBUTES);
security_attributes.lpSecurityDescriptor = NULL;
security_attributes.bInheritHandle = true;
if (CreatePipe(&read_end, &write_end, &security_attributes, 0) == 0)
throw_win32_error("CreatePipe");
rc = SetHandleInformation(read_end, HANDLE_FLAG_INHERIT, 0);
if (rc == 0)
{
if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
/* Presumably it's Windows 9x, so the call is not supported.
* Punt on security and let the pipe end be inherited.
*/
}
else
throw_win32_error("SetHandleInformation");
}
if (!quiet)
{
error_handle = GetStdHandle(STD_ERROR_HANDLE);;
if (error_handle != INVALID_HANDLE_VALUE)
{
rc = DuplicateHandle(
GetCurrentProcess(), error_handle,
GetCurrentProcess(), &error_handle,
0, true, DUPLICATE_SAME_ACCESS
);
if (rc == 0)
throw_win32_error("DuplicateHandle");
}
}
else
{
error_handle = CreateFile("nul",
GENERIC_WRITE, FILE_SHARE_WRITE,
&security_attributes, OPEN_EXISTING, 0, NULL);
/* Errors can be safely ignored:
* - For the Windows NT family, INVALID_HANDLE_VALUE does actually the right thing.
* - For Windows 9x, spurious debug messages could be generated, tough luck!
*/
}
{
const std::string &command_line = argv_to_command_line(this->argv);
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof process_info);
STARTUPINFO startup_info;
memset(&startup_info, 0, sizeof startup_info);
startup_info.cb = sizeof startup_info;
startup_info.hStdOutput = write_end;
startup_info.hStdError = error_handle;
startup_info.dwFlags = STARTF_USESTDHANDLES;
char *c_command_line = strdup(command_line.c_str());
if (c_command_line == NULL)
throw_posix_error("strdup");
rc = CreateProcess(
NULL, c_command_line,
NULL, NULL,
true, 0,
NULL, NULL,
&startup_info,
&process_info
);
free(c_command_line);
if (rc == 0)
status = -1;
else
{
CloseHandle(process_info.hProcess); /* ignore errors */
CloseHandle(process_info.hThread); /* ignore errors */
if (error_handle != INVALID_HANDLE_VALUE)
CloseHandle(error_handle); /* ignore errors */
}
}
if (status == 0)
{
CloseHandle(write_end); /* ignore errors */
while (true)
{
char buffer[BUFSIZ];
unsigned long nbytes;
bool success = ReadFile(read_end, buffer, sizeof buffer, &nbytes, NULL);
if (!success)
{
status = -(GetLastError() != ERROR_BROKEN_PIPE);
break;
}
if (my_stdout != NULL)
my_stdout->write(buffer, nbytes);
}
CloseHandle(read_end); /* ignore errors */
}
if (status < 0)
{
std::ostringstream message;
message
<< "system(\""
<< this->command
<< " ...\") failed";
throw Win32Error(message.str());
}
}
#else
void Command::call(std::ostream *my_stdout, bool quiet)
{
int status;
FILE *file;
{
const std::string &command_line = argv_to_command_line(this->argv);
file = ::popen(command_line.c_str(), "r");
}
if (file != NULL)
{
char buffer[BUFSIZ];
size_t nbytes;
status = 0;
while (!feof(file))
{
nbytes = fread(buffer, 1, sizeof buffer, file);
if (ferror(file))
{
status = -1;
break;
}
if (my_stdout != NULL)
my_stdout->write(buffer, nbytes);
}
status = status || pclose(file);
}
else
status = -1;
if (status < 0)
{
std::ostringstream message;
message
<< "system(\""
<< this->command
<< " ...\") failed";
throw_posix_error(message.str());
}
}
#endif
#if WIN32
class FilterWriterData
{
public:
HANDLE handle;
const std::string &string;
FilterWriterData(HANDLE handle, const std::string &string)
: handle(handle),
string(string)
{ }
};
unsigned long WINAPI filter_writer(void *data_)
{
bool success;
FilterWriterData *data = reinterpret_cast<FilterWriterData*>(data_);
success = WriteFile(data->handle, data->string.c_str(), data->string.length(), NULL, NULL);
if (!success)
throw_win32_error("WriteFile");
success = CloseHandle(data->handle);
if (!success)
throw_win32_error("CloseHandle");
return 0;
}
std::string Command::filter(const std::string &command_line, const std::string string)
{
int status = 0;
unsigned long rc;
HANDLE stdin_read, stdin_write, stdout_read, stdout_write, error_handle;
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof (SECURITY_ATTRIBUTES);
security_attributes.lpSecurityDescriptor = NULL;
security_attributes.bInheritHandle = true;
if (CreatePipe(&stdin_read, &stdin_write, &security_attributes, 0) == 0)
throw_win32_error("CreatePipe");
if (CreatePipe(&stdout_read, &stdout_write, &security_attributes, 0) == 0)
throw_win32_error("CreatePipe");
rc =
SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0) &&
SetHandleInformation(stdin_write, HANDLE_FLAG_INHERIT, 0);
if (rc == 0)
{
if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
/* Presumably it's Windows 9x, so the call is not supported.
* Punt on security and let the pipe end be inherited.
*/
}
else
throw_win32_error("SetHandleInformation");
}
error_handle = GetStdHandle(STD_ERROR_HANDLE);;
if (error_handle != INVALID_HANDLE_VALUE)
{
rc = DuplicateHandle(
GetCurrentProcess(), error_handle,
GetCurrentProcess(), &error_handle,
0, true, DUPLICATE_SAME_ACCESS
);
if (rc == 0)
throw_win32_error("DuplicateHandle");
}
{
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof process_info);
STARTUPINFO startup_info;
memset(&startup_info, 0, sizeof startup_info);
startup_info.cb = sizeof startup_info;
startup_info.hStdInput = stdin_read;
startup_info.hStdOutput = stdout_write;
startup_info.hStdError = error_handle;
startup_info.dwFlags = STARTF_USESTDHANDLES;
char *c_command_line = strdup(command_line.c_str());
if (c_command_line == NULL)
throw_posix_error("strdup");
rc = CreateProcess(
NULL, c_command_line,
NULL, NULL,
true, 0,
NULL, NULL,
&startup_info,
&process_info
);
free(c_command_line);
if (rc == 0)
status = -1;
else
{
CloseHandle(process_info.hProcess); /* ignore errors */
CloseHandle(process_info.hThread); /* ignore errors */
if (error_handle != INVALID_HANDLE_VALUE)
CloseHandle(error_handle); /* ignore errors */
}
}
if (status == 0)
{
std::ostringstream stream;
CloseHandle(stdin_read); /* ignore errors */
CloseHandle(stdout_write); /* ignore errors */
FilterWriterData writer_data(stdin_write, string);
HANDLE thread_handle = CreateThread(NULL, 0, filter_writer, &writer_data, 0, NULL);
if (thread_handle == NULL)
throw_win32_error("CreateThread");
while (true)
{
char buffer[BUFSIZ];
unsigned long nbytes;
bool success = ReadFile(stdout_read, buffer, sizeof buffer, &nbytes, NULL);
if (!success)
{
status = -(GetLastError() != ERROR_BROKEN_PIPE);
break;
}
stream.write(buffer, nbytes);
}
CloseHandle(stdout_read); /* ignore errors */
rc = WaitForSingleObject(thread_handle, INFINITE);
if (rc == WAIT_FAILED)
throw_win32_error("WaitForSingleObject");
CloseHandle(thread_handle); /* ignore errors */
return stream.str();
}
if (status < 0)
{
std::ostringstream message;
message
<< "system(\""
<< command_line
<< "\") failed";
throw Win32Error(message.str());
}
return string; /* Should not really happen. */
}
#elif HAVE_FORK
std::string Command::filter(const std::string &command_line, const std::string string)
{
int rc;
int pipe_fds[2];
rc = pipe(pipe_fds);
if (rc != 0)
throw_posix_error("pipe");
pid_t writer_pid = fork();
if (writer_pid == -1)
throw_posix_error("fork");
else if (writer_pid == 0)
{
/* Writer: */
close(pipe_fds[0]); /* Deliberately ignore errors. */
rc = dup2(pipe_fds[1], STDOUT_FILENO);
if (rc == -1)
throw_posix_error("dup2");
FILE *fp = popen(command_line.c_str(), "w");
if (fp == NULL)
throw_posix_error("popen");
if (fputs(string.c_str(), fp) == EOF)
throw_posix_error("fputs");
rc = pclose(fp);
if (rc != 0)
throw_posix_error("pclose");
exit(0);
}
else
{
/* Main process: */
close(pipe_fds[1]); /* Deliberately ignore errors. */
std::ostringstream stream;
while (1)
{
char buffer[BUFSIZ];
size_t n = read(pipe_fds[0], buffer, sizeof buffer);
if (n < 0)
throw_posix_error("read");
else if (n == 0)
break;
else
stream.write(buffer, n);
}
int status;
writer_pid = wait(&status);
if (writer_pid == static_cast<pid_t>(-1))
throw_posix_error("wait");
if (status != 0)
{
std::ostringstream message;
message
<< "system(\""
<< command_line
<< "\") failed";
if (WIFEXITED(status))
message << " with exit code " << WEXITSTATUS(status);
throw CommandFailed(message.str());
}
return stream.str();
}
return string; /* Should not really happen. */
}
#else
std::string Command::filter(const std::string &command_line, const std::string string)
{
/* Should not really happen. */
errno = ENOSYS;
throw_posix_error("fork");
}
#endif
/* class Directory
* ===============
*/
Directory::Directory(const std::string &name)
: name(name), posix_dir(NULL)
{
this->open(name.c_str());
}
Directory::~Directory() throw ()
{
this->close();
}
void Directory::open(const char* path)
{
this->posix_dir = opendir(path);
if (this->posix_dir == NULL)
throw_posix_error(path);
}
void Directory::close(void)
{
if (this->posix_dir == NULL)
return;
if (closedir(static_cast<DIR*>(this->posix_dir)) != 0)
throw_posix_error(this->name);
}
/* class Array<tp>
* ===============
*/
template <typename tp>
class Array
{
private:
Array(const Array &); // not defined
Array& operator=(const Array &); // not defined
protected:
tp *buffer;
public:
explicit Array(size_t size)
{
buffer = new tp[size];
}
operator tp * ()
{
return this->buffer;
}
~Array() throw ()
{
delete[] this->buffer;
}
};
/* class TemporaryPathTemplate : Array<char>
* =========================================
*/
class TemporaryPathTemplate : public Array<char>
{
protected:
static const char *temporary_directory()
{
const char *result = getenv("TMPDIR");
if (result == NULL)
result = P_tmpdir;
return result;
}
public:
TemporaryPathTemplate()
: Array<char>(strlen(this->temporary_directory()) + strlen(PACKAGE_NAME) + 9)
{
sprintf(*this, "%s%c%s.XXXXXX", this->temporary_directory(), path_separator, PACKAGE_NAME);
}
};
/* class TemporaryDirectory : Directory
* ====================================
*/
TemporaryDirectory::TemporaryDirectory() : Directory()
{
#if !WIN32
TemporaryPathTemplate path_buffer;
if (mkdtemp(path_buffer) == NULL)
throw_posix_error(static_cast<char*>(path_buffer));
#else
char base_path_buffer[PATH_MAX];
char path_buffer[PATH_MAX];
if (GetTempPath(PATH_MAX, base_path_buffer) == 0)
throw_win32_error("GetTempPath");
if (GetTempFileName(base_path_buffer, PACKAGE_NAME, 0, path_buffer) == 0)
throw_win32_error("GetTempFileName");
if (unlink(path_buffer) < 0)
throw_posix_error(path_buffer);
if (mkdir(path_buffer) < 0)
throw_posix_error(path_buffer);
#endif
this->name += path_buffer;
}
TemporaryDirectory::~TemporaryDirectory() throw ()
{
if (rmdir(this->name.c_str()) == -1)
warn_posix_error(this->name);
}
/* class File : std::fstream
* =========================
*/
void File::open(const char* path, bool truncate)
{
std::fstream::openmode mode = std::fstream::in | std::fstream::out | std::fstream::binary;
if (truncate)
mode |= std::fstream::trunc;
this->exceptions(std::ifstream::failbit | std::ifstream::badbit);
if (path == NULL)
this->std::fstream::open(this->name.c_str(), mode);
else
{
this->name = path;
this->std::fstream::open(path, mode);
}
this->exceptions(std::ifstream::badbit);
}
File::File(const std::string &name)
{
this->open(name.c_str());
}
File::File(const Directory& directory, const std::string &name)
{
std::ostringstream stream;
this->base_name = name;
stream << directory << path_separator << name;
this->open(stream.str().c_str());
}
size_t File::size()
{
this->seekg(0, std::ios::end);
return this->tellg();
}
void File::reopen(bool truncate)
{
if (this->is_open())
this->close();
this->open(NULL, truncate);
}
const std::string& File::get_basename() const
{
return this->base_name;
}
File::operator const std::string& () const
{
return this->name;
}
std::ostream &operator<<(std::ostream &out, const Directory &directory)
{
return out << directory.name;
}
std::ostream &operator<<(std::ostream &out, const File &file)
{
return out << file.name;
}
/* class TemporaryFile : File
* ==========================
*/
void TemporaryFile::construct()
{
#if !WIN32
TemporaryPathTemplate path_buffer;
int fd = mkstemp(path_buffer);
if (fd == -1)
throw_posix_error(static_cast<char*>(path_buffer));
if (::close(fd) == -1)
throw_posix_error(static_cast<char*>(path_buffer));
#else
char base_path_buffer[PATH_MAX];
char path_buffer[PATH_MAX];
if (GetTempPath(PATH_MAX, base_path_buffer) == 0)
throw_win32_error("GetTempPath");
if (GetTempFileName(base_path_buffer, PACKAGE_NAME, 0, path_buffer) == 0)
throw_win32_error("GetTempFileName");
HANDLE handle = CreateFile(path_buffer, 0, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
if (handle == 0)
throw_win32_error("CreateFile");
CloseHandle(handle); /* ignore errors */
#endif
this->open(path_buffer);
}
TemporaryFile::TemporaryFile()
{
this->construct();
}
TemporaryFile::~TemporaryFile() throw ()
{
if (this->is_open())
this->close();
if (unlink(this->name.c_str()) == -1)
warn_posix_error(this->name);
}
/* class ExistingFile : File
* =========================
*/
ExistingFile::ExistingFile(const std::string &name)
: File()
{
this->name = name;
this->open(NULL, false);
}
ExistingFile::ExistingFile(const Directory& directory, const std::string &name)
: File()
{
std::ostringstream stream;
stream << directory << "/" << name;
this->name = stream.str();
this->open(NULL, false);
}
#if WIN32
/* class Cwd
* =========
*/
Cwd::Cwd(const std::string &path)
{
int rc;
size_t size = 32;
while (1)
{
Array<char> buffer(size);
rc = getcwd(buffer, size) == NULL;
if (rc != 0)
{
if (errno == ERANGE && size < std::numeric_limits<size_t>::max() / 2)
{
size *= 2;
continue;
}
throw_posix_error("getcwd");
}
this->previous_cwd = buffer;
break;
}
rc = chdir(path.c_str());
if (rc != 0)
throw_posix_error("chdir");
}
Cwd::~Cwd()
{
if (this->previous_cwd.length())
{
int rc = chdir(this->previous_cwd.c_str());
if (rc != 0)
{
warn_posix_error("chdir");
abort();
}
}
}
#endif
/* utility functions
* =================
*/
namespace encoding
{
#if WIN32
/* The native encoding (so called ANSI character set) can differ from the
* terminal encoding (typically: so called OEM charset).
*/
template <>
std::ostream &operator <<(std::ostream &stream, const proxy<native, terminal> &converter)
{
int rc;
const std::string &string = converter.string;
size_t length = converter.string.length();
Array<char> buffer(length);
string.copy(buffer, length);
rc = CharToOemBuff(buffer, buffer, length);
if (rc == 0)
{
/* This should actually never happen. */
throw_win32_error("CharToOemBuff");
}
stream.write(buffer, length);
return stream;
}
#else
template <>
std::ostream &operator <<(std::ostream &stream, const proxy<native, terminal> &converter)
{
stream << converter.string;
return stream;
}
#endif
template <>
std::ostream &operator <<(std::ostream &stream, const proxy<native, utf8> &converter)
{
/* The following code assumes that wchar_t strings are UTF-32 or UTF-16.
* This is not necessarily the case for every system.
*
* See
* http://unicode.org/faq/utf_bom.html
* for description of both UTF-16 and UTF-8.
*/
const std::string &string = converter.string;
size_t length = string.length();
Array<wchar_t> wstring(length + 1);
length = mbstowcs(wstring, string.c_str(), length + 1);
if (length == static_cast<size_t>(-1))
throw_posix_error("mbstowcs");
uint32_t code, code_shift = 0;
for (size_t i = 0; i < length; i++)
{
code = wstring[i];
if (code_shift)
{
/* A leading surrogate has been encountered. */
if (code >= 0xdc00 && code < 0xe000)
{
/* A trailing surrogate is encountered. */
code = code_shift + (code & 0x3ff);
}
else
{
/* An unpaired surrogate is encountered. */
errno = EILSEQ;
throw_posix_error(__FUNCTION__);
}
code_shift = 0;
}
else if (code >= 0xd800 && code < 0xdc00)
{
/* A leading surrogate is encountered. */
code_shift = 0x10000 + ((code & 0x3ff) << 10);
continue;
}
if (code >= 0x110000 || (code & 0xfffe) == 0xfffe)
{
/* Code is out of range or a non-character is encountered. */
errno = EILSEQ;
throw_posix_error(__FUNCTION__);
}
if (code < 0x80)
{
char ascii = code;
stream << ascii;
}
else
{
char buffer[4];
size_t nbytes;
for (nbytes = 2; nbytes < 4; nbytes++)
if (code < (1U << (5 * nbytes + 1)))
break;
buffer[0] = (0xff00 >> nbytes) & 0xff;
for (size_t i = nbytes - 1; i; i--)
{
buffer[i] = 0x80 | (code & 0x3f);
code >>= 6;
}
buffer[0] |= code;
stream.write(buffer, nbytes);
}
}
return stream;
}
}
void copy_stream(std::istream &istream, std::ostream &ostream, bool seek)
{
if (seek)
istream.seekg(0, std::ios::beg);
char buffer[BUFSIZ];
while (!istream.eof())
{
istream.read(buffer, sizeof buffer);
ostream.write(buffer, istream.gcount());
}
}
void copy_stream(std::istream &istream, std::ostream &ostream, bool seek, std::streamsize limit)
{
if (seek)
istream.seekg(0, std::ios::beg);
char buffer[BUFSIZ];
while (!istream.eof() && limit > 0)
{
std::streamsize chunk_size = std::min(static_cast<std::streamsize>(sizeof buffer), limit);
istream.read(buffer, chunk_size);
ostream.write(buffer, istream.gcount());
limit -= chunk_size;
}
}
bool is_stream_a_tty(const std::ostream &ostream)
{
if (&ostream == &std::cout)
return isatty(STDOUT_FILENO);
else
{
/* Not implemented for streams other that ``std::cout``.
* See http://www.ginac.de/~kreckel/fileno/ for a more general
* (although unportable, GCC-specific) solution.
*/
throw std::invalid_argument("is_a_tty(const std::ostream &)");
}
}
void split_path(const std::string &path, std::string &directory_name, std::string &file_name)
{
/* POSIX-compliant ``basename()`` and ``dirname()`` would split ``/foo/bar/``
* into ``/foo`` and ``"bar"``, instead of desired ``"foo/bar"`` and an empty
* string. To deal with this weirdness, a trailing ``!`` character is
* appended to the splitted path.
*/
{
Array<char> buffer(path.length() + 2);
sprintf(buffer, "%s!", path.c_str());
directory_name = ::dirname(buffer);
}
{
Array<char> buffer(path.length() + 2);
sprintf(buffer, "%s!", path.c_str());
file_name = ::basename(buffer);
size_t length = file_name.length();
assert(length > 0);
assert(file_name[length - 1] == '!');
file_name.erase(length - 1);
}
}
std::string absolute_path(const std::string &path, const std::string &dir_name)
{
if (path.length() == 0)
return path;
if (path[0] != '.')
return path;
if (path.length() == 1 || (path.length() >= 2 && (path[1] == unix_path_separator || path[1] == path_separator)))
return dir_name + path_separator + path.substr(std::min(static_cast<size_t>(2), path.length()));
assert(path.length() >= 2);
if (path[1] != '.')
return path;
if (path.length() == 2 || (path.length() >= 3 && (path[2] == unix_path_separator || path[2] == path_separator)))
return dir_name + path_separator + path;
return path;
}
#if defined(va_copy)
#elif defined(__va_copy)
#define va_copy __va_copy
#else
#define va_copy(dest, src) memcpy((dest), (src), sizeof (va_list))
#endif
std::string string_vprintf(const char *message, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int length = vsnprintf(NULL, 0, message, args_copy);
va_end(args_copy);
assert(length >= 0);
if (length < 0)
throw_posix_error("vsnprintf");
Array<char> buffer(length + 1);
length = vsprintf(buffer, message, args);
assert(length >= 0);
if (length < 0)
throw_posix_error("vsprintf");
return static_cast<char*>(buffer);
}
void prevent_pop_out(void)
{
#if WIN32
/* GetConsoleProcessList() function is not available for some systems (e.g.,
* Wine, Windows 98), so it's not desireable to import it at link time.
*/
typedef DWORD (WINAPI *get_console_process_list_fn)(LPDWORD, DWORD);
get_console_process_list_fn get_console_process_list;
HMODULE dll = GetModuleHandle("kernel32");
if (dll == NULL)
return;
get_console_process_list = (get_console_process_list_fn) GetProcAddress(dll, "GetConsoleProcessList");
if (get_console_process_list != NULL)
{
unsigned long pid, rc;
rc = get_console_process_list(&pid, 1);
if (rc == 1)
MessageBox(NULL, _("pdf2djvu is intended to be run from the command prompt."), PACKAGE_NAME, MB_OK | MB_ICONINFORMATION);
}
#endif
}
std::string string_printf(const char *message, ...)
{
va_list args;
va_start(args, message);
std::string result = string_vprintf(message, args);
va_end(args);
return result;
}
// vim:ts=2 sw=2 et
|