--- a/configure.in +++ b/configure.in @@ -310,7 +310,7 @@ AC_ARG_ENABLE(kernelbuild, AC_HELP_STRING(--enable-kernel-build=x,Set the target kernel build path), [ - if test -e $enableval/include/linux/autoconf.h; then + if test -e $enableval/include/linux/autoconf.h -o -e $enableval/include/generated/autoconf.h; then AC_SUBST([KERNEL_BUILD_PATH],[$enableval]) else AC_MSG_ERROR([The kernel build directory is not valid or not configured!]) @@ -333,12 +333,12 @@ echo Set the lib_ifxos include path $enableval AC_SUBST([IFXOS_INCLUDE_PATH],[$enableval]) else - echo -e Set the default lib_ifxos include path $DEFAULT_IFXOS_INCLUDE_PATH + echo Set the default lib_ifxos include path $DEFAULT_IFXOS_INCLUDE_PATH AC_SUBST([IFXOS_INCLUDE_PATH],[$DEFAULT_IFXOS_INCLUDE_PATH]) fi ], [ - echo -e Set the default lib_ifxos include path $DEFAULT_IFXOS_INCLUDE_PATH + echo Set the default lib_ifxos include path $DEFAULT_IFXOS_INCLUDE_PATH AC_SUBST([IFXOS_INCLUDE_PATH],[$DEFAULT_IFXOS_INCLUDE_PATH]) ] ) @@ -1702,73 +1702,73 @@ AC_SUBST([DISTCHECK_CONFIGURE_PARAMS],[$CONFIGURE_OPTIONS]) AC_CONFIG_COMMANDS_PRE([ -echo -e "------------------------------------------------------------------------" -echo -e " Configuration for drv_dsl_cpe_api:" -echo -e " Configure model type: $DSL_CONFIG_MODEL_TYPE" -echo -e " Source code location: $srcdir" -echo -e " Compiler: $CC" -echo -e " Compiler c-flags: $CFLAGS" -echo -e " Extra compiler c-flags: $EXTRA_DRV_CFLAGS" -echo -e " Host System Type: $host" -echo -e " Install path: $prefix" -echo -e " Linux kernel include path: $KERNEL_INCL_PATH" -echo -e " Linux kernel build path: $KERNEL_BUILD_PATH" -echo -e " Linux kernel architecture: $KERNEL_ARCH" -echo -e " Include IFXOS: $INCLUDE_DSL_CPE_API_IFXOS_SUPPORT" -echo -e " IFXOS include path: $IFXOS_INCLUDE_PATH" -echo -e " Driver Include Path $DSL_DRIVER_INCL_PATH" -echo -e " DSL device: $DSL_DEVICE_NAME" -echo -e " Max device number: $DSL_DRV_MAX_DEVICE_NUMBER" -echo -e " Channels per line: $DSL_CHANNELS_PER_LINE" -echo -e " Build lib (only for kernel 2.6) $DSL_CPE_API_LIBRARY_BUILD_2_6" -echo -e " DSL data led flash frequency: $DSL_DATA_LED_FLASH_FREQUENCY Hz" -echo -e " Disable debug prints: $DSL_DEBUG_DISABLE" -echo -e " Preselection of max. debug level: $DSL_DBG_MAX_LEVEL_SET" -echo -e " Preselected max. debug level: $DSL_DBG_MAX_LEVEL_PRE" -echo -e " Include deprecated functions: $INCLUDE_DEPRECATED" -echo -e " Include Device Exception Codes: $INCLUDE_DEVICE_EXCEPTION_CODES" -echo -e " Include FW request support: $INCLUDE_FW_REQUEST_SUPPORT" -echo -e " Include ADSL trace buffer: $INCLUDE_DSL_CPE_TRACE_BUFFER" -echo -e " Include ADSL MIB: $INCLUDE_DSL_ADSL_MIB" -echo -e " Include ADSL LED: $INCLUDE_ADSL_LED" -echo -e " Include CEOC: $INCLUDE_DSL_CEOC" -echo -e " Include config get support: $INCLUDE_DSL_CONFIG_GET" -echo -e " Include System i/f configuration: $INCLUDE_DSL_SYSTEM_INTERFACE" -echo -e " Include Resource Statistics: $INCLUDE_DSL_RESOURCE_STATISTICS" -echo -e " Include Framing Parameters: $INCLUDE_DSL_FRAMING_PARAMETERS" -echo -e " Include G997 Line Inventory: $INCLUDE_DSL_G997_LINE_INVENTORY" -echo -e " Include G997 Framing Parameters: $INCLUDE_DSL_G997_FRAMING_PARAMETERS" -echo -e " Include G997 per tone data: $INCLUDE_DSL_G997_PER_TONE" -echo -e " Include G997 status: $INCLUDE_DSL_G997_STATUS" -echo -e " Include G997 alarm: $INCLUDE_DSL_G997_ALARM" -echo -e " Include DSL Bonding: $INCLUDE_DSL_BONDING" -echo -e " Include Misc Line Status $INCLUDE_DSL_CPE_MISC_LINE_STATUS" -echo -e " Include DELT: $INCLUDE_DSL_DELT" -echo -e " Include DELT data static storage: $DSL_CPE_STATIC_DELT_DATA" -echo -e " Include PM: $INCLUDE_DSL_PM" -echo -e " Include PM config: $INCLUDE_DSL_CPE_PM_CONFIG" -echo -e " Include PM total: $INCLUDE_DSL_CPE_PM_TOTAL_COUNTERS" -echo -e " Include PM history: $INCLUDE_DSL_CPE_PM_HISTORY" -echo -e " Include PM showtime: $INCLUDE_DSL_CPE_PM_SHOWTIME_COUNTERS" -echo -e " Include PM optional: $INCLUDE_DSL_CPE_PM_OPTIONAL_PARAMETERS" -echo -e " Include PM line: $INCLUDE_DSL_CPE_PM_LINE_COUNTERS" -echo -e " Include PM line event showtime: $INCLUDE_DSL_CPE_PM_LINE_EVENT_SHOWTIME_COUNTERS" -echo -e " Include PM channel: $INCLUDE_DSL_CPE_PM_CHANNEL_COUNTERS" -echo -e " Include PM channel extended: $INCLUDE_DSL_CPE_PM_CHANNEL_EXT_COUNTERS" -echo -e " Include PM data path: $INCLUDE_DSL_CPE_PM_DATA_PATH_COUNTERS" -echo -e " Include PM data path failure: $INCLUDE_DSL_CPE_PM_DATA_PATH_FAILURE_COUNTERS" -echo -e " Include PM ReTx: $INCLUDE_DSL_CPE_PM_RETX_COUNTERS" -echo -e " Include PM line threshold: $INCLUDE_DSL_CPE_PM_LINE_THRESHOLDS" -echo -e " Include PM channel threshold: $INCLUDE_DSL_CPE_PM_CHANNEL_THRESHOLDS" -echo -e " Include PM data path threshold: $INCLUDE_DSL_CPE_PM_DATA_PATH_THRESHOLDS" -echo -e " Include PM ReTx threshold: $INCLUDE_DSL_CPE_PM_RETX_THRESHOLDS" -echo -e " Include FW memory free support: $INCLUDE_DSL_FIRMWARE_MEMORY_FREE" -echo -e "----------------------- deprectated ! ----------------------------------" -echo -e " Include PM line failure: $INCLUDE_DSL_CPE_PM_LINE_FAILURE_COUNTERS" -echo -e "" -echo -e " Settings:" -echo -e " Configure options: $CONFIGURE_OPTIONS" -echo -e "------------------------------------------------------------------------" +echo "------------------------------------------------------------------------" +echo " Configuration for drv_dsl_cpe_api:" +echo " Configure model type: $DSL_CONFIG_MODEL_TYPE" +echo " Source code location: $srcdir" +echo " Compiler: $CC" +echo " Compiler c-flags: $CFLAGS" +echo " Extra compiler c-flags: $EXTRA_DRV_CFLAGS" +echo " Host System Type: $host" +echo " Install path: $prefix" +echo " Linux kernel include path: $KERNEL_INCL_PATH" +echo " Linux kernel build path: $KERNEL_BUILD_PATH" +echo " Linux kernel architecture: $KERNEL_ARCH" +echo " Include IFXOS: $INCLUDE_DSL_CPE_API_IFXOS_SUPPORT" +echo " IFXOS include path: $IFXOS_INCLUDE_PATH" +echo " Driver Include Path $DSL_DRIVER_INCL_PATH" +echo " DSL device: $DSL_DEVICE_NAME" +echo " Max device number: $DSL_DRV_MAX_DEVICE_NUMBER" +echo " Channels per line: $DSL_CHANNELS_PER_LINE" +echo " Build lib (only for kernel 2.6) $DSL_CPE_API_LIBRARY_BUILD_2_6" +echo " DSL data led flash frequency: $DSL_DATA_LED_FLASH_FREQUENCY Hz" +echo " Disable debug prints: $DSL_DEBUG_DISABLE" +echo " Preselection of max. debug level: $DSL_DBG_MAX_LEVEL_SET" +echo " Preselected max. debug level: $DSL_DBG_MAX_LEVEL_PRE" +echo " Include deprecated functions: $INCLUDE_DEPRECATED" +echo " Include Device Exception Codes: $INCLUDE_DEVICE_EXCEPTION_CODES" +echo " Include FW request support: $INCLUDE_FW_REQUEST_SUPPORT" +echo " Include ADSL trace buffer: $INCLUDE_DSL_CPE_TRACE_BUFFER" +echo " Include ADSL MIB: $INCLUDE_DSL_ADSL_MIB" +echo " Include ADSL LED: $INCLUDE_ADSL_LED" +echo " Include CEOC: $INCLUDE_DSL_CEOC" +echo " Include config get support: $INCLUDE_DSL_CONFIG_GET" +echo " Include System i/f configuration: $INCLUDE_DSL_SYSTEM_INTERFACE" +echo " Include Resource Statistics: $INCLUDE_DSL_RESOURCE_STATISTICS" +echo " Include Framing Parameters: $INCLUDE_DSL_FRAMING_PARAMETERS" +echo " Include G997 Line Inventory: $INCLUDE_DSL_G997_LINE_INVENTORY" +echo " Include G997 Framing Parameters: $INCLUDE_DSL_G997_FRAMING_PARAMETERS" +echo " Include G997 per tone data: $INCLUDE_DSL_G997_PER_TONE" +echo " Include G997 status: $INCLUDE_DSL_G997_STATUS" +echo " Include G997 alarm: $INCLUDE_DSL_G997_ALARM" +echo " Include DSL Bonding: $INCLUDE_DSL_BONDING" +echo " Include Misc Line Status $INCLUDE_DSL_CPE_MISC_LINE_STATUS" +echo " Include DELT: $INCLUDE_DSL_DELT" +echo " Include DELT data static storage: $DSL_CPE_STATIC_DELT_DATA" +echo " Include PM: $INCLUDE_DSL_PM" +echo " Include PM config: $INCLUDE_DSL_CPE_PM_CONFIG" +echo " Include PM total: $INCLUDE_DSL_CPE_PM_TOTAL_COUNTERS" +echo " Include PM history: $INCLUDE_DSL_CPE_PM_HISTORY" +echo " Include PM showtime: $INCLUDE_DSL_CPE_PM_SHOWTIME_COUNTERS" +echo " Include PM optional: $INCLUDE_DSL_CPE_PM_OPTIONAL_PARAMETERS" +echo " Include PM line: $INCLUDE_DSL_CPE_PM_LINE_COUNTERS" +echo " Include PM line event showtime: $INCLUDE_DSL_CPE_PM_LINE_EVENT_SHOWTIME_COUNTERS" +echo " Include PM channel: $INCLUDE_DSL_CPE_PM_CHANNEL_COUNTERS" +echo " Include PM channel extended: $INCLUDE_DSL_CPE_PM_CHANNEL_EXT_COUNTERS" +echo " Include PM data path: $INCLUDE_DSL_CPE_PM_DATA_PATH_COUNTERS" +echo " Include PM data path failure: $INCLUDE_DSL_CPE_PM_DATA_PATH_FAILURE_COUNTERS" +echo " Include PM ReTx: $INCLUDE_DSL_CPE_PM_RETX_COUNTERS" +echo " Include PM line threshold: $INCLUDE_DSL_CPE_PM_LINE_THRESHOLDS" +echo " Include PM channel threshold: $INCLUDE_DSL_CPE_PM_CHANNEL_THRESHOLDS" +echo " Include PM data path threshold: $INCLUDE_DSL_CPE_PM_DATA_PATH_THRESHOLDS" +echo " Include PM ReTx threshold: $INCLUDE_DSL_CPE_PM_RETX_THRESHOLDS" +echo " Include FW memory free support: $INCLUDE_DSL_FIRMWARE_MEMORY_FREE" +echo "----------------------- deprectated ! ----------------------------------" +echo " Include PM line failure: $INCLUDE_DSL_CPE_PM_LINE_FAILURE_COUNTERS" +echo "" +echo " Settings:" +echo " Configure options: $CONFIGURE_OPTIONS" +echo "------------------------------------------------------------------------" ]) AC_CONFIG_FILES([Makefile src/Makefile]) --- a/src/Makefile.am +++ b/src/Makefile.am @@ -303,7 +303,7 @@ drv_dsl_cpe_api_OBJS = "$(subst .c,.o,$(filter %.c,$(drv_dsl_cpe_api_SOURCES)))" drv_dsl_cpe_api.ko: $(drv_dsl_cpe_api_SOURCES) - @echo -e "drv_dsl_cpe_api: Making Linux 2.6.x kernel object" + @echo "drv_dsl_cpe_api: Making Linux 2.6.x kernel object" if test ! -e common/drv_dsl_cpe_api.c ; then \ echo "copy source files (as links only!)"; \ for f in $(filter %.c,$(drv_dsl_cpe_api_SOURCES)); do \ @@ -311,10 +311,10 @@ cp -s $(addprefix @abs_srcdir@/,$$f) $(PWD)/`dirname $$f`/ ; \ done \ fi - @echo -e "# drv_dsl_cpe_api: Generated to build Linux 2.6.x kernel object" > $(PWD)/Kbuild - @echo -e "obj-m := $(subst .ko,.o,$@)" >> $(PWD)/Kbuild - @echo -e "$(subst .ko,,$@)-y := $(drv_dsl_cpe_api_OBJS)" >> $(PWD)/Kbuild - @echo -e "EXTRA_CFLAGS := $(CFLAGS) -DHAVE_CONFIG_H $(drv_dsl_cpe_api_CFLAGS) $(DSL_DRIVER_INCL_PATH) $(IFXOS_INCLUDE_PATH) -I@abs_srcdir@/include -I$(PWD)/include" >> $(PWD)/Kbuild + @echo "# drv_dsl_cpe_api: Generated to build Linux 2.6.x kernel object" > $(PWD)/Kbuild + @echo "obj-m := $(subst .ko,.o,$@)" >> $(PWD)/Kbuild + @echo "$(subst .ko,,$@)-y := $(drv_dsl_cpe_api_OBJS)" >> $(PWD)/Kbuild + @echo "EXTRA_CFLAGS := $(CFLAGS) -DHAVE_CONFIG_H $(drv_dsl_cpe_api_CFLAGS) $(DSL_DRIVER_INCL_PATH) $(IFXOS_INCLUDE_PATH) -I@abs_srcdir@/include -I$(PWD)/include" >> $(PWD)/Kbuild $(MAKE) ARCH=@KERNEL_ARCH@ -C @KERNEL_BUILD_PATH@ O=@KERNEL_BUILD_PATH@ M=$(PWD) modules clean-generic: --- a/src/include/drv_dsl_cpe_os_linux.h +++ b/src/include/drv_dsl_cpe_os_linux.h @@ -16,8 +16,6 @@ extern "C" { #endif -#include -#include #include #include #include @@ -26,8 +24,10 @@ #include #include -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) - #include +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,33)) +#include +#else +#include #endif #include @@ -39,7 +39,8 @@ #include #include #include -#include +//#include +#include #ifdef INCLUDE_DSL_CPE_API_IFXOS_SUPPORT /** IFXOS includes*/ 9 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
/*
 * Copyright (C) 2012-2014 Dominik Schürmann <dominik@dominikschuermann.de>
 * Copyright (C) 2010-2014 Thialfihar <thi@thialfihar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.sufficientlysecure.keychain.pgp;

import android.content.Context;
import android.support.annotation.NonNull;
import android.webkit.MimeTypeMap;

import org.openintents.openpgp.OpenPgpDecryptionResult;
import org.openintents.openpgp.OpenPgpMetadata;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.spongycastle.bcpg.ArmoredInputStream;
import org.spongycastle.openpgp.PGPCompressedData;
import org.spongycastle.openpgp.PGPDataValidationException;
import org.spongycastle.openpgp.PGPEncryptedData;
import org.spongycastle.openpgp.PGPEncryptedDataList;
import org.spongycastle.openpgp.PGPException;
import org.spongycastle.openpgp.PGPKeyValidationException;
import org.spongycastle.openpgp.PGPLiteralData;
import org.spongycastle.openpgp.PGPOnePassSignature;
import org.spongycastle.openpgp.PGPOnePassSignatureList;
import org.spongycastle.openpgp.PGPPBEEncryptedData;
import org.spongycastle.openpgp.PGPPublicKeyEncryptedData;
import org.spongycastle.openpgp.PGPSignature;
import org.spongycastle.openpgp.PGPSignatureList;
import org.spongycastle.openpgp.PGPUtil;
import org.spongycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.spongycastle.openpgp.operator.PBEDataDecryptorFactory;
import org.spongycastle.openpgp.operator.PGPDigestCalculatorProvider;
import org.spongycastle.openpgp.operator.jcajce.CachingDataDecryptorFactory;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder;
import org.spongycastle.util.encoders.DecoderException;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Constants.key;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.operations.BaseOperation;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.operations.results.DecryptVerifyResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogType;
import org.sufficientlysecure.keychain.operations.results.OperationResult.OperationLog;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.util.FileHelper;
import org.sufficientlysecure.keychain.util.InputData;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.Passphrase;
import org.sufficientlysecure.keychain.util.ProgressScaler;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SignatureException;
import java.util.Date;
import java.util.Iterator;

public class PgpDecryptVerifyOperation extends BaseOperation<PgpDecryptVerifyInputParcel> {

    public PgpDecryptVerifyOperation(Context context, ProviderHelper providerHelper, Progressable progressable) {
        super(context, providerHelper, progressable);
    }

    /** Decrypts and/or verifies data based on parameters of PgpDecryptVerifyInputParcel. */
    @NonNull
    public DecryptVerifyResult execute(PgpDecryptVerifyInputParcel input, CryptoInputParcel cryptoInput) {
        InputData inputData;
        OutputStream outputStream;

        if (input.getInputBytes() != null) {
            byte[] inputBytes = input.getInputBytes();
            inputData = new InputData(new ByteArrayInputStream(inputBytes), inputBytes.length);
        } else {
            try {
                InputStream inputStream = mContext.getContentResolver().openInputStream(input.getInputUri());
                long inputSize = FileHelper.getFileSize(mContext, input.getInputUri(), 0);
                inputData = new InputData(inputStream, inputSize);
            } catch (FileNotFoundException e) {
                Log.e(Constants.TAG, "Input URI could not be opened: " + input.getInputUri(), e);
                OperationLog log = new OperationLog();
                log.add(LogType.MSG_DC_ERROR_INPUT, 1);
                return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
            }
        }

        if (input.getOutputUri() == null) {
            outputStream = new ByteArrayOutputStream();
        } else {
            try {
                outputStream = mContext.getContentResolver().openOutputStream(input.getOutputUri());
            } catch (FileNotFoundException e) {
                Log.e(Constants.TAG, "Output URI could not be opened: " + input.getOutputUri(), e);
                OperationLog log = new OperationLog();
                log.add(LogType.MSG_DC_ERROR_IO, 1);
                return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
            }
        }

        DecryptVerifyResult result = executeInternal(input, cryptoInput, inputData, outputStream);
        if (outputStream instanceof ByteArrayOutputStream) {
            byte[] outputData = ((ByteArrayOutputStream) outputStream).toByteArray();
            result.setOutputBytes(outputData);
        }

        return result;

    }

    @NonNull
    public DecryptVerifyResult execute(PgpDecryptVerifyInputParcel input, CryptoInputParcel cryptoInput,
            InputData inputData, OutputStream outputStream) {
        return executeInternal(input, cryptoInput, inputData, outputStream);
    }

    @NonNull
    private DecryptVerifyResult executeInternal(PgpDecryptVerifyInputParcel input, CryptoInputParcel cryptoInput,
            InputData inputData, OutputStream outputStream) {
        try {
            if (input.getDetachedSignature() != null) {
                Log.d(Constants.TAG, "Detached signature present, verifying with this signature only");

                return verifyDetachedSignature(input, inputData, outputStream, 0);
            } else {
                // automatically works with PGP ascii armor and PGP binary
                InputStream in = PGPUtil.getDecoderStream(inputData.getInputStream());

                if (in instanceof ArmoredInputStream) {
                    ArmoredInputStream aIn = (ArmoredInputStream) in;
                    // it is ascii armored
                    Log.d(Constants.TAG, "ASCII Armor Header Line: " + aIn.getArmorHeaderLine());

                    if (input.isSignedLiteralData()) {
                        return verifySignedLiteralData(input, aIn, outputStream, 0);
                    } else if (aIn.isClearText()) {
                        // a cleartext signature, verify it with the other method
                        return verifyCleartextSignature(aIn, outputStream, 0);
                    } else {
                        // else: ascii armored encryption! go on...
                        return decryptVerify(input, cryptoInput, in, outputStream, 0);
                    }
                } else {
                    return decryptVerify(input, cryptoInput, in, outputStream, 0);
                }
            }
        } catch (PGPException e) {
            Log.d(Constants.TAG, "PGPException", e);
            OperationLog log = new OperationLog();
            log.add(LogType.MSG_DC_ERROR_PGP_EXCEPTION, 1);
            return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
        } catch (DecoderException | ArrayIndexOutOfBoundsException e) {
            // these can happen if assumptions in JcaPGPObjectFactory.nextObject() aren't
            // fulfilled, so we need to catch them here to handle this gracefully
            Log.d(Constants.TAG, "data error", e);
            OperationLog log = new OperationLog();
            log.add(LogType.MSG_DC_ERROR_IO, 1);
            return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
        } catch (IOException e) {
            Log.d(Constants.TAG, "IOException", e);
            OperationLog log = new OperationLog();
            log.add(LogType.MSG_DC_ERROR_IO, 1);
            return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
        }
    }

    /**Verify signed plaintext data (PGP/INLINE). */
    @NonNull
    private DecryptVerifyResult verifySignedLiteralData(
            PgpDecryptVerifyInputParcel input, InputStream in, OutputStream out, int indent)
            throws IOException, PGPException {
        OperationLog log = new OperationLog();
        log.add(LogType.MSG_VL, indent);

        // thinking that the proof-fetching operation is going to take most of the time
        updateProgress(R.string.progress_reading_data, 75, 100);

        JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
        Object o = pgpF.nextObject();
        if (o instanceof PGPCompressedData) {
            log.add(LogType.MSG_DC_CLEAR_DECOMPRESS, indent + 1);

            pgpF = new JcaPGPObjectFactory(((PGPCompressedData) o).getDataStream());
            o = pgpF.nextObject();
            updateProgress(R.string.progress_decompressing_data, 80, 100);
        }

        // all we want to see is a OnePassSignatureList followed by LiteralData
        if (!(o instanceof PGPOnePassSignatureList)) {
            log.add(LogType.MSG_VL_ERROR_MISSING_SIGLIST, indent);
            return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
        }
        PGPOnePassSignatureList sigList = (PGPOnePassSignatureList) o;

        // go through all signatures (should be just one), make sure we have
        //  the key and it matches the one we’re looking for
        CanonicalizedPublicKeyRing signingRing = null;
        CanonicalizedPublicKey signingKey = null;
        int signatureIndex = -1;
        for (int i = 0; i < sigList.size(); ++i) {
            try {
                long sigKeyId = sigList.get(i).getKeyID();
                signingRing = mProviderHelper.getCanonicalizedPublicKeyRing(
                        KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(sigKeyId)
                );
                signingKey = signingRing.getPublicKey(sigKeyId);
                signatureIndex = i;
            } catch (ProviderHelper.NotFoundException e) {