[
  {
    "path": ".gitattributes",
    "content": ".git* export-ignore\n"
  },
  {
    "path": ".github/workflows/release-linux-arm64.yml",
    "content": "on:\n  release:\n    types: [published]\nname: Build Release Binary (Linux ARM64)\njobs:\n  build:\n    name: Build Release Binary\n    runs-on: ubuntu-22.04-arm\n    permissions:\n      contents: read\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v3\n      - name: Install dependencies\n        run: sudo apt install libssl-dev\n      - name: Build binary\n        run: make\n      - name: Upload release artifact\n        uses: actions/upload-artifact@v4\n        with:\n          name: git-crypt-artifacts\n          path: git-crypt\n  upload:\n    name: Upload Release Binary\n    runs-on: ubuntu-latest\n    needs: build\n    permissions:\n      contents: write\n    steps:\n      - name: Download release artifact\n        uses: actions/download-artifact@v4\n        with:\n          name: git-crypt-artifacts\n      - name: Upload release asset\n        uses: actions/github-script@v6\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n          script: |\n            const fs = require(\"fs\").promises;\n            const { repo: { owner, repo }, sha } = context;\n            await github.rest.repos.uploadReleaseAsset({\n              owner, repo,\n              release_id: ${{ github.event.release.id }},\n              name: 'git-crypt-${{ github.event.release.name }}-linux-aarch64',\n              data: await fs.readFile('git-crypt'),\n            });\n"
  },
  {
    "path": ".github/workflows/release-linux.yml",
    "content": "on:\n  release:\n    types: [published]\nname: Build Release Binary (Linux)\njobs:\n  build:\n    name: Build Release Binary\n    runs-on: ubuntu-22.04\n    permissions:\n      contents: read\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v3\n      - name: Install dependencies\n        run: sudo apt install libssl-dev\n      - name: Build binary\n        run: make\n      - name: Upload release artifact\n        uses: actions/upload-artifact@v4\n        with:\n          name: git-crypt-artifacts\n          path: git-crypt\n  upload:\n    name: Upload Release Binary\n    runs-on: ubuntu-latest\n    needs: build\n    permissions:\n      contents: write\n    steps:\n      - name: Download release artifact\n        uses: actions/download-artifact@v4\n        with:\n          name: git-crypt-artifacts\n      - name: Upload release asset\n        uses: actions/github-script@v6\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n          script: |\n            const fs = require(\"fs\").promises;\n            const { repo: { owner, repo }, sha } = context;\n            await github.rest.repos.uploadReleaseAsset({\n              owner, repo,\n              release_id: ${{ github.event.release.id }},\n              name: 'git-crypt-${{ github.event.release.name }}-linux-x86_64',\n              data: await fs.readFile('git-crypt'),\n            });\n"
  },
  {
    "path": ".github/workflows/release-windows.yml",
    "content": "on:\n  release:\n    types: [published]\nname: Build Release Binary (Windows)\njobs:\n  build:\n    name: Build Release Binary\n    runs-on: windows-2022\n    permissions:\n      contents: read\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v3\n      - name: Setup msys2\n        uses: msys2/setup-msys2@v2\n        with:\n          msystem: MINGW64\n          update: true\n          install: >-\n            base-devel\n            msys2-devel\n            mingw-w64-x86_64-toolchain\n            mingw-w64-x86_64-openssl\n            openssl-devel\n      - name: Build binary\n        shell: msys2 {0}\n        run: make LDFLAGS=\"-static-libstdc++ -static -lcrypto -lws2_32 -lcrypt32\"\n      - name: Upload release artifact\n        uses: actions/upload-artifact@v4\n        with:\n          name: git-crypt-artifacts\n          path: git-crypt.exe\n  upload:\n    name: Upload Release Binary\n    runs-on: ubuntu-latest\n    needs: build\n    permissions:\n      contents: write\n    steps:\n      - name: Download release artifact\n        uses: actions/download-artifact@v4\n        with:\n          name: git-crypt-artifacts\n      - name: Upload release asset\n        uses: actions/github-script@v6\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n          script: |\n            const fs = require(\"fs\").promises;\n            const { repo: { owner, repo }, sha } = context;\n            await github.rest.repos.uploadReleaseAsset({\n              owner, repo,\n              release_id: ${{ github.event.release.id }},\n              name: 'git-crypt-${{ github.event.release.name }}-x86_64.exe',\n              data: await fs.readFile('git-crypt.exe'),\n            });\n"
  },
  {
    "path": ".gitignore",
    "content": "*.o\ngit-crypt\n"
  },
  {
    "path": "AUTHORS",
    "content": "Andrew Ayer <agwa@andrewayer.name>\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "Thanks for your interest in contributing to git-crypt!  git-crypt is\nopen source software and welcomes contributions in the form of code,\ndocumentation, bug reports, or anything else that improves git-crypt.\n\nWhen contributing code, please consider the following guidelines:\n\n * You are encouraged to open an issue on GitHub to discuss any non-trivial\n   changes before you start coding.\n\n * Please mimic the existing code style as much as possible.  In\n   particular, please indent code using tab characters with a width\n   of 8.\n\n * To minimize merge commits, please rebase your changes before opening\n   a pull request.\n\n * To submit your patch, open a pull request on GitHub.\n\nFinally, be aware that since git-crypt is security-sensitive software,\nthe bar for contributions is higher than average.  Please don't be\ndiscouraged by this, but be prepared for patches to possibly go through\nseveral rounds of feedback and improvement before being accepted.\nYour patience and understanding is appreciated.\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "INSTALL",
    "content": "DEPENDENCIES\n\nTo build git-crypt, you need:\n\n                                    Debian/Ubuntu package   RHEL/CentOS package\n  -----------------------------------------------------------------------------\n  Make                              make                    make\n  A C++11 compiler (e.g. gcc 4.9+)  g++                     gcc-c++\n  OpenSSL development files         libssl-dev              openssl-devel\n\n\nTo use git-crypt, you need:\n\n                                    Debian/Ubuntu package   RHEL/CentOS package\n  -----------------------------------------------------------------------------\n  Git 1.7.2 or newer                git                     git\n  OpenSSL                           openssl                 openssl\n\nNote: Git 1.8.5 or newer is recommended for best performance.\n\n\nBUILDING GIT-CRYPT\n\nRun:\n\n\t$ make\n\t$ make install\n\nTo install to a specific location:\n\n\t$ make install PREFIX=/usr/local\n\nOr, just copy the git-crypt binary to wherever is most convenient for you.\n\n\nBUILDING THE MAN PAGE\n\nTo build and install the git-crypt(1) man page, pass ENABLE_MAN=yes to make:\n\n\t$ make ENABLE_MAN=yes\n\t$ make ENABLE_MAN=yes install\n\nxsltproc is required to build the man page.  Note that xsltproc will access\nthe Internet to retrieve its stylesheet unless the Docbook stylesheet is\ninstalled locally and registered in the system's XML catalog.\n\n\nBUILDING A DEBIAN PACKAGE\n\nDebian packaging can be found in the 'debian' branch of the project\nGit repository.  The package is built using git-buildpackage as follows:\n\n\t$ git checkout debian\n\t$ git-buildpackage -uc -us\n\n\nINSTALLING ON MAC OS X\n\nUsing the brew package manager, simply run:\n\n        $ brew install git-crypt\n\n\nEXPERIMENTAL WINDOWS SUPPORT\n\ngit-crypt should build on Windows with MinGW, although the build system\nis not yet finalized so you will need to pass your own CXX, CXXFLAGS, and\nLDFLAGS variables to make.  Additionally, Windows support is less tested\nand does not currently create key files with restrictive permissions,\nmaking it unsuitable for use on a multi-user system.  Windows support\nwill mature in a future version of git-crypt.  Bug reports and patches\nare most welcome!\n"
  },
  {
    "path": "INSTALL.md",
    "content": "### Dependencies\n\nTo build git-crypt, you need:\n\n| Software                        | Debian/Ubuntu package | RHEL/CentOS package|\n|---------------------------------|-----------------------|--------------------|\n|Make                             | make                  | make               |\n|A C++11 compiler (e.g. gcc 4.9+) | g++                   | gcc-c++            |\n|OpenSSL development files        | libssl-dev            | openssl-devel      |\n\n\nTo use git-crypt, you need:\n\n| Software                        | Debian/Ubuntu package | RHEL/CentOS package|\n|---------------------------------|-----------------------|--------------------|\n|Git 1.7.2 or newer               | git                   | git                |\n|OpenSSL                          | openssl               | openssl            |\n\nNote: Git 1.8.5 or newer is recommended for best performance.\n\n\n### Building git-crypt\n\nRun:\n\n    make\n    make install\n\nTo install to a specific location:\n\n    make install PREFIX=/usr/local\n\nOr, just copy the git-crypt binary to wherever is most convenient for you.\n\n\n### Building The Man Page\n\nTo build and install the git-crypt(1) man page, pass `ENABLE_MAN=yes` to make:\n\n    make ENABLE_MAN=yes\n    make ENABLE_MAN=yes install\n\nxsltproc is required to build the man page.  Note that xsltproc will access\nthe Internet to retrieve its stylesheet unless the Docbook stylesheet is\ninstalled locally and registered in the system's XML catalog.\n\n\n### Building A Debian Package\n\nDebian packaging can be found in the 'debian' branch of the project Git\nrepository.  The package is built using git-buildpackage as follows:\n\n    git checkout debian\n    git-buildpackage -uc -us\n\n\n### Installing On Mac OS X\n\nUsing the brew package manager, simply run:\n\n    brew install git-crypt\n\n### Experimental Windows Support\n\ngit-crypt should build on Windows with MinGW, although the build system\nis not yet finalized so you will need to pass your own CXX, CXXFLAGS, and\nLDFLAGS variables to make.  Additionally, Windows support is less tested\nand does not currently create key files with restrictive permissions,\nmaking it unsuitable for use on a multi-user system.  Windows support\nwill mature in a future version of git-crypt.  Bug reports and patches\nare most welcome!\n"
  },
  {
    "path": "Makefile",
    "content": "#\n# Copyright (c) 2015 Andrew Ayer\n#\n# See COPYING file for license information.\n#\n\nCXXFLAGS ?= -Wall -pedantic -Wno-long-long -O2\nCXXFLAGS += -std=c++11\nPREFIX ?= /usr/local\nBINDIR ?= $(PREFIX)/bin\nMANDIR ?= $(PREFIX)/share/man\n\nENABLE_MAN ?= no\nDOCBOOK_XSL ?= http://cdn.docbook.org/release/xsl-nons/current/manpages/docbook.xsl\n\nOBJFILES = \\\n    git-crypt.o \\\n    commands.o \\\n    crypto.o \\\n    gpg.o \\\n    key.o \\\n    util.o \\\n    parse_options.o \\\n    coprocess.o \\\n    fhstream.o\n\nOBJFILES += crypto-openssl-11.o\nLDFLAGS += -lcrypto\n\nXSLTPROC ?= xsltproc\nDOCBOOK_FLAGS += --param man.output.in.separate.dir 1 \\\n\t\t --stringparam man.output.base.dir man/ \\\n\t\t --param man.output.subdirs.enabled 1 \\\n\t\t --param man.authors.section.enabled 1\n\nall: build\n\n#\n# Build\n#\nBUILD_MAN_TARGETS-yes = build-man\nBUILD_MAN_TARGETS-no =\nBUILD_TARGETS := build-bin $(BUILD_MAN_TARGETS-$(ENABLE_MAN))\n\nbuild: $(BUILD_TARGETS)\n\nbuild-bin: git-crypt\n\ngit-crypt: $(OBJFILES)\n\t$(CXX) $(CXXFLAGS) -o $@ $(OBJFILES) $(LDFLAGS)\n\nutil.o: util.cpp util-unix.cpp util-win32.cpp\ncoprocess.o: coprocess.cpp coprocess-unix.cpp coprocess-win32.cpp\n\nbuild-man: man/man1/git-crypt.1\n\nman/man1/git-crypt.1: man/git-crypt.xml\n\t$(XSLTPROC) $(DOCBOOK_FLAGS) $(DOCBOOK_XSL) man/git-crypt.xml\n\n#\n# Clean\n#\nCLEAN_MAN_TARGETS-yes = clean-man\nCLEAN_MAN_TARGETS-no =\nCLEAN_TARGETS := clean-bin $(CLEAN_MAN_TARGETS-$(ENABLE_MAN))\n\nclean: $(CLEAN_TARGETS)\n\nclean-bin:\n\trm -f $(OBJFILES) git-crypt\n\nclean-man:\n\trm -f man/man1/git-crypt.1\n\n#\n# Install\n#\nINSTALL_MAN_TARGETS-yes = install-man\nINSTALL_MAN_TARGETS-no =\nINSTALL_TARGETS := install-bin $(INSTALL_MAN_TARGETS-$(ENABLE_MAN))\n\ninstall: $(INSTALL_TARGETS)\n\ninstall-bin: build-bin\n\tinstall -d $(DESTDIR)$(BINDIR)\n\tinstall -m 755 git-crypt $(DESTDIR)$(BINDIR)/\n\ninstall-man: build-man\n\tinstall -d $(DESTDIR)$(MANDIR)/man1\n\tinstall -m 644 man/man1/git-crypt.1 $(DESTDIR)$(MANDIR)/man1/\n\n.PHONY: all \\\n\tbuild build-bin build-man \\\n\tclean clean-bin clean-man \\\n\tinstall install-bin install-man\n"
  },
  {
    "path": "NEWS.md",
    "content": "# Change Log\n\n## v0.8.0 (2025-09-23)\n* Remove OpenSSL 1.0 support, fix compilation with OpenSSL 3.\n* Avoid use of problematic short GPG key IDs.\n\n## v0.7.0 (2022-04-21)\n* Avoid \"argument list too long\" errors on macOS.\n* Fix handling of \"-\" arguments.\n* Minor documentation improvements.\n\n## v0.6.0 (2017-11-26)\n* Add support for OpenSSL 1.1 (still works with OpenSSL 1.0).\n* Switch to C++11 (gcc 4.9 or higher now required to build).\n* Allow GPG to fail on some keys (makes unlock work better if there are\n  multiple keys that can unlock the repo but only some are available).\n* Allow the repo state directory to be configured with the\n  git-crypt.repoStateDir git config option.\n* Respect the gpg.program git config option.\n* Don't hard code path to git-crypt in .git/config on Linux (ensures\n  repo continues to work if git-crypt is moved).\n* Ensure git-crypt's gpg files won't be treated as text by Git.\n* Minor improvements to build system, documentation.\n\n## v0.5.0 (2015-05-30)\n* Drastically speed up lock/unlock when used with Git 1.8.5 or newer.\n* Add git-crypt(1) man page (pass `ENABLE_MAN=yes` to make to build).\n* Add --trusted option to `git-crypt gpg-add-user` to add user even if\n  GPG doesn't trust user's key.\n* Improve `git-crypt lock` usability, add --force option.\n* Ignore symlinks and other non-files when running `git-crypt status`.\n* Fix compilation on old versions of Mac OS X.\n* Fix GPG mode when with-fingerprint enabled in gpg.conf.\n* Minor bug fixes and improvements to help/error messages.\n\n## v0.4.2 (2015-01-31)\n* Fix unlock and lock under Git 2.2.2 and higher.\n* Drop support for versions of Git older than 1.7.2.\n* Minor improvements to some help/error messages.\n\n## v0.4.1 (2015-01-08)\n* Important usability fix to ensure that the .git-crypt directory\n  can't be encrypted by accident (see\n  [the release notes](RELEASE_NOTES-0.4.1.md) for more information).\n\n## v0.4 (2014-11-16)\n(See [the release notes](RELEASE_NOTES-0.4.md) for important details.)\n* Add optional GPG support: GPG can be used to share the repository\n  between one or more users in lieu of sharing a secret key.\n* New workflow: the symmetric key is now stored inside the .git\n  directory.  Although backwards compatibility has been preserved\n  with repositories created by old versions of git-crypt, the\n  commands for setting up a repository have changed.  See the\n  release notes file for details.\n* Multiple key support: it's now possible to encrypt different parts\n  of a repository with different keys.\n* Initial `git-crypt status` command to report which files are\n  encrypted and to fix problems that are detected.\n* Numerous usability, documentation, and error reporting improvements.\n* Major internal code improvements that will make future development\n  easier.\n* Initial experimental Windows support.\n\n## v0.3 (2013-04-05)\n* Fix `git-crypt init` on newer versions of Git.  Previously,\n  encrypted files were not being automatically decrypted after running\n  `git-crypt init` with recent versions of Git.\n* Allow `git-crypt init` to be run even if the working tree contains\n  untracked files.\n* `git-crypt init` now properly escapes arguments to the filter\n  commands it configures, allowing both the path to git-crypt and the\n  path to the key file to contain arbitrary characters such as spaces.\n\n## v0.2 (2013-01-25)\n* Numerous improvements to `git-crypt init` usability.\n* Fix gitattributes example in [README](README.md): the old example\n  showed a colon after the filename where there shouldn't be one.\n* Various build fixes and improvements.\n\n## v0.1 (2012-11-29)\n* Initial release.\n"
  },
  {
    "path": "README.md",
    "content": "git-crypt - transparent file encryption in git\n==============================================\n\ngit-crypt enables transparent encryption and decryption of files in a\ngit repository.  Files which you choose to protect are encrypted when\ncommitted, and decrypted when checked out.  git-crypt lets you freely\nshare a repository containing a mix of public and private content.\ngit-crypt gracefully degrades, so developers without the secret key can\nstill clone and commit to a repository with encrypted files.  This lets\nyou store your secret material (such as keys or passwords) in the same\nrepository as your code, without requiring you to lock down your entire\nrepository.\n\ngit-crypt was written by [Andrew Ayer](https://www.agwa.name) (agwa@andrewayer.name).\nFor more information, see <https://www.agwa.name/projects/git-crypt>.\n\nBuilding git-crypt\n------------------\nSee the [INSTALL.md](INSTALL.md) file.\n\n\nUsing git-crypt\n---------------\n\nConfigure a repository to use git-crypt:\n\n    cd repo\n    git-crypt init\n\nSpecify files to encrypt by creating a .gitattributes file:\n\n    secretfile filter=git-crypt diff=git-crypt\n    *.key filter=git-crypt diff=git-crypt\n    secretdir/** filter=git-crypt diff=git-crypt\n\nLike a .gitignore file, it can match wildcards and should be checked into\nthe repository.  See below for more information about .gitattributes.\nMake sure you don't accidentally encrypt the .gitattributes file itself\n(or other git files like .gitignore or .gitmodules).  Make sure your\n.gitattributes rules are in place *before* you add sensitive files, or\nthose files won't be encrypted!\n\nShare the repository with others (or with yourself) using GPG:\n\n    git-crypt add-gpg-user USER_ID\n\n`USER_ID` can be a key ID, a full fingerprint, an email address, or\nanything else that uniquely identifies a public key to GPG (see \"HOW TO\nSPECIFY A USER ID\" in the gpg man page).  Note: `git-crypt add-gpg-user`\nwill add and commit a GPG-encrypted key file in the .git-crypt directory\nof the root of your repository.\n\nAlternatively, you can export a symmetric secret key, which you must\nsecurely convey to collaborators (GPG is not required, and no files\nare added to your repository):\n\n    git-crypt export-key /path/to/key\n\nAfter cloning a repository with encrypted files, unlock with GPG:\n\n    git-crypt unlock\n\nOr with a symmetric key:\n\n    git-crypt unlock /path/to/key\n\nThat's all you need to do - after git-crypt is set up (either with\n`git-crypt init` or `git-crypt unlock`), you can use git normally -\nencryption and decryption happen transparently.\n\nCurrent Status\n--------------\n\nThe latest version of git-crypt is [0.8.0](NEWS.md), released on\n2025-09-23.  git-crypt aims to be bug-free and reliable, meaning it\nshouldn't crash, malfunction, or expose your confidential data.\nHowever, it has not yet reached maturity, meaning it is not as\ndocumented, featureful, or easy-to-use as it should be.  Additionally,\nthere may be backwards-incompatible changes introduced before version\n1.0.\n\nSecurity\n--------\n\ngit-crypt is more secure than other transparent git encryption systems.\ngit-crypt encrypts files using AES-256 in CTR mode with a synthetic IV\nderived from the SHA-1 HMAC of the file.  This mode of operation is\nprovably semantically secure under deterministic chosen-plaintext attack.\nThat means that although the encryption is deterministic (which is\nrequired so git can distinguish when a file has and hasn't changed),\nit leaks no information beyond whether two files are identical or not.\nOther proposals for transparent git encryption use ECB or CBC with a\nfixed IV.  These systems are not semantically secure and leak information.\n\nLimitations\n-----------\n\ngit-crypt relies on git filters, which were not designed with encryption\nin mind.  As such, git-crypt is not the best tool for encrypting most or\nall of the files in a repository. Where git-crypt really shines is where\nmost of your repository is public, but you have a few files (perhaps\nprivate keys named *.key, or a file with API credentials) which you\nneed to encrypt.  For encrypting an entire repository, consider using a\nsystem like [git-remote-gcrypt](https://spwhitton.name/tech/code/git-remote-gcrypt/)\ninstead.  (Note: no endorsement is made of git-remote-gcrypt's security.)\n\ngit-crypt does not encrypt file names, commit messages, symlink targets,\ngitlinks, or other metadata.\n\ngit-crypt does not hide when a file does or doesn't change, the length\nof a file, or the fact that two files are identical (see \"Security\"\nsection above).\n\ngit-crypt does not support revoking access to an encrypted repository\nwhich was previously granted. This applies to both multi-user GPG\nmode (there's no del-gpg-user command to complement add-gpg-user)\nand also symmetric key mode (there's no support for rotating the key).\nThis is because it is an inherently complex problem in the context\nof historical data. For example, even if a key was rotated at one\npoint in history, a user having the previous key can still access\nprevious repository history. This problem is discussed in more detail in\n<https://github.com/AGWA/git-crypt/issues/47>.\n\nFiles encrypted with git-crypt are not compressible.  Even the smallest\nchange to an encrypted file requires git to store the entire changed file,\ninstead of just a delta.\n\nAlthough git-crypt protects individual file contents with a SHA-1\nHMAC, git-crypt cannot be used securely unless the entire repository is\nprotected against tampering (an attacker who can mutate your repository\ncan alter your .gitattributes file to disable encryption).  If necessary,\nuse git features such as signed tags instead of relying solely on\ngit-crypt for integrity.\n\nFiles encrypted with git-crypt cannot be patched with git-apply, unless\nthe patch itself is encrypted.  To generate an encrypted patch, use `git\ndiff --no-textconv --binary`.  Alternatively, you can apply a plaintext\npatch outside of git using the patch command.\n\ngit-crypt does not work reliably with some third-party git GUIs, such\nas [Atlassian SourceTree](https://jira.atlassian.com/browse/SRCTREE-2511)\nand GitHub for Mac.  Files might be left in an unencrypted state.\n\nGitattributes File\n------------------\n\nThe .gitattributes file is documented in the gitattributes(5) man page.\nThe file pattern format is the same as the one used by .gitignore,\nas documented in the gitignore(5) man page, with the exception that\nspecifying merely a directory (e.g. `/dir/`) is *not* sufficient to\nencrypt all files beneath it.\n\nAlso note that the pattern `dir/*` does not match files under\nsub-directories of dir/.  To encrypt an entire sub-tree dir/, use `dir/**`:\n\n    dir/** filter=git-crypt diff=git-crypt\n\nThe .gitattributes file must not be encrypted, so make sure wildcards don't\nmatch it accidentally.  If necessary, you can exclude .gitattributes from\nencryption like this:\n\n    .gitattributes !filter !diff\n"
  },
  {
    "path": "RELEASE_NOTES-0.4.1.md",
    "content": "git-crypt 0.4.1 is a bugfix-only release that contains an important\nusability fix for users who use GPG mode to encrypt an entire repository.\n\nPreviously, if you used a '*' pattern in the top-level .gitattributes\nfile, and you did not explicitly add a pattern to exclude the .git-crypt\ndirectory, the files contained therein would be encrypted, rendering\nthe repository impossible to unlock with GPG.\n\ngit-crypt now adds a .gitattributes file to the .git-crypt directory\nto prevent its contents from being encrypted, regardless of patterns in\nthe top-level .gitattributes.\n\nIf you are using git-crypt in GPG mode to encrypt an entire repository,\nand you do not already have a .gitattributes pattern to exclude the\n.git-crypt directory, you are strongly advised to upgrade.  After\nupgrading, you should do the following in each of your repositories to\nensure that the information inside .git-crypt is properly stored:\n\n1. Remove existing key files: `rm .git-crypt/keys/*/0/*`\n\n2. Re-add GPG user(s): `git-crypt add-gpg-user GPG_USER_ID ...`\n"
  },
  {
    "path": "RELEASE_NOTES-0.4.md",
    "content": "Changes to be aware of for git-crypt 0.4\n========================================\n\n(For a complete list of changes, see the [NEWS](NEWS.md) file.)\n\n\n### New workflow\n\nThe commands for setting up a repository have changed in git-crypt 0.4.\nThe previous commands continue to work, but will be removed in a future\nrelease of git-crypt.  Please get in the habit of using the new syntax:\n\n`git-crypt init` no longer takes an argument, and is now used only when\ninitializing a repository for the very first time.  It generates a key\nand stores it in the `.git` directory. There is no longer a separate\n`keygen` step, and you no longer need to keep a copy of the key outside\nthe repository.\n\n`git-crypt init` is no longer used to decrypt a cloned repository.  Instead,\nrun `git-crypt unlock /path/to/keyfile`, where `keyfile` is obtained by\nrunning `git-crypt export-key /path/to/keyfile` from an already-decrypted\nrepository.\n\n\n### GPG mode\n\ngit-crypt now supports GPG.  A repository can be shared with one or more\nGPG users in lieu of sharing a secret symmetric key.  Symmetric key support\nisn't going away, but the workflow of GPG mode is extremely easy and all users\nare encouraged to consider it for their repositories.\n\nSee the [README](README.md) for details on using GPG.\n\n\n### Status command\n\nA new command, `git-crypt status`, lists encrypted files, which is\nuseful for making sure your `.gitattributes` pattern is protecting the\nright files.\n\n\n### Multiple key support\n\ngit-crypt now lets you encrypt different sets of files with different\nkeys, which is useful if you want to grant different collaborators access\nto different sets of files.\n\nSee [doc/multiple_keys.md](doc/multiple_keys.md) for details.\n\n\n### Compatibility with old repositories\n\nRepositories created with older versions of git-crypt continue to work\nwithout any changes needed, and backwards compatibility with these\nrepositories will be maintained indefinitely.\n\nHowever, you will not be able to take advantage of git-crypt's new\nfeatures, such as GPG support, unless you migrate your repository.\n\nTo migrate your repository, first ensure the working tree is clean.\nThen migrate your current key file and use the migrated key to unlock\nyour repository as follows:\n\n    git-crypt migrate-key /path/to/old_key /path/to/migrated_key\n    git-crypt unlock /path/to/migrated_key\n\nOnce you've confirmed that your repository is functional, you can delete\nboth the old and migrated key files (though keeping a backup of your key\nis always a good idea).\n\n\n### Known issues\n\nIt is not yet possible to revoke access from a GPG user.  This will\nrequire substantial development work and will be a major focus of future\ngit-crypt development.\n\nThe output of `git-crypt status` is currently very bare-bones and will\nbe substantially improved in a future release.  Do not rely on its output\nbeing stable.  A future release of git-crypt will provide an option for stable\nmachine-readable output.\n\nOn Windows, git-crypt does not create key files with restrictive\npermissions.  Take care when using git-crypt on a multi-user Windows system.\n"
  },
  {
    "path": "THANKS.md",
    "content": "For their contributions to git-crypt, I thank:\n\n * Michael Mior and @zimbatm for the Homebrew formula.\n\n * Cyril Cleaud for help with Windows support.\n\n * The following people for contributing patches:\n   * Adam Nelson\n   * Caleb Maclennan\n   * Darayus Nanavati\n   * Jon Sailor\n   * Linus G Thiel\n   * Michael Schout\n   * Simon Kotlinski\n   * Kevin Menard\n   * Wael M. Nasreddine\n   * Kevin Borgolte\n   * Adrian Cohea\n\n * And everyone who has tested git-crypt, provided feedback, reported\n   bugs, and participated in discussions about new features.\n\nThank you!\n"
  },
  {
    "path": "commands.cpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"commands.hpp\"\n#include \"crypto.hpp\"\n#include \"util.hpp\"\n#include \"key.hpp\"\n#include \"gpg.hpp\"\n#include \"parse_options.hpp\"\n#include \"coprocess.hpp\"\n#include <unistd.h>\n#include <stdint.h>\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <cstddef>\n#include <cstring>\n#include <cctype>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <exception>\n#include <vector>\n\nenum {\n\t// # of arguments per git checkout call; must be large enough to be efficient but small\n\t// enough to avoid operating system limits on argument length\n\tGIT_CHECKOUT_BATCH_SIZE = 100\n};\n\nstatic std::string attribute_name (const char* key_name)\n{\n\tif (key_name) {\n\t\t// named key\n\t\treturn std::string(\"git-crypt-\") + key_name;\n\t} else {\n\t\t// default key\n\t\treturn \"git-crypt\";\n\t}\n}\n\nstatic std::string git_version_string ()\n{\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"version\");\n\n\tstd::stringstream\t\toutput;\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git version' failed - is Git installed?\");\n\t}\n\tstd::string\t\t\tword;\n\toutput >> word; // \"git\"\n\toutput >> word; // \"version\"\n\toutput >> word; // \"1.7.10.4\"\n\treturn word;\n}\n\nstatic std::vector<int> parse_version (const std::string& str)\n{\n\tstd::istringstream\tin(str);\n\tstd::vector<int>\tversion;\n\tstd::string\t\tcomponent;\n\twhile (std::getline(in, component, '.')) {\n\t\tversion.push_back(std::atoi(component.c_str()));\n\t}\n\treturn version;\n}\n\nstatic const std::vector<int>& git_version ()\n{\n\tstatic const std::vector<int> version(parse_version(git_version_string()));\n\treturn version;\n}\n\nstatic std::vector<int> make_version (int a, int b, int c)\n{\n\tstd::vector<int>\tversion;\n\tversion.push_back(a);\n\tversion.push_back(b);\n\tversion.push_back(c);\n\treturn version;\n}\n\nstatic void git_config (const std::string& name, const std::string& value)\n{\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"config\");\n\tcommand.push_back(name);\n\tcommand.push_back(value);\n\n\tif (!successful_exit(exec_command(command))) {\n\t\tthrow Error(\"'git config' failed\");\n\t}\n}\n\nstatic bool git_has_config (const std::string& name)\n{\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"config\");\n\tcommand.push_back(\"--get-all\");\n\tcommand.push_back(name);\n\n\tstd::stringstream\t\toutput;\n\tswitch (exit_status(exec_command(command, output))) {\n\t\tcase 0:  return true;\n\t\tcase 1:  return false;\n\t\tdefault: throw Error(\"'git config' failed\");\n\t}\n}\n\nstatic void git_deconfig (const std::string& name)\n{\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"config\");\n\tcommand.push_back(\"--remove-section\");\n\tcommand.push_back(name);\n\n\tif (!successful_exit(exec_command(command))) {\n\t\tthrow Error(\"'git config' failed\");\n\t}\n}\n\nstatic void configure_git_filters (const char* key_name)\n{\n\tstd::string\tescaped_git_crypt_path(escape_shell_arg(our_exe_path()));\n\n\tif (key_name) {\n\t\t// Note: key_name contains only shell-safe characters so it need not be escaped.\n\t\tgit_config(std::string(\"filter.git-crypt-\") + key_name + \".smudge\",\n\t\t           escaped_git_crypt_path + \" smudge --key-name=\" + key_name);\n\t\tgit_config(std::string(\"filter.git-crypt-\") + key_name + \".clean\",\n\t\t           escaped_git_crypt_path + \" clean --key-name=\" + key_name);\n\t\tgit_config(std::string(\"filter.git-crypt-\") + key_name + \".required\", \"true\");\n\t\tgit_config(std::string(\"diff.git-crypt-\") + key_name + \".textconv\",\n\t\t           escaped_git_crypt_path + \" diff --key-name=\" + key_name);\n\t} else {\n\t\tgit_config(\"filter.git-crypt.smudge\", escaped_git_crypt_path + \" smudge\");\n\t\tgit_config(\"filter.git-crypt.clean\", escaped_git_crypt_path + \" clean\");\n\t\tgit_config(\"filter.git-crypt.required\", \"true\");\n\t\tgit_config(\"diff.git-crypt.textconv\", escaped_git_crypt_path + \" diff\");\n\t}\n}\n\nstatic void deconfigure_git_filters (const char* key_name)\n{\n\t// deconfigure the git-crypt filters\n\tif (git_has_config(\"filter.\" + attribute_name(key_name) + \".smudge\") ||\n\t\t\tgit_has_config(\"filter.\" + attribute_name(key_name) + \".clean\") ||\n\t\t\tgit_has_config(\"filter.\" + attribute_name(key_name) + \".required\")) {\n\n\t\tgit_deconfig(\"filter.\" + attribute_name(key_name));\n\t}\n\n\tif (git_has_config(\"diff.\" + attribute_name(key_name) + \".textconv\")) {\n\t\tgit_deconfig(\"diff.\" + attribute_name(key_name));\n\t}\n}\n\nstatic bool git_checkout_batch (std::vector<std::string>::const_iterator paths_begin, std::vector<std::string>::const_iterator paths_end)\n{\n\tif (paths_begin == paths_end) {\n\t\treturn true;\n\t}\n\n\tstd::vector<std::string>\tcommand;\n\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"checkout\");\n\tcommand.push_back(\"--\");\n\n\tfor (auto path(paths_begin); path != paths_end; ++path) {\n\t\tcommand.push_back(*path);\n\t}\n\n\tif (!successful_exit(exec_command(command))) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nstatic bool git_checkout (const std::vector<std::string>& paths)\n{\n\tauto paths_begin(paths.begin());\n\twhile (paths.end() - paths_begin >= GIT_CHECKOUT_BATCH_SIZE) {\n\t\tif (!git_checkout_batch(paths_begin, paths_begin + GIT_CHECKOUT_BATCH_SIZE)) {\n\t\t\treturn false;\n\t\t}\n\t\tpaths_begin += GIT_CHECKOUT_BATCH_SIZE;\n\t}\n\treturn git_checkout_batch(paths_begin, paths.end());\n}\n\nstatic bool same_key_name (const char* a, const char* b)\n{\n\treturn (!a && !b) || (a && b && std::strcmp(a, b) == 0);\n}\n\nstatic void validate_key_name_or_throw (const char* key_name)\n{\n\tstd::string\t\t\treason;\n\tif (!validate_key_name(key_name, &reason)) {\n\t\tthrow Error(reason);\n\t}\n}\n\nstatic std::string get_internal_state_path ()\n{\n\t// git rev-parse --git-dir\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"rev-parse\");\n\tcommand.push_back(\"--git-dir\");\n\n\tstd::stringstream\t\toutput;\n\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git rev-parse --git-dir' failed - is this a Git repository?\");\n\t}\n\n\tstd::string\t\t\tpath;\n\tstd::getline(output, path);\n\tpath += \"/git-crypt\";\n\n\treturn path;\n}\n\nstatic std::string get_internal_keys_path (const std::string& internal_state_path)\n{\n\treturn internal_state_path + \"/keys\";\n}\n\nstatic std::string get_internal_keys_path ()\n{\n\treturn get_internal_keys_path(get_internal_state_path());\n}\n\nstatic std::string get_internal_key_path (const char* key_name)\n{\n\tstd::string\t\tpath(get_internal_keys_path());\n\tpath += \"/\";\n\tpath += key_name ? key_name : \"default\";\n\n\treturn path;\n}\n\nstd::string get_git_config (const std::string& name)\n{\n\t// git config --get\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"config\");\n\tcommand.push_back(\"--get\");\n\tcommand.push_back(name);\n\n\tstd::stringstream\toutput;\n\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git config' missing value for key '\" + name +\"'\");\n\t}\n\n\tstd::string\t\tvalue;\n\tstd::getline(output, value);\n\n\treturn value;\n}\n\nstatic std::string get_repo_state_path ()\n{\n\t// git rev-parse --show-toplevel\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"rev-parse\");\n\tcommand.push_back(\"--show-toplevel\");\n\n\tstd::stringstream\t\toutput;\n\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git rev-parse --show-toplevel' failed - is this a Git repository?\");\n\t}\n\n\tstd::string\t\t\tpath;\n\tstd::getline(output, path);\n\n\tif (path.empty()) {\n\t\t// could happen for a bare repo\n\t\tthrow Error(\"Could not determine Git working tree - is this a non-bare repo?\");\n\t}\n\n\t// Check if the repo state dir has been explicitly configured. If so, use that in path construction.\n\tif (git_has_config(\"git-crypt.repoStateDir\")) {\n\t\tstd::string\t\trepoStateDir = get_git_config(\"git-crypt.repoStateDir\");\n\n\t\t// The repoStateDir value must always be relative to git work tree to ensure the repoStateDir can be committed\n\t\t// along with the remainder of the repository.\n\t\tpath += '/' + repoStateDir;\n\t} else {\n\t\t// There is no explicitly configured repo state dir configured, so use the default.\n\t\tpath += \"/.git-crypt\";\n\t}\n\n\treturn path;\n}\n\nstatic std::string get_repo_keys_path (const std::string& repo_state_path)\n{\n\treturn repo_state_path + \"/keys\";\n}\n\nstatic std::string get_repo_keys_path ()\n{\n\treturn get_repo_keys_path(get_repo_state_path());\n}\n\nstatic std::string get_path_to_top ()\n{\n\t// git rev-parse --show-cdup\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"rev-parse\");\n\tcommand.push_back(\"--show-cdup\");\n\n\tstd::stringstream\t\toutput;\n\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git rev-parse --show-cdup' failed - is this a Git repository?\");\n\t}\n\n\tstd::string\t\t\tpath_to_top;\n\tstd::getline(output, path_to_top);\n\n\treturn path_to_top;\n}\n\nstatic void get_git_status (std::ostream& output)\n{\n\t// git status -uno --porcelain\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"status\");\n\tcommand.push_back(\"-uno\"); // don't show untracked files\n\tcommand.push_back(\"--porcelain\");\n\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git status' failed - is this a Git repository?\");\n\t}\n}\n\n// returns filter and diff attributes as a pair\nstatic std::pair<std::string, std::string> get_file_attributes (const std::string& filename)\n{\n\t// git check-attr filter diff -- filename\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"check-attr\");\n\tcommand.push_back(\"filter\");\n\tcommand.push_back(\"diff\");\n\tcommand.push_back(\"--\");\n\tcommand.push_back(filename);\n\n\tstd::stringstream\t\toutput;\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git check-attr' failed - is this a Git repository?\");\n\t}\n\n\tstd::string\t\t\tfilter_attr;\n\tstd::string\t\t\tdiff_attr;\n\n\tstd::string\t\t\tline;\n\t// Example output:\n\t// filename: filter: git-crypt\n\t// filename: diff: git-crypt\n\twhile (std::getline(output, line)) {\n\t\t// filename might contain \": \", so parse line backwards\n\t\t// filename: attr_name: attr_value\n\t\t//         ^name_pos  ^value_pos\n\t\tconst std::string::size_type\tvalue_pos(line.rfind(\": \"));\n\t\tif (value_pos == std::string::npos || value_pos == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst std::string::size_type\tname_pos(line.rfind(\": \", value_pos - 1));\n\t\tif (name_pos == std::string::npos) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst std::string\t\tattr_name(line.substr(name_pos + 2, value_pos - (name_pos + 2)));\n\t\tconst std::string\t\tattr_value(line.substr(value_pos + 2));\n\n\t\tif (attr_value != \"unspecified\" && attr_value != \"unset\" && attr_value != \"set\") {\n\t\t\tif (attr_name == \"filter\") {\n\t\t\t\tfilter_attr = attr_value;\n\t\t\t} else if (attr_name == \"diff\") {\n\t\t\t\tdiff_attr = attr_value;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::make_pair(filter_attr, diff_attr);\n}\n\n// returns filter and diff attributes as a pair\nstatic std::pair<std::string, std::string> get_file_attributes (const std::string& filename, std::ostream& check_attr_stdin, std::istream& check_attr_stdout)\n{\n\tcheck_attr_stdin << filename << '\\0' << std::flush;\n\n\tstd::string\t\t\tfilter_attr;\n\tstd::string\t\t\tdiff_attr;\n\n\t// Example output:\n\t// filename\\0filter\\0git-crypt\\0filename\\0diff\\0git-crypt\\0\n\tfor (int i = 0; i < 2; ++i) {\n\t\tstd::string\t\tfilename;\n\t\tstd::string\t\tattr_name;\n\t\tstd::string\t\tattr_value;\n\t\tstd::getline(check_attr_stdout, filename, '\\0');\n\t\tstd::getline(check_attr_stdout, attr_name, '\\0');\n\t\tstd::getline(check_attr_stdout, attr_value, '\\0');\n\n\t\tif (attr_value != \"unspecified\" && attr_value != \"unset\" && attr_value != \"set\") {\n\t\t\tif (attr_name == \"filter\") {\n\t\t\t\tfilter_attr = attr_value;\n\t\t\t} else if (attr_name == \"diff\") {\n\t\t\t\tdiff_attr = attr_value;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::make_pair(filter_attr, diff_attr);\n}\n\nstatic bool check_if_blob_is_encrypted (const std::string& object_id)\n{\n\t// git cat-file blob object_id\n\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"cat-file\");\n\tcommand.push_back(\"blob\");\n\tcommand.push_back(object_id);\n\n\t// TODO: do this more efficiently - don't read entire command output into buffer, only read what we need\n\tstd::stringstream\t\toutput;\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git cat-file' failed - is this a Git repository?\");\n\t}\n\n\tchar\t\t\t\theader[10];\n\toutput.read(header, sizeof(header));\n\treturn output.gcount() == sizeof(header) && std::memcmp(header, \"\\0GITCRYPT\\0\", 10) == 0;\n}\n\nstatic bool check_if_file_is_encrypted (const std::string& filename)\n{\n\t// git ls-files -sz filename\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"ls-files\");\n\tcommand.push_back(\"-sz\");\n\tcommand.push_back(\"--\");\n\tcommand.push_back(filename);\n\n\tstd::stringstream\t\toutput;\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git ls-files' failed - is this a Git repository?\");\n\t}\n\n\tif (output.peek() == -1) {\n\t\treturn false;\n\t}\n\n\tstd::string\t\t\tmode;\n\tstd::string\t\t\tobject_id;\n\toutput >> mode >> object_id;\n\n\treturn check_if_blob_is_encrypted(object_id);\n}\n\nstatic bool is_git_file_mode (const std::string& mode)\n{\n\treturn (std::strtoul(mode.c_str(), nullptr, 8) & 0170000) == 0100000;\n}\n\nstatic void get_encrypted_files (std::vector<std::string>& files, const char* key_name)\n{\n\t// git ls-files -cz -- path_to_top\n\tstd::vector<std::string>\tls_files_command;\n\tls_files_command.push_back(\"git\");\n\tls_files_command.push_back(\"ls-files\");\n\tls_files_command.push_back(\"-csz\");\n\tls_files_command.push_back(\"--\");\n\tconst std::string\t\tpath_to_top(get_path_to_top());\n\tif (!path_to_top.empty()) {\n\t\tls_files_command.push_back(path_to_top);\n\t}\n\n\tCoprocess\t\t\tls_files;\n\tstd::istream*\t\t\tls_files_stdout = ls_files.stdout_pipe();\n\tls_files.spawn(ls_files_command);\n\n\tCoprocess\t\t\tcheck_attr;\n\tstd::ostream*\t\t\tcheck_attr_stdin = nullptr;\n\tstd::istream*\t\t\tcheck_attr_stdout = nullptr;\n\tif (git_version() >= make_version(1, 8, 5)) {\n\t\t// In Git 1.8.5 (released 27 Nov 2013) and higher, we use a single `git check-attr` process\n\t\t// to get the attributes of all files at once.  In prior versions, we have to fork and exec\n\t\t// a separate `git check-attr` process for each file, since -z and --stdin aren't supported.\n\t\t// In a repository with thousands of files, this results in an almost 100x speedup.\n\t\tstd::vector<std::string>\tcheck_attr_command;\n\t\tcheck_attr_command.push_back(\"git\");\n\t\tcheck_attr_command.push_back(\"check-attr\");\n\t\tcheck_attr_command.push_back(\"--stdin\");\n\t\tcheck_attr_command.push_back(\"-z\");\n\t\tcheck_attr_command.push_back(\"filter\");\n\t\tcheck_attr_command.push_back(\"diff\");\n\n\t\tcheck_attr_stdin = check_attr.stdin_pipe();\n\t\tcheck_attr_stdout = check_attr.stdout_pipe();\n\t\tcheck_attr.spawn(check_attr_command);\n\t}\n\n\twhile (ls_files_stdout->peek() != -1) {\n\t\tstd::string\t\tmode;\n\t\tstd::string\t\tobject_id;\n\t\tstd::string\t\tstage;\n\t\tstd::string\t\tfilename;\n\t\t*ls_files_stdout >> mode >> object_id >> stage >> std::ws;\n\t\tstd::getline(*ls_files_stdout, filename, '\\0');\n\n\t\tif (is_git_file_mode(mode)) {\n\t\t\tstd::string\tfilter_attribute;\n\n\t\t\tif (check_attr_stdin) {\n\t\t\t\tfilter_attribute = get_file_attributes(filename, *check_attr_stdin, *check_attr_stdout).first;\n\t\t\t} else {\n\t\t\t\tfilter_attribute = get_file_attributes(filename).first;\n\t\t\t}\n\n\t\t\tif (filter_attribute == attribute_name(key_name)) {\n\t\t\t\tfiles.push_back(filename);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!successful_exit(ls_files.wait())) {\n\t\tthrow Error(\"'git ls-files' failed - is this a Git repository?\");\n\t}\n\n\tif (check_attr_stdin) {\n\t\tcheck_attr.close_stdin();\n\t\tif (!successful_exit(check_attr.wait())) {\n\t\t\tthrow Error(\"'git check-attr' failed - is this a Git repository?\");\n\t\t}\n\t}\n}\n\nstatic void load_key (Key_file& key_file, const char* key_name, const char* key_path =0, const char* legacy_path =0)\n{\n\tif (legacy_path) {\n\t\tstd::ifstream\t\tkey_file_in(legacy_path, std::fstream::binary);\n\t\tif (!key_file_in) {\n\t\t\tthrow Error(std::string(\"Unable to open key file: \") + legacy_path);\n\t\t}\n\t\tkey_file.load_legacy(key_file_in);\n\t} else if (key_path) {\n\t\tstd::ifstream\t\tkey_file_in(key_path, std::fstream::binary);\n\t\tif (!key_file_in) {\n\t\t\tthrow Error(std::string(\"Unable to open key file: \") + key_path);\n\t\t}\n\t\tkey_file.load(key_file_in);\n\t} else {\n\t\tstd::ifstream\t\tkey_file_in(get_internal_key_path(key_name).c_str(), std::fstream::binary);\n\t\tif (!key_file_in) {\n\t\t\t// TODO: include key name in error message\n\t\t\tthrow Error(\"Unable to open key file - have you unlocked/initialized this repository yet?\");\n\t\t}\n\t\tkey_file.load(key_file_in);\n\t}\n}\n\nstatic bool decrypt_repo_key (Key_file& key_file, const char* key_name, uint32_t key_version, const std::vector<std::string>& secret_keys, const std::string& keys_path)\n{\n\tstd::exception_ptr gpg_error;\n\n\tfor (std::vector<std::string>::const_iterator seckey(secret_keys.begin()); seckey != secret_keys.end(); ++seckey) {\n\t\tstd::ostringstream\t\tpath_builder;\n\t\tpath_builder << keys_path << '/' << (key_name ? key_name : \"default\") << '/' << key_version << '/' << *seckey << \".gpg\";\n\t\tstd::string\t\t\tpath(path_builder.str());\n\t\tif (access(path.c_str(), F_OK) == 0) {\n\t\t\tstd::stringstream\tdecrypted_contents;\n\t\t\ttry {\n\t\t\t\tgpg_decrypt_from_file(path, decrypted_contents);\n\t\t\t} catch (const Gpg_error&) {\n\t\t\t\tgpg_error = std::current_exception();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tKey_file\t\tthis_version_key_file;\n\t\t\tthis_version_key_file.load(decrypted_contents);\n\t\t\tconst Key_file::Entry*\tthis_version_entry = this_version_key_file.get(key_version);\n\t\t\tif (!this_version_entry) {\n\t\t\t\tthrow Error(\"GPG-encrypted keyfile is malformed because it does not contain expected key version\");\n\t\t\t}\n\t\t\tif (!same_key_name(key_name, this_version_key_file.get_key_name())) {\n\t\t\t\tthrow Error(\"GPG-encrypted keyfile is malformed because it does not contain expected key name\");\n\t\t\t}\n\t\t\tkey_file.set_key_name(key_name);\n\t\t\tkey_file.add(*this_version_entry);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tif (gpg_error) {\n\t\tstd::rethrow_exception(gpg_error);\n\t}\n\n\treturn false;\n}\n\nstatic bool decrypt_repo_keys (std::vector<Key_file>& key_files, uint32_t key_version, const std::vector<std::string>& secret_keys, const std::string& keys_path)\n{\n\tbool\t\t\t\tsuccessful = false;\n\tstd::vector<std::string>\tdirents;\n\n\tif (access(keys_path.c_str(), F_OK) == 0) {\n\t\tdirents = get_directory_contents(keys_path.c_str());\n\t}\n\n\tfor (std::vector<std::string>::const_iterator dirent(dirents.begin()); dirent != dirents.end(); ++dirent) {\n\t\tconst char*\t\tkey_name = 0;\n\t\tif (*dirent != \"default\") {\n\t\t\tif (!validate_key_name(dirent->c_str())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkey_name = dirent->c_str();\n\t\t}\n\n\t\tKey_file\tkey_file;\n\t\tif (decrypt_repo_key(key_file, key_name, key_version, secret_keys, keys_path)) {\n\t\t\tkey_files.push_back(key_file);\n\t\t\tsuccessful = true;\n\t\t}\n\t}\n\treturn successful;\n}\n\nstatic void encrypt_repo_key (const char* key_name, const Key_file::Entry& key, const std::vector<std::pair<std::string, bool> >& collab_keys, const std::string& keys_path, std::vector<std::string>* new_files)\n{\n\tstd::string\tkey_file_data;\n\t{\n\t\tKey_file this_version_key_file;\n\t\tthis_version_key_file.set_key_name(key_name);\n\t\tthis_version_key_file.add(key);\n\t\tkey_file_data = this_version_key_file.store_to_string();\n\t}\n\n\tfor (std::vector<std::pair<std::string, bool> >::const_iterator collab(collab_keys.begin()); collab != collab_keys.end(); ++collab) {\n\t\tconst std::string&\tfingerprint(collab->first);\n\t\tconst bool\t\tkey_is_trusted(collab->second);\n\t\tstd::ostringstream\tpath_builder;\n\t\tpath_builder << keys_path << '/' << (key_name ? key_name : \"default\") << '/' << key.version << '/' << fingerprint << \".gpg\";\n\t\tstd::string\t\tpath(path_builder.str());\n\n\t\tif (access(path.c_str(), F_OK) == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tmkdir_parent(path);\n\t\tgpg_encrypt_to_file(path, fingerprint, key_is_trusted, key_file_data.data(), key_file_data.size());\n\t\tnew_files->push_back(path);\n\t}\n}\n\nstatic int parse_plumbing_options (const char** key_name, const char** key_file, int argc, const char** argv)\n{\n\tOptions_list\toptions;\n\toptions.push_back(Option_def(\"-k\", key_name));\n\toptions.push_back(Option_def(\"--key-name\", key_name));\n\toptions.push_back(Option_def(\"--key-file\", key_file));\n\n\treturn parse_options(options, argc, argv);\n}\n\n// Encrypt contents of stdin and write to stdout\nint clean (int argc, const char** argv)\n{\n\tconst char*\t\tkey_name = 0;\n\tconst char*\t\tkey_path = 0;\n\tconst char*\t\tlegacy_key_path = 0;\n\n\tint\t\t\targi = parse_plumbing_options(&key_name, &key_path, argc, argv);\n\tif (argc - argi == 0) {\n\t} else if (!key_name && !key_path && argc - argi == 1) { // Deprecated - for compatibility with pre-0.4\n\t\tlegacy_key_path = argv[argi];\n\t} else {\n\t\tstd::clog << \"Usage: git-crypt clean [--key-name=NAME] [--key-file=PATH]\" << std::endl;\n\t\treturn 2;\n\t}\n\tKey_file\t\tkey_file;\n\tload_key(key_file, key_name, key_path, legacy_key_path);\n\n\tconst Key_file::Entry*\tkey = key_file.get_latest();\n\tif (!key) {\n\t\tstd::clog << \"git-crypt: error: key file is empty\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// Read the entire file\n\n\tHmac_sha1_state\thmac(key->hmac_key, HMAC_KEY_LEN); // Calculate the file's SHA1 HMAC as we go\n\tuint64_t\t\tfile_size = 0;\t// Keep track of the length, make sure it doesn't get too big\n\tstd::string\t\tfile_contents;\t// First 8MB or so of the file go here\n\ttemp_fstream\t\ttemp_file;\t// The rest of the file spills into a temporary file on disk\n\ttemp_file.exceptions(std::fstream::badbit);\n\n\tchar\t\t\tbuffer[1024];\n\n\twhile (std::cin && file_size < Aes_ctr_encryptor::MAX_CRYPT_BYTES) {\n\t\tstd::cin.read(buffer, sizeof(buffer));\n\n\t\tconst size_t\tbytes_read = std::cin.gcount();\n\n\t\thmac.add(reinterpret_cast<unsigned char*>(buffer), bytes_read);\n\t\tfile_size += bytes_read;\n\n\t\tif (file_size <= 8388608) {\n\t\t\tfile_contents.append(buffer, bytes_read);\n\t\t} else {\n\t\t\tif (!temp_file.is_open()) {\n\t\t\t\ttemp_file.open(std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::app);\n\t\t\t}\n\t\t\ttemp_file.write(buffer, bytes_read);\n\t\t}\n\t}\n\n\t// Make sure the file isn't so large we'll overflow the counter value (which would doom security)\n\tif (file_size >= Aes_ctr_encryptor::MAX_CRYPT_BYTES) {\n\t\tstd::clog << \"git-crypt: error: file too long to encrypt securely\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// We use an HMAC of the file as the encryption nonce (IV) for CTR mode.\n\t// By using a hash of the file we ensure that the encryption is\n\t// deterministic so git doesn't think the file has changed when it really\n\t// hasn't.  CTR mode with a synthetic IV is provably semantically secure\n\t// under deterministic CPA as long as the synthetic IV is derived from a\n\t// secure PRF applied to the message.  Since HMAC-SHA1 is a secure PRF, this\n\t// encryption scheme is semantically secure under deterministic CPA.\n\t// \n\t// Informally, consider that if a file changes just a tiny bit, the IV will\n\t// be completely different, resulting in a completely different ciphertext\n\t// that leaks no information about the similarities of the plaintexts.  Also,\n\t// since we're using the output from a secure hash function plus a counter\n\t// as the input to our block cipher, we should never have a situation where\n\t// two different plaintext blocks get encrypted with the same CTR value.  A\n\t// nonce will be reused only if the entire file is the same, which leaks no\n\t// information except that the files are the same.\n\t//\n\t// To prevent an attacker from building a dictionary of hash values and then\n\t// looking up the nonce (which must be stored in the clear to allow for\n\t// decryption), we use an HMAC as opposed to a straight hash.\n\n\t// Note: Hmac_sha1_state::LEN >= Aes_ctr_encryptor::NONCE_LEN\n\n\tunsigned char\t\tdigest[Hmac_sha1_state::LEN];\n\thmac.get(digest);\n\n\t// Write a header that...\n\tstd::cout.write(\"\\0GITCRYPT\\0\", 10); // ...identifies this as an encrypted file\n\tstd::cout.write(reinterpret_cast<char*>(digest), Aes_ctr_encryptor::NONCE_LEN); // ...includes the nonce\n\n\t// Now encrypt the file and write to stdout\n\tAes_ctr_encryptor\taes(key->aes_key, digest);\n\n\t// First read from the in-memory copy\n\tconst unsigned char*\tfile_data = reinterpret_cast<const unsigned char*>(file_contents.data());\n\tsize_t\t\t\tfile_data_len = file_contents.size();\n\twhile (file_data_len > 0) {\n\t\tconst size_t\tbuffer_len = std::min(sizeof(buffer), file_data_len);\n\t\taes.process(file_data, reinterpret_cast<unsigned char*>(buffer), buffer_len);\n\t\tstd::cout.write(buffer, buffer_len);\n\t\tfile_data += buffer_len;\n\t\tfile_data_len -= buffer_len;\n\t}\n\n\t// Then read from the temporary file if applicable\n\tif (temp_file.is_open()) {\n\t\ttemp_file.seekg(0);\n\t\twhile (temp_file.peek() != -1) {\n\t\t\ttemp_file.read(buffer, sizeof(buffer));\n\n\t\t\tconst size_t\tbuffer_len = temp_file.gcount();\n\n\t\t\taes.process(reinterpret_cast<unsigned char*>(buffer),\n\t\t\t            reinterpret_cast<unsigned char*>(buffer),\n\t\t\t            buffer_len);\n\t\t\tstd::cout.write(buffer, buffer_len);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nstatic int decrypt_file_to_stdout (const Key_file& key_file, const unsigned char* header, std::istream& in)\n{\n\tconst unsigned char*\tnonce = header + 10;\n\tuint32_t\t\tkey_version = 0; // TODO: get the version from the file header\n\n\tconst Key_file::Entry*\tkey = key_file.get(key_version);\n\tif (!key) {\n\t\tstd::clog << \"git-crypt: error: key version \" << key_version << \" not available - please unlock with the latest version of the key.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tAes_ctr_decryptor\taes(key->aes_key, nonce);\n\tHmac_sha1_state\t\thmac(key->hmac_key, HMAC_KEY_LEN);\n\twhile (in) {\n\t\tunsigned char\tbuffer[1024];\n\t\tin.read(reinterpret_cast<char*>(buffer), sizeof(buffer));\n\t\taes.process(buffer, buffer, in.gcount());\n\t\thmac.add(buffer, in.gcount());\n\t\tstd::cout.write(reinterpret_cast<char*>(buffer), in.gcount());\n\t}\n\n\tunsigned char\t\tdigest[Hmac_sha1_state::LEN];\n\thmac.get(digest);\n\tif (!leakless_equals(digest, nonce, Aes_ctr_decryptor::NONCE_LEN)) {\n\t\tstd::clog << \"git-crypt: error: encrypted file has been tampered with!\" << std::endl;\n\t\t// Although we've already written the tampered file to stdout, exiting\n\t\t// with a non-zero status will tell git the file has not been filtered,\n\t\t// so git will not replace it.\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\n// Decrypt contents of stdin and write to stdout\nint smudge (int argc, const char** argv)\n{\n\tconst char*\t\tkey_name = 0;\n\tconst char*\t\tkey_path = 0;\n\tconst char*\t\tlegacy_key_path = 0;\n\n\tint\t\t\targi = parse_plumbing_options(&key_name, &key_path, argc, argv);\n\tif (argc - argi == 0) {\n\t} else if (!key_name && !key_path && argc - argi == 1) { // Deprecated - for compatibility with pre-0.4\n\t\tlegacy_key_path = argv[argi];\n\t} else {\n\t\tstd::clog << \"Usage: git-crypt smudge [--key-name=NAME] [--key-file=PATH]\" << std::endl;\n\t\treturn 2;\n\t}\n\tKey_file\t\tkey_file;\n\tload_key(key_file, key_name, key_path, legacy_key_path);\n\n\t// Read the header to get the nonce and make sure it's actually encrypted\n\tunsigned char\t\theader[10 + Aes_ctr_decryptor::NONCE_LEN];\n\tstd::cin.read(reinterpret_cast<char*>(header), sizeof(header));\n\tif (std::cin.gcount() != sizeof(header) || std::memcmp(header, \"\\0GITCRYPT\\0\", 10) != 0) {\n\t\t// File not encrypted - just copy it out to stdout\n\t\tstd::clog << \"git-crypt: Warning: file not encrypted\" << std::endl;\n\t\tstd::clog << \"git-crypt: Run 'git-crypt status' to make sure all files are properly encrypted.\" << std::endl;\n\t\tstd::clog << \"git-crypt: If 'git-crypt status' reports no problems, then an older version of\" << std::endl;\n\t\tstd::clog << \"git-crypt: this file may be unencrypted in the repository's history.  If this\" << std::endl;\n\t\tstd::clog << \"git-crypt: file contains sensitive information, you can use 'git filter-branch'\" << std::endl;\n\t\tstd::clog << \"git-crypt: to remove its old versions from the history.\" << std::endl;\n\t\tstd::cout.write(reinterpret_cast<char*>(header), std::cin.gcount()); // include the bytes which we already read\n\t\tstd::cout << std::cin.rdbuf();\n\t\treturn 0;\n\t}\n\n\treturn decrypt_file_to_stdout(key_file, header, std::cin);\n}\n\nint diff (int argc, const char** argv)\n{\n\tconst char*\t\tkey_name = 0;\n\tconst char*\t\tkey_path = 0;\n\tconst char*\t\tfilename = 0;\n\tconst char*\t\tlegacy_key_path = 0;\n\n\tint\t\t\targi = parse_plumbing_options(&key_name, &key_path, argc, argv);\n\tif (argc - argi == 1) {\n\t\tfilename = argv[argi];\n\t} else if (!key_name && !key_path && argc - argi == 2) { // Deprecated - for compatibility with pre-0.4\n\t\tlegacy_key_path = argv[argi];\n\t\tfilename = argv[argi + 1];\n\t} else {\n\t\tstd::clog << \"Usage: git-crypt diff [--key-name=NAME] [--key-file=PATH] FILENAME\" << std::endl;\n\t\treturn 2;\n\t}\n\tKey_file\t\tkey_file;\n\tload_key(key_file, key_name, key_path, legacy_key_path);\n\n\t// Open the file\n\tstd::ifstream\t\tin(filename, std::fstream::binary);\n\tif (!in) {\n\t\tstd::clog << \"git-crypt: \" << filename << \": unable to open for reading\" << std::endl;\n\t\treturn 1;\n\t}\n\tin.exceptions(std::fstream::badbit);\n\n\t// Read the header to get the nonce and determine if it's actually encrypted\n\tunsigned char\t\theader[10 + Aes_ctr_decryptor::NONCE_LEN];\n\tin.read(reinterpret_cast<char*>(header), sizeof(header));\n\tif (in.gcount() != sizeof(header) || std::memcmp(header, \"\\0GITCRYPT\\0\", 10) != 0) {\n\t\t// File not encrypted - just copy it out to stdout\n\t\tstd::cout.write(reinterpret_cast<char*>(header), in.gcount()); // include the bytes which we already read\n\t\tstd::cout << in.rdbuf();\n\t\treturn 0;\n\t}\n\n\t// Go ahead and decrypt it\n\treturn decrypt_file_to_stdout(key_file, header, in);\n}\n\nvoid help_init (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt init [OPTIONS]\" << std::endl;\n\tout << std::endl;\n\tout << \"    -k, --key-name KEYNAME      Initialize the given key, instead of the default\" << std::endl;\n\tout << std::endl;\n}\n\nint init (int argc, const char** argv)\n{\n\tconst char*\tkey_name = 0;\n\tOptions_list\toptions;\n\toptions.push_back(Option_def(\"-k\", &key_name));\n\toptions.push_back(Option_def(\"--key-name\", &key_name));\n\n\tint\t\targi = parse_options(options, argc, argv);\n\n\tif (!key_name && argc - argi == 1) {\n\t\tstd::clog << \"Warning: 'git-crypt init' with a key file is deprecated as of git-crypt 0.4\" << std::endl;\n\t\tstd::clog << \"and will be removed in a future release. Please get in the habit of using\" << std::endl;\n\t\tstd::clog << \"'git-crypt unlock KEYFILE' instead.\" << std::endl;\n\t\treturn unlock(argc, argv);\n\t}\n\tif (argc - argi != 0) {\n\t\tstd::clog << \"Error: git-crypt init takes no arguments\" << std::endl;\n\t\thelp_init(std::clog);\n\t\treturn 2;\n\t}\n\n\tif (key_name) {\n\t\tvalidate_key_name_or_throw(key_name);\n\t}\n\n\tstd::string\t\tinternal_key_path(get_internal_key_path(key_name));\n\tif (access(internal_key_path.c_str(), F_OK) == 0) {\n\t\t// TODO: add a -f option to reinitialize the repo anyways (this should probably imply a refresh)\n\t\t// TODO: include key_name in error message\n\t\tstd::clog << \"Error: this repository has already been initialized with git-crypt.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// 1. Generate a key and install it\n\tstd::clog << \"Generating key...\" << std::endl;\n\tKey_file\t\tkey_file;\n\tkey_file.set_key_name(key_name);\n\tkey_file.generate();\n\n\tmkdir_parent(internal_key_path);\n\tif (!key_file.store_to_file(internal_key_path.c_str())) {\n\t\tstd::clog << \"Error: \" << internal_key_path << \": unable to write key file\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// 2. Configure git for git-crypt\n\tconfigure_git_filters(key_name);\n\n\treturn 0;\n}\n\nvoid help_unlock (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt unlock\" << std::endl;\n\tout << \"   or: git-crypt unlock KEY_FILE ...\" << std::endl;\n}\nint unlock (int argc, const char** argv)\n{\n\t// 1. Make sure working directory is clean (ignoring untracked files)\n\t// We do this because we check out files later, and we don't want the\n\t// user to lose any changes.  (TODO: only care if encrypted files are\n\t// modified, since we only check out encrypted files)\n\n\t// Running 'git status' also serves as a check that the Git repo is accessible.\n\n\tstd::stringstream\tstatus_output;\n\tget_git_status(status_output);\n\tif (status_output.peek() != -1) {\n\t\tstd::clog << \"Error: Working directory not clean.\" << std::endl;\n\t\tstd::clog << \"Please commit your changes or 'git stash' them before running 'git-crypt unlock'.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// 2. Load the key(s)\n\tstd::vector<Key_file>\tkey_files;\n\tif (argc > 0) {\n\t\t// Read from the symmetric key file(s)\n\n\t\tfor (int argi = 0; argi < argc; ++argi) {\n\t\t\tconst char*\tsymmetric_key_file = argv[argi];\n\t\t\tKey_file\tkey_file;\n\n\t\t\ttry {\n\t\t\t\tif (std::strcmp(symmetric_key_file, \"-\") == 0) {\n\t\t\t\t\tkey_file.load(std::cin);\n\t\t\t\t} else {\n\t\t\t\t\tif (!key_file.load_from_file(symmetric_key_file)) {\n\t\t\t\t\t\tstd::clog << \"Error: \" << symmetric_key_file << \": unable to read key file\" << std::endl;\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Key_file::Incompatible) {\n\t\t\t\tstd::clog << \"Error: \" << symmetric_key_file << \" is in an incompatible format\" << std::endl;\n\t\t\t\tstd::clog << \"Please upgrade to a newer version of git-crypt.\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t} catch (Key_file::Malformed) {\n\t\t\t\tstd::clog << \"Error: \" << symmetric_key_file << \": not a valid git-crypt key file\" << std::endl;\n\t\t\t\tstd::clog << \"If this key was created prior to git-crypt 0.4, you need to migrate it\" << std::endl;\n\t\t\t\tstd::clog << \"by running 'git-crypt migrate-key /path/to/old_key /path/to/migrated_key'.\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tkey_files.push_back(key_file);\n\t\t}\n\t} else {\n\t\t// Decrypt GPG key from root of repo\n\t\tstd::string\t\t\trepo_keys_path(get_repo_keys_path());\n\t\tstd::vector<std::string>\tgpg_secret_keys(gpg_list_secret_keys());\n\t\t// TODO: command-line option to specify the precise secret key to use\n\t\t// TODO: don't hard code key version 0 here - instead, determine the most recent version and try to decrypt that, or decrypt all versions if command-line option specified\n\t\t// TODO: command line option to only unlock specific key instead of all of them\n\t\t// TODO: avoid decrypting repo keys which are already unlocked in the .git directory\n\t\tif (!decrypt_repo_keys(key_files, 0, gpg_secret_keys, repo_keys_path)) {\n\t\t\tstd::clog << \"Error: no GPG secret key available to unlock this repository.\" << std::endl;\n\t\t\tstd::clog << \"To unlock with a shared symmetric key instead, specify the path to the symmetric key as an argument to 'git-crypt unlock'.\" << std::endl;\n\t\t\t// TODO std::clog << \"To see a list of GPG keys authorized to unlock this repository, run 'git-crypt ls-gpg-users'.\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\n\t// 3. Install the key(s) and configure the git filters\n\tstd::vector<std::string>\tencrypted_files;\n\tfor (std::vector<Key_file>::iterator key_file(key_files.begin()); key_file != key_files.end(); ++key_file) {\n\t\tstd::string\t\tinternal_key_path(get_internal_key_path(key_file->get_key_name()));\n\t\t// TODO: croak if internal_key_path already exists???\n\t\tmkdir_parent(internal_key_path);\n\t\tif (!key_file->store_to_file(internal_key_path.c_str())) {\n\t\t\tstd::clog << \"Error: \" << internal_key_path << \": unable to write key file\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tconfigure_git_filters(key_file->get_key_name());\n\t\tget_encrypted_files(encrypted_files, key_file->get_key_name());\n\t}\n\n\t// 4. Check out the files that are currently encrypted.\n\t// Git won't check out a file if its mtime hasn't changed, so touch every file first.\n\tfor (std::vector<std::string>::const_iterator file(encrypted_files.begin()); file != encrypted_files.end(); ++file) {\n\t\ttouch_file(*file);\n\t}\n\tif (!git_checkout(encrypted_files)) {\n\t\tstd::clog << \"Error: 'git checkout' failed\" << std::endl;\n\t\tstd::clog << \"git-crypt has been set up but existing encrypted files have not been decrypted\" << std::endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid help_lock (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt lock [OPTIONS]\" << std::endl;\n\tout << std::endl;\n\tout << \"    -a, --all                Lock all keys, instead of just the default\" << std::endl;\n\tout << \"    -k, --key-name KEYNAME   Lock the given key, instead of the default\" << std::endl;\n\tout << \"    -f, --force              Lock even if unclean (you may lose uncommited work)\" << std::endl;\n\tout << std::endl;\n}\nint lock (int argc, const char** argv)\n{\n\tconst char*\tkey_name = 0;\n\tbool\t\tall_keys = false;\n\tbool\t\tforce = false;\n\tOptions_list\toptions;\n\toptions.push_back(Option_def(\"-k\", &key_name));\n\toptions.push_back(Option_def(\"--key-name\", &key_name));\n\toptions.push_back(Option_def(\"-a\", &all_keys));\n\toptions.push_back(Option_def(\"--all\", &all_keys));\n\toptions.push_back(Option_def(\"-f\", &force));\n\toptions.push_back(Option_def(\"--force\", &force));\n\n\tint\t\t\targi = parse_options(options, argc, argv);\n\n\tif (argc - argi != 0) {\n\t\tstd::clog << \"Error: git-crypt lock takes no arguments\" << std::endl;\n\t\thelp_lock(std::clog);\n\t\treturn 2;\n\t}\n\n\tif (all_keys && key_name) {\n\t\tstd::clog << \"Error: -k and --all options are mutually exclusive\" << std::endl;\n\t\treturn 2;\n\t}\n\n\t// 1. Make sure working directory is clean (ignoring untracked files)\n\t// We do this because we check out files later, and we don't want the\n\t// user to lose any changes.  (TODO: only care if encrypted files are\n\t// modified, since we only check out encrypted files)\n\n\t// Running 'git status' also serves as a check that the Git repo is accessible.\n\n\tstd::stringstream\tstatus_output;\n\tget_git_status(status_output);\n\tif (!force && status_output.peek() != -1) {\n\t\tstd::clog << \"Error: Working directory not clean.\" << std::endl;\n\t\tstd::clog << \"Please commit your changes or 'git stash' them before running 'git-crypt lock'.\" << std::endl;\n\t\tstd::clog << \"Or, use 'git-crypt lock --force' and possibly lose uncommitted changes.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// 2. deconfigure the git filters and remove decrypted keys\n\tstd::vector<std::string>\tencrypted_files;\n\tif (all_keys) {\n\t\t// deconfigure for all keys\n\t\tstd::vector<std::string> dirents = get_directory_contents(get_internal_keys_path().c_str());\n\n\t\tfor (std::vector<std::string>::const_iterator dirent(dirents.begin()); dirent != dirents.end(); ++dirent) {\n\t\t\tconst char* this_key_name = (*dirent == \"default\" ? 0 : dirent->c_str());\n\t\t\tremove_file(get_internal_key_path(this_key_name));\n\t\t\tdeconfigure_git_filters(this_key_name);\n\t\t\tget_encrypted_files(encrypted_files, this_key_name);\n\t\t}\n\t} else {\n\t\t// just handle the given key\n\t\tstd::string\tinternal_key_path(get_internal_key_path(key_name));\n\t\tif (access(internal_key_path.c_str(), F_OK) == -1 && errno == ENOENT) {\n\t\t\tstd::clog << \"Error: this repository is already locked\";\n\t\t\tif (key_name) {\n\t\t\t\tstd::clog << \" with key '\" << key_name << \"'\";\n\t\t\t}\n\t\t\tstd::clog << \".\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tremove_file(internal_key_path);\n\t\tdeconfigure_git_filters(key_name);\n\t\tget_encrypted_files(encrypted_files, key_name);\n\t}\n\n\t// 3. Check out the files that are currently decrypted but should be encrypted.\n\t// Git won't check out a file if its mtime hasn't changed, so touch every file first.\n\tfor (std::vector<std::string>::const_iterator file(encrypted_files.begin()); file != encrypted_files.end(); ++file) {\n\t\ttouch_file(*file);\n\t}\n\tif (!git_checkout(encrypted_files)) {\n\t\tstd::clog << \"Error: 'git checkout' failed\" << std::endl;\n\t\tstd::clog << \"git-crypt has been locked up but existing decrypted files have not been encrypted\" << std::endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid help_add_gpg_user (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt add-gpg-user [OPTIONS] GPG_USER_ID ...\" << std::endl;\n\tout << std::endl;\n\tout << \"    -k, --key-name KEYNAME      Add GPG user to given key, instead of default\" << std::endl;\n\tout << \"    -n, --no-commit             Don't automatically commit\" << std::endl;\n\tout << \"    --trusted                   Assume the GPG user IDs are trusted\" << std::endl;\n\tout << std::endl;\n}\nint add_gpg_user (int argc, const char** argv)\n{\n\tconst char*\t\tkey_name = 0;\n\tbool\t\t\tno_commit = false;\n\tbool\t\t\ttrusted = false;\n\tOptions_list\t\toptions;\n\toptions.push_back(Option_def(\"-k\", &key_name));\n\toptions.push_back(Option_def(\"--key-name\", &key_name));\n\toptions.push_back(Option_def(\"-n\", &no_commit));\n\toptions.push_back(Option_def(\"--no-commit\", &no_commit));\n\toptions.push_back(Option_def(\"--trusted\", &trusted));\n\n\tint\t\t\targi = parse_options(options, argc, argv);\n\tif (argc - argi == 0) {\n\t\tstd::clog << \"Error: no GPG user ID specified\" << std::endl;\n\t\thelp_add_gpg_user(std::clog);\n\t\treturn 2;\n\t}\n\n\t// build a list of key fingerprints, and whether the key is trusted, for every collaborator specified on the command line\n\tstd::vector<std::pair<std::string, bool> >\tcollab_keys;\n\n\tfor (int i = argi; i < argc; ++i) {\n\t\tstd::vector<std::string> keys(gpg_lookup_key(argv[i]));\n\t\tif (keys.empty()) {\n\t\t\tstd::clog << \"Error: public key for '\" << argv[i] << \"' not found in your GPG keyring\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (keys.size() > 1) {\n\t\t\tstd::clog << \"Error: more than one public key matches '\" << argv[i] << \"' - please be more specific\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tconst bool is_full_fingerprint(std::strncmp(argv[i], \"0x\", 2) == 0 && std::strlen(argv[i]) == 42);\n\t\tcollab_keys.push_back(std::make_pair(keys[0], trusted || is_full_fingerprint));\n\t}\n\n\t// TODO: have a retroactive option to grant access to all key versions, not just the most recent\n\tKey_file\t\t\tkey_file;\n\tload_key(key_file, key_name);\n\tconst Key_file::Entry*\t\tkey = key_file.get_latest();\n\tif (!key) {\n\t\tstd::clog << \"Error: key file is empty\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tconst std::string\t\tstate_path(get_repo_state_path());\n\tstd::vector<std::string>\tnew_files;\n\n\tencrypt_repo_key(key_name, *key, collab_keys, get_repo_keys_path(state_path), &new_files);\n\n\t// Add a .gitatributes file to the repo state directory to prevent files in it from being encrypted.\n\tconst std::string\t\tstate_gitattributes_path(state_path + \"/.gitattributes\");\n\tif (access(state_gitattributes_path.c_str(), F_OK) != 0) {\n\t\tstd::ofstream\t\tstate_gitattributes_file(state_gitattributes_path.c_str());\n\t\t//                          |--------------------------------------------------------------------------------| 80 chars\n\t\tstate_gitattributes_file << \"# Do not edit this file.  To specify the files to encrypt, create your own\\n\";\n\t\tstate_gitattributes_file << \"# .gitattributes file in the directory where your files are.\\n\";\n\t\tstate_gitattributes_file << \"* !filter !diff\\n\";\n\t\tstate_gitattributes_file << \"*.gpg binary\\n\";\n\t\tstate_gitattributes_file.close();\n\t\tif (!state_gitattributes_file) {\n\t\t\tstd::clog << \"Error: unable to write \" << state_gitattributes_path << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tnew_files.push_back(state_gitattributes_path);\n\t}\n\n\t// add/commit the new files\n\tif (!new_files.empty()) {\n\t\t// git add NEW_FILE ...\n\t\tstd::vector<std::string>\tcommand;\n\t\tcommand.push_back(\"git\");\n\t\tcommand.push_back(\"add\");\n\t\tcommand.push_back(\"--\");\n\t\tcommand.insert(command.end(), new_files.begin(), new_files.end());\n\t\tif (!successful_exit(exec_command(command))) {\n\t\t\tstd::clog << \"Error: 'git add' failed\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\t// git commit ...\n\t\tif (!no_commit) {\n\t\t\t// TODO: include key_name in commit message\n\t\t\tstd::ostringstream\tcommit_message_builder;\n\t\t\tcommit_message_builder << \"Add \" << collab_keys.size() << \" git-crypt collaborator\" << (collab_keys.size() != 1 ? \"s\" : \"\") << \"\\n\\nNew collaborators:\\n\\n\";\n\t\t\tfor (std::vector<std::pair<std::string, bool> >::const_iterator collab(collab_keys.begin()); collab != collab_keys.end(); ++collab) {\n\t\t\t\tcommit_message_builder << \"    \" << collab->first << '\\n';\n\t\t\t\tcommit_message_builder << \"        \" << gpg_get_uid(collab->first) << '\\n';\n\t\t\t}\n\n\t\t\t// git commit -m MESSAGE NEW_FILE ...\n\t\t\tcommand.clear();\n\t\t\tcommand.push_back(\"git\");\n\t\t\tcommand.push_back(\"commit\");\n\t\t\tcommand.push_back(\"-m\");\n\t\t\tcommand.push_back(commit_message_builder.str());\n\t\t\tcommand.push_back(\"--\");\n\t\t\tcommand.insert(command.end(), new_files.begin(), new_files.end());\n\n\t\t\tif (!successful_exit(exec_command(command))) {\n\t\t\t\tstd::clog << \"Error: 'git commit' failed\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid help_rm_gpg_user (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt rm-gpg-user [OPTIONS] GPG_USER_ID ...\" << std::endl;\n\tout << std::endl;\n\tout << \"    -k, --key-name KEYNAME      Remove user from given key, instead of default\" << std::endl;\n\tout << \"    -n, --no-commit             Don't automatically commit\" << std::endl;\n\tout << std::endl;\n}\nint rm_gpg_user (int argc, const char** argv) // TODO\n{\n\tstd::clog << \"Error: rm-gpg-user is not yet implemented.\" << std::endl;\n\treturn 1;\n}\n\nvoid help_ls_gpg_users (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt ls-gpg-users\" << std::endl;\n}\nint ls_gpg_users (int argc, const char** argv) // TODO\n{\n\t// Sketch:\n\t// Scan the sub-directories in .git-crypt/keys, outputting something like this:\n\t// ====\n\t// Key version 0:\n\t//  0x143DE9B3F7316900 Andrew Ayer <andrew@example.com>\n\t//  0x4E386D9C9C61702F ???\n\t// Key version 1:\n\t//  0x143DE9B3F7316900 Andrew Ayer <andrew@example.com>\n\t//  0x1727274463D27F40 John Smith <smith@example.com>\n\t//  0x4E386D9C9C61702F ???\n\t// ====\n\t// To resolve a long hex ID, use a command like this:\n\t//  gpg --options /dev/null --fixed-list-mode --batch --with-colons --list-keys 0x143DE9B3F7316900\n\n\tstd::clog << \"Error: ls-gpg-users is not yet implemented.\" << std::endl;\n\treturn 1;\n}\n\nvoid help_export_key (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt export-key [OPTIONS] FILENAME\" << std::endl;\n\tout << std::endl;\n\tout << \"    -k, --key-name KEYNAME      Export the given key, instead of the default\" << std::endl;\n\tout << std::endl;\n\tout << \"When FILENAME is -, export to standard out.\" << std::endl;\n}\nint export_key (int argc, const char** argv)\n{\n\t// TODO: provide options to export only certain key versions\n\tconst char*\t\tkey_name = 0;\n\tOptions_list\t\toptions;\n\toptions.push_back(Option_def(\"-k\", &key_name));\n\toptions.push_back(Option_def(\"--key-name\", &key_name));\n\n\tint\t\t\targi = parse_options(options, argc, argv);\n\n\tif (argc - argi != 1) {\n\t\tstd::clog << \"Error: no filename specified\" << std::endl;\n\t\thelp_export_key(std::clog);\n\t\treturn 2;\n\t}\n\n\tKey_file\t\tkey_file;\n\tload_key(key_file, key_name);\n\n\tconst char*\t\tout_file_name = argv[argi];\n\n\tif (std::strcmp(out_file_name, \"-\") == 0) {\n\t\tkey_file.store(std::cout);\n\t} else {\n\t\tif (!key_file.store_to_file(out_file_name)) {\n\t\t\tstd::clog << \"Error: \" << out_file_name << \": unable to write key file\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid help_keygen (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt keygen FILENAME\" << std::endl;\n\tout << std::endl;\n\tout << \"When FILENAME is -, write to standard out.\" << std::endl;\n}\nint keygen (int argc, const char** argv)\n{\n\tif (argc != 1) {\n\t\tstd::clog << \"Error: no filename specified\" << std::endl;\n\t\thelp_keygen(std::clog);\n\t\treturn 2;\n\t}\n\n\tconst char*\t\tkey_file_name = argv[0];\n\n\tif (std::strcmp(key_file_name, \"-\") != 0 && access(key_file_name, F_OK) == 0) {\n\t\tstd::clog << key_file_name << \": File already exists\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::clog << \"Generating key...\" << std::endl;\n\tKey_file\t\tkey_file;\n\tkey_file.generate();\n\n\tif (std::strcmp(key_file_name, \"-\") == 0) {\n\t\tkey_file.store(std::cout);\n\t} else {\n\t\tif (!key_file.store_to_file(key_file_name)) {\n\t\t\tstd::clog << \"Error: \" << key_file_name << \": unable to write key file\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid help_migrate_key (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt migrate-key OLDFILENAME NEWFILENAME\" << std::endl;\n\tout << std::endl;\n\tout << \"Use - to read from standard in/write to standard out.\" << std::endl;\n}\nint migrate_key (int argc, const char** argv)\n{\n\tif (argc != 2) {\n\t\tstd::clog << \"Error: filenames not specified\" << std::endl;\n\t\thelp_migrate_key(std::clog);\n\t\treturn 2;\n\t}\n\n\tconst char*\t\tkey_file_name = argv[0];\n\tconst char*\t\tnew_key_file_name = argv[1];\n\tKey_file\t\tkey_file;\n\n\ttry {\n\t\tif (std::strcmp(key_file_name, \"-\") == 0) {\n\t\t\tkey_file.load_legacy(std::cin);\n\t\t} else {\n\t\t\tstd::ifstream\tin(key_file_name, std::fstream::binary);\n\t\t\tif (!in) {\n\t\t\t\tstd::clog << \"Error: \" << key_file_name << \": unable to open for reading\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tkey_file.load_legacy(in);\n\t\t}\n\n\t\tif (std::strcmp(new_key_file_name, \"-\") == 0) {\n\t\t\tkey_file.store(std::cout);\n\t\t} else {\n\t\t\tif (!key_file.store_to_file(new_key_file_name)) {\n\t\t\t\tstd::clog << \"Error: \" << new_key_file_name << \": unable to write key file\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t} catch (Key_file::Malformed) {\n\t\tstd::clog << \"Error: \" << key_file_name << \": not a valid legacy git-crypt key file\" << std::endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid help_refresh (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt refresh\" << std::endl;\n}\nint refresh (int argc, const char** argv) // TODO: do a force checkout, much like in unlock\n{\n\tstd::clog << \"Error: refresh is not yet implemented.\" << std::endl;\n\treturn 1;\n}\n\nvoid help_status (std::ostream& out)\n{\n\t//     |--------------------------------------------------------------------------------| 80 chars\n\tout << \"Usage: git-crypt status [OPTIONS] [FILE ...]\" << std::endl;\n\t//out << \"   or: git-crypt status -r [OPTIONS]\" << std::endl;\n\t//out << \"   or: git-crypt status -f\" << std::endl;\n\tout << std::endl;\n\tout << \"    -e             Show encrypted files only\" << std::endl;\n\tout << \"    -u             Show unencrypted files only\" << std::endl;\n\t//out << \"    -r             Show repository status only\" << std::endl;\n\tout << \"    -f, --fix      Fix problems with the repository\" << std::endl;\n\t//out << \"    -z             Machine-parseable output\" << std::endl;\n\tout << std::endl;\n}\nint status (int argc, const char** argv)\n{\n\t// Usage:\n\t//  git-crypt status -r [-z]\t\t\tShow repo status\n\t//  git-crypt status [-e | -u] [-z] [FILE ...]\tShow encrypted status of files\n\t//  git-crypt status -f\t\t\t\tFix unencrypted blobs\n\n\tbool\t\trepo_status_only = false;\t// -r show repo status only\n\tbool\t\tshow_encrypted_only = false;\t// -e show encrypted files only\n\tbool\t\tshow_unencrypted_only = false;\t// -u show unencrypted files only\n\tbool\t\tfix_problems = false;\t\t// -f fix problems\n\tbool\t\tmachine_output = false;\t\t// -z machine-parseable output\n\n\tOptions_list\toptions;\n\toptions.push_back(Option_def(\"-r\", &repo_status_only));\n\toptions.push_back(Option_def(\"-e\", &show_encrypted_only));\n\toptions.push_back(Option_def(\"-u\", &show_unencrypted_only));\n\toptions.push_back(Option_def(\"-f\", &fix_problems));\n\toptions.push_back(Option_def(\"--fix\", &fix_problems));\n\toptions.push_back(Option_def(\"-z\", &machine_output));\n\n\tint\t\targi = parse_options(options, argc, argv);\n\n\tif (repo_status_only) {\n\t\tif (show_encrypted_only || show_unencrypted_only) {\n\t\t\tstd::clog << \"Error: -e and -u options cannot be used with -r\" << std::endl;\n\t\t\treturn 2;\n\t\t}\n\t\tif (fix_problems) {\n\t\t\tstd::clog << \"Error: -f option cannot be used with -r\" << std::endl;\n\t\t\treturn 2;\n\t\t}\n\t\tif (argc - argi != 0) {\n\t\t\tstd::clog << \"Error: filenames cannot be specified when -r is used\" << std::endl;\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\tif (show_encrypted_only && show_unencrypted_only) {\n\t\tstd::clog << \"Error: -e and -u options are mutually exclusive\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tif (fix_problems && (show_encrypted_only || show_unencrypted_only)) {\n\t\tstd::clog << \"Error: -e and -u options cannot be used with -f\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tif (machine_output) {\n\t\t// TODO: implement machine-parseable output\n\t\tstd::clog << \"Sorry, machine-parseable output is not yet implemented\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tif (argc - argi == 0) {\n\t\t// TODO: check repo status:\n\t\t//\tis it set up for git-crypt?\n\t\t//\twhich keys are unlocked?\n\t\t//\t--> check for filter config (see configure_git_filters()) and corresponding internal key\n\n\t\tif (repo_status_only) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t// git ls-files -cotsz --exclude-standard ...\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(\"git\");\n\tcommand.push_back(\"ls-files\");\n\tcommand.push_back(\"-cotsz\");\n\tcommand.push_back(\"--exclude-standard\");\n\tcommand.push_back(\"--\");\n\tif (argc - argi == 0) {\n\t\tconst std::string\tpath_to_top(get_path_to_top());\n\t\tif (!path_to_top.empty()) {\n\t\t\tcommand.push_back(path_to_top);\n\t\t}\n\t} else {\n\t\tfor (int i = argi; i < argc; ++i) {\n\t\t\tcommand.push_back(argv[i]);\n\t\t}\n\t}\n\n\tstd::stringstream\t\toutput;\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Error(\"'git ls-files' failed - is this a Git repository?\");\n\t}\n\n\t// Output looks like (w/o newlines):\n\t// ? .gitignore\\0\n\t// H 100644 06ec22e5ed0de9280731ef000a10f9c3fbc26338 0     afile\\0\n\n\tstd::vector<std::string>\tfiles;\n\tbool\t\t\t\tattribute_errors = false;\n\tbool\t\t\t\tunencrypted_blob_errors = false;\n\tunsigned int\t\t\tnbr_of_fixed_blobs = 0;\n\tunsigned int\t\t\tnbr_of_fix_errors = 0;\n\n\twhile (output.peek() != -1) {\n\t\tstd::string\t\ttag;\n\t\tstd::string\t\tobject_id;\n\t\tstd::string\t\tfilename;\n\t\toutput >> tag;\n\t\tif (tag != \"?\") {\n\t\t\tstd::string\tmode;\n\t\t\tstd::string\tstage;\n\t\t\toutput >> mode >> object_id >> stage;\n\t\t\tif (!is_git_file_mode(mode)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\toutput >> std::ws;\n\t\tstd::getline(output, filename, '\\0');\n\n\t\t// TODO: get file attributes en masse for efficiency... unfortunately this requires machine-parseable output from git check-attr to be workable, and this is only supported in Git 1.8.5 and above (released 27 Nov 2013)\n\t\tconst std::pair<std::string, std::string> file_attrs(get_file_attributes(filename));\n\n\t\tif (file_attrs.first == \"git-crypt\" || std::strncmp(file_attrs.first.c_str(), \"git-crypt-\", 10) == 0) {\n\t\t\t// File is encrypted\n\t\t\tconst bool\tblob_is_unencrypted = !object_id.empty() && !check_if_blob_is_encrypted(object_id);\n\n\t\t\tif (fix_problems && blob_is_unencrypted) {\n\t\t\t\tif (access(filename.c_str(), F_OK) != 0) {\n\t\t\t\t\tstd::clog << \"Error: \" << filename << \": cannot stage encrypted version because not present in working tree - please 'git rm' or 'git checkout' it\" << std::endl;\n\t\t\t\t\t++nbr_of_fix_errors;\n\t\t\t\t} else {\n\t\t\t\t\ttouch_file(filename);\n\t\t\t\t\tstd::vector<std::string>\tgit_add_command;\n\t\t\t\t\tgit_add_command.push_back(\"git\");\n\t\t\t\t\tgit_add_command.push_back(\"add\");\n\t\t\t\t\tgit_add_command.push_back(\"--\");\n\t\t\t\t\tgit_add_command.push_back(filename);\n\t\t\t\t\tif (!successful_exit(exec_command(git_add_command))) {\n\t\t\t\t\t\tthrow Error(\"'git-add' failed\");\n\t\t\t\t\t}\n\t\t\t\t\tif (check_if_file_is_encrypted(filename)) {\n\t\t\t\t\t\tstd::cout << filename << \": staged encrypted version\" << std::endl;\n\t\t\t\t\t\t++nbr_of_fixed_blobs;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstd::clog << \"Error: \" << filename << \": still unencrypted even after staging\" << std::endl;\n\t\t\t\t\t\t++nbr_of_fix_errors;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (!fix_problems && !show_unencrypted_only) {\n\t\t\t\t// TODO: output the key name used to encrypt this file\n\t\t\t\tstd::cout << \"    encrypted: \" << filename;\n\t\t\t\tif (file_attrs.second != file_attrs.first) {\n\t\t\t\t\t// but diff filter is not properly set\n\t\t\t\t\tstd::cout << \" *** WARNING: diff=\" << file_attrs.first << \" attribute not set ***\";\n\t\t\t\t\tattribute_errors = true;\n\t\t\t\t}\n\t\t\t\tif (blob_is_unencrypted) {\n\t\t\t\t\t// File not actually encrypted\n\t\t\t\t\tstd::cout << \" *** WARNING: staged/committed version is NOT ENCRYPTED! ***\";\n\t\t\t\t\tunencrypted_blob_errors = true;\n\t\t\t\t}\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\t\t} else {\n\t\t\t// File not encrypted\n\t\t\tif (!fix_problems && !show_encrypted_only) {\n\t\t\t\tstd::cout << \"not encrypted: \" << filename << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tint\t\t\t\texit_status = 0;\n\n\tif (attribute_errors) {\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"Warning: one or more files has a git-crypt filter attribute but not a\" << std::endl;\n\t\tstd::cout << \"corresponding git-crypt diff attribute.  For proper 'git diff' operation\" << std::endl;\n\t\tstd::cout << \"you should fix the .gitattributes file to specify the correct diff attribute.\" << std::endl;\n\t\tstd::cout << \"Consult the git-crypt documentation for help.\" << std::endl;\n\t\texit_status = 1;\n\t}\n\tif (unencrypted_blob_errors) {\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"Warning: one or more files is marked for encryption via .gitattributes but\" << std::endl;\n\t\tstd::cout << \"was staged and/or committed before the .gitattributes file was in effect.\" << std::endl;\n\t\tstd::cout << \"Run 'git-crypt status' with the '-f' option to stage an encrypted version.\" << std::endl;\n\t\texit_status = 1;\n\t}\n\tif (nbr_of_fixed_blobs) {\n\t\tstd::cout << \"Staged \" << nbr_of_fixed_blobs << \" encrypted file\" << (nbr_of_fixed_blobs != 1 ? \"s\" : \"\") << \".\" << std::endl;\n\t\tstd::cout << \"Warning: if these files were previously committed, unencrypted versions still exist in the repository's history.\" << std::endl;\n\t}\n\tif (nbr_of_fix_errors) {\n\t\tstd::cout << \"Unable to stage \" << nbr_of_fix_errors << \" file\" << (nbr_of_fix_errors != 1 ? \"s\" : \"\") << \".\" << std::endl;\n\t\texit_status = 1;\n\t}\n\n\treturn exit_status;\n}\n\n"
  },
  {
    "path": "commands.hpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_COMMANDS_HPP\n#define GIT_CRYPT_COMMANDS_HPP\n\n#include <string>\n#include <iosfwd>\n\nstruct Error {\n\tstd::string\tmessage;\n\n\texplicit Error (std::string m) : message(m) { }\n};\n\n// Plumbing commands:\nint clean (int argc, const char** argv);\nint smudge (int argc, const char** argv);\nint diff (int argc, const char** argv);\n// Public commands:\nint init (int argc, const char** argv);\nint unlock (int argc, const char** argv);\nint lock (int argc, const char** argv);\nint add_gpg_user (int argc, const char** argv);\nint rm_gpg_user (int argc, const char** argv);\nint ls_gpg_users (int argc, const char** argv);\nint export_key (int argc, const char** argv);\nint keygen (int argc, const char** argv);\nint migrate_key (int argc, const char** argv);\nint refresh (int argc, const char** argv);\nint status (int argc, const char** argv);\n\n// Help messages:\nvoid help_init (std::ostream&);\nvoid help_unlock (std::ostream&);\nvoid help_lock (std::ostream&);\nvoid help_add_gpg_user (std::ostream&);\nvoid help_rm_gpg_user (std::ostream&);\nvoid help_ls_gpg_users (std::ostream&);\nvoid help_export_key (std::ostream&);\nvoid help_keygen (std::ostream&);\nvoid help_migrate_key (std::ostream&);\nvoid help_refresh (std::ostream&);\nvoid help_status (std::ostream&);\n\n// other\nstd::string get_git_config (const std::string& name);\n\n#endif\n"
  },
  {
    "path": "coprocess-unix.cpp",
    "content": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"coprocess.hpp\"\n#include \"util.hpp\"\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <errno.h>\n\nstatic int execvp (const std::string& file, const std::vector<std::string>& args)\n{\n\tstd::vector<const char*>\targs_c_str;\n\targs_c_str.reserve(args.size());\n\tfor (std::vector<std::string>::const_iterator arg(args.begin()); arg != args.end(); ++arg) {\n\t\targs_c_str.push_back(arg->c_str());\n\t}\n\targs_c_str.push_back(nullptr);\n\treturn execvp(file.c_str(), const_cast<char**>(&args_c_str[0]));\n}\n\nCoprocess::Coprocess ()\n{\n\tpid = -1;\n\tstdin_pipe_reader = -1;\n\tstdin_pipe_writer = -1;\n\tstdin_pipe_ostream = nullptr;\n\tstdout_pipe_reader = -1;\n\tstdout_pipe_writer = -1;\n\tstdout_pipe_istream = nullptr;\n}\n\nCoprocess::~Coprocess ()\n{\n\tclose_stdin();\n\tclose_stdout();\n}\n\nstd::ostream*\tCoprocess::stdin_pipe ()\n{\n\tif (!stdin_pipe_ostream) {\n\t\tint\tfds[2];\n\t\tif (pipe(fds) == -1) {\n\t\t\tthrow System_error(\"pipe\", \"\", errno);\n\t\t}\n\t\tstdin_pipe_reader = fds[0];\n\t\tstdin_pipe_writer = fds[1];\n\t\tstdin_pipe_ostream = new ofhstream(this, write_stdin);\n\t}\n\treturn stdin_pipe_ostream;\n}\n\nvoid\t\tCoprocess::close_stdin ()\n{\n\tdelete stdin_pipe_ostream;\n\tstdin_pipe_ostream = nullptr;\n\tif (stdin_pipe_writer != -1) {\n\t\tclose(stdin_pipe_writer);\n\t\tstdin_pipe_writer = -1;\n\t}\n\tif (stdin_pipe_reader != -1) {\n\t\tclose(stdin_pipe_reader);\n\t\tstdin_pipe_reader = -1;\n\t}\n}\n\nstd::istream*\tCoprocess::stdout_pipe ()\n{\n\tif (!stdout_pipe_istream) {\n\t\tint\tfds[2];\n\t\tif (pipe(fds) == -1) {\n\t\t\tthrow System_error(\"pipe\", \"\", errno);\n\t\t}\n\t\tstdout_pipe_reader = fds[0];\n\t\tstdout_pipe_writer = fds[1];\n\t\tstdout_pipe_istream = new ifhstream(this, read_stdout);\n\t}\n\treturn stdout_pipe_istream;\n}\n\nvoid\t\tCoprocess::close_stdout ()\n{\n\tdelete stdout_pipe_istream;\n\tstdout_pipe_istream = nullptr;\n\tif (stdout_pipe_writer != -1) {\n\t\tclose(stdout_pipe_writer);\n\t\tstdout_pipe_writer = -1;\n\t}\n\tif (stdout_pipe_reader != -1) {\n\t\tclose(stdout_pipe_reader);\n\t\tstdout_pipe_reader = -1;\n\t}\n}\n\nvoid\t\tCoprocess::spawn (const std::vector<std::string>& args)\n{\n\tpid = fork();\n\tif (pid == -1) {\n\t\tthrow System_error(\"fork\", \"\", errno);\n\t}\n\tif (pid == 0) {\n\t\tif (stdin_pipe_writer != -1) {\n\t\t\tclose(stdin_pipe_writer);\n\t\t}\n\t\tif (stdout_pipe_reader != -1) {\n\t\t\tclose(stdout_pipe_reader);\n\t\t}\n\t\tif (stdin_pipe_reader != -1) {\n\t\t\tdup2(stdin_pipe_reader, 0);\n\t\t\tclose(stdin_pipe_reader);\n\t\t}\n\t\tif (stdout_pipe_writer != -1) {\n\t\t\tdup2(stdout_pipe_writer, 1);\n\t\t\tclose(stdout_pipe_writer);\n\t\t}\n\n\t\texecvp(args[0], args);\n\t\tperror(args[0].c_str());\n\t\t_exit(-1);\n\t}\n\tif (stdin_pipe_reader != -1) {\n\t\tclose(stdin_pipe_reader);\n\t\tstdin_pipe_reader = -1;\n\t}\n\tif (stdout_pipe_writer != -1) {\n\t\tclose(stdout_pipe_writer);\n\t\tstdout_pipe_writer = -1;\n\t}\n}\n\nint\t\tCoprocess::wait ()\n{\n\tint\t\tstatus = 0;\n\tif (waitpid(pid, &status, 0) == -1) {\n\t\tthrow System_error(\"waitpid\", \"\", errno);\n\t}\n\treturn status;\n}\n\nsize_t\t\tCoprocess::write_stdin (void* handle, const void* buf, size_t count)\n{\n\tconst int\tfd = static_cast<Coprocess*>(handle)->stdin_pipe_writer;\n\tssize_t\t\tret;\n\twhile ((ret = write(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted\n\tif (ret < 0) {\n\t\tthrow System_error(\"write\", \"\", errno);\n\t}\n\treturn ret;\n}\n\nsize_t\t\tCoprocess::read_stdout (void* handle, void* buf, size_t count)\n{\n\tconst int\tfd = static_cast<Coprocess*>(handle)->stdout_pipe_reader;\n\tssize_t\t\tret;\n\twhile ((ret = read(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted\n\tif (ret < 0) {\n\t\tthrow System_error(\"read\", \"\", errno);\n\t}\n\treturn ret;\n}\n"
  },
  {
    "path": "coprocess-unix.hpp",
    "content": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_COPROCESS_HPP\n#define GIT_CRYPT_COPROCESS_HPP\n\n#include \"fhstream.hpp\"\n#include <unistd.h>\n#include <vector>\n\nclass Coprocess {\n\tpid_t\t\tpid;\n\n\tint\t\tstdin_pipe_reader;\n\tint\t\tstdin_pipe_writer;\n\tofhstream*\tstdin_pipe_ostream;\n\tstatic size_t\twrite_stdin (void*, const void*, size_t);\n\n\tint\t\tstdout_pipe_reader;\n\tint\t\tstdout_pipe_writer;\n\tifhstream*\tstdout_pipe_istream;\n\tstatic size_t\tread_stdout (void*, void*, size_t);\n\n\t\t\tCoprocess (const Coprocess&);\t// Disallow copy\n\tCoprocess&\toperator= (const Coprocess&);\t// Disallow assignment\npublic:\n\t\t\tCoprocess ();\n\t\t\t~Coprocess ();\n\n\tstd::ostream*\tstdin_pipe ();\n\tvoid\t\tclose_stdin ();\n\n\tstd::istream*\tstdout_pipe ();\n\tvoid\t\tclose_stdout ();\n\n\tvoid\t\tspawn (const std::vector<std::string>&);\n\n\tint\t\twait ();\n};\n\n#endif\n"
  },
  {
    "path": "coprocess-win32.cpp",
    "content": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"coprocess-win32.hpp\"\n#include \"util.hpp\"\n\n\nstatic void escape_cmdline_argument (std::string& cmdline, const std::string& arg)\n{\n\t// For an explanation of Win32's arcane argument quoting rules, see:\n\t//  http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx\n\t//  http://msdn.microsoft.com/en-us/library/bb776391%28v=vs.85%29.aspx\n\t//  http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx\n\t//  http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx\n\tcmdline.push_back('\"');\n\n\tstd::string::const_iterator\tp(arg.begin());\n\twhile (p != arg.end()) {\n\t\tif (*p == '\"') {\n\t\t\tcmdline.push_back('\\\\');\n\t\t\tcmdline.push_back('\"');\n\t\t\t++p;\n\t\t} else if (*p == '\\\\') {\n\t\t\tunsigned int\tnum_backslashes = 0;\n\t\t\twhile (p != arg.end() && *p == '\\\\') {\n\t\t\t\t++num_backslashes;\n\t\t\t\t++p;\n\t\t\t}\n\t\t\tif (p == arg.end() || *p == '\"') {\n\t\t\t\t// Backslashes need to be escaped\n\t\t\t\tnum_backslashes *= 2;\n\t\t\t}\n\t\t\twhile (num_backslashes--) {\n\t\t\t\tcmdline.push_back('\\\\');\n\t\t\t}\n\t\t} else {\n\t\t\tcmdline.push_back(*p++);\n\t\t}\n\t}\n\n\tcmdline.push_back('\"');\n}\n\nstatic std::string format_cmdline (const std::vector<std::string>& command)\n{\n\tstd::string\t\tcmdline;\n\tfor (std::vector<std::string>::const_iterator arg(command.begin()); arg != command.end(); ++arg) {\n\t\tif (arg != command.begin()) {\n\t\t\tcmdline.push_back(' ');\n\t\t}\n\t\tescape_cmdline_argument(cmdline, *arg);\n\t}\n\treturn cmdline;\n}\n\nstatic HANDLE spawn_command (const std::vector<std::string>& command, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle)\n{\n\tPROCESS_INFORMATION\tproc_info;\n\tZeroMemory(&proc_info, sizeof(proc_info));\n\n\tSTARTUPINFO\t\tstart_info;\n\tZeroMemory(&start_info, sizeof(start_info));\n\n\tstart_info.cb = sizeof(STARTUPINFO);\n\tstart_info.hStdInput = stdin_handle ? stdin_handle : GetStdHandle(STD_INPUT_HANDLE);\n\tstart_info.hStdOutput = stdout_handle ? stdout_handle : GetStdHandle(STD_OUTPUT_HANDLE);\n\tstart_info.hStdError = stderr_handle ? stderr_handle : GetStdHandle(STD_ERROR_HANDLE);\n\tstart_info.dwFlags |= STARTF_USESTDHANDLES;\n\n\tstd::string\t\tcmdline(format_cmdline(command));\n\n\tif (!CreateProcessA(nullptr,\t\t// application name (nullptr to use command line)\n\t\t\t\tconst_cast<char*>(cmdline.c_str()),\n\t\t\t\tnullptr,\t// process security attributes\n\t\t\t\tnullptr,\t// primary thread security attributes\n\t\t\t\tTRUE,\t\t// handles are inherited\n\t\t\t\t0,\t\t// creation flags\n\t\t\t\tnullptr,\t// use parent's environment\n\t\t\t\tnullptr,\t// use parent's current directory\n\t\t\t\t&start_info,\n\t\t\t\t&proc_info)) {\n\t\tthrow System_error(\"CreateProcess\", cmdline, GetLastError());\n\t}\n\n\tCloseHandle(proc_info.hThread);\n\n\treturn proc_info.hProcess;\n}\n\n\nCoprocess::Coprocess ()\n{\n\tproc_handle = nullptr;\n\tstdin_pipe_reader = nullptr;\n\tstdin_pipe_writer = nullptr;\n\tstdin_pipe_ostream = nullptr;\n\tstdout_pipe_reader = nullptr;\n\tstdout_pipe_writer = nullptr;\n\tstdout_pipe_istream = nullptr;\n}\n\nCoprocess::~Coprocess ()\n{\n\tclose_stdin();\n\tclose_stdout();\n\tif (proc_handle) {\n\t\tCloseHandle(proc_handle);\n\t}\n}\n\nstd::ostream*\tCoprocess::stdin_pipe ()\n{\n\tif (!stdin_pipe_ostream) {\n\t\tSECURITY_ATTRIBUTES\tsec_attr;\n\n\t\t// Set the bInheritHandle flag so pipe handles are inherited.\n\t\tsec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);\n\t\tsec_attr.bInheritHandle = TRUE;\n\t\tsec_attr.lpSecurityDescriptor = nullptr;\n\n\t\t// Create a pipe for the child process's STDIN.\n\t\tif (!CreatePipe(&stdin_pipe_reader, &stdin_pipe_writer, &sec_attr, 0)) {\n\t\t\tthrow System_error(\"CreatePipe\", \"\", GetLastError());\n\t\t}\n\n\t\t// Ensure the write handle to the pipe for STDIN is not inherited.\n\t\tif (!SetHandleInformation(stdin_pipe_writer, HANDLE_FLAG_INHERIT, 0)) {\n\t\t\tthrow System_error(\"SetHandleInformation\", \"\", GetLastError());\n\t\t}\n\n\t\tstdin_pipe_ostream = new ofhstream(this, write_stdin);\n\t}\n\treturn stdin_pipe_ostream;\n}\n\nvoid\t\tCoprocess::close_stdin ()\n{\n\tdelete stdin_pipe_ostream;\n\tstdin_pipe_ostream = nullptr;\n\tif (stdin_pipe_writer) {\n\t\tCloseHandle(stdin_pipe_writer);\n\t\tstdin_pipe_writer = nullptr;\n\t}\n\tif (stdin_pipe_reader) {\n\t\tCloseHandle(stdin_pipe_reader);\n\t\tstdin_pipe_reader = nullptr;\n\t}\n}\n\nstd::istream*\tCoprocess::stdout_pipe ()\n{\n\tif (!stdout_pipe_istream) {\n\t\tSECURITY_ATTRIBUTES\tsec_attr;\n\n\t\t// Set the bInheritHandle flag so pipe handles are inherited.\n\t\tsec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);\n\t\tsec_attr.bInheritHandle = TRUE;\n\t\tsec_attr.lpSecurityDescriptor = nullptr;\n\n\t\t// Create a pipe for the child process's STDOUT.\n\t\tif (!CreatePipe(&stdout_pipe_reader, &stdout_pipe_writer, &sec_attr, 0)) {\n\t\t\tthrow System_error(\"CreatePipe\", \"\", GetLastError());\n\t\t}\n\n\t\t// Ensure the read handle to the pipe for STDOUT is not inherited.\n\t\tif (!SetHandleInformation(stdout_pipe_reader, HANDLE_FLAG_INHERIT, 0)) {\n\t\t\tthrow System_error(\"SetHandleInformation\", \"\", GetLastError());\n\t\t}\n\n\t\tstdout_pipe_istream = new ifhstream(this, read_stdout);\n\t}\n\treturn stdout_pipe_istream;\n}\n\nvoid\t\tCoprocess::close_stdout ()\n{\n\tdelete stdout_pipe_istream;\n\tstdout_pipe_istream = nullptr;\n\tif (stdout_pipe_writer) {\n\t\tCloseHandle(stdout_pipe_writer);\n\t\tstdout_pipe_writer = nullptr;\n\t}\n\tif (stdout_pipe_reader) {\n\t\tCloseHandle(stdout_pipe_reader);\n\t\tstdout_pipe_reader = nullptr;\n\t}\n}\n\nvoid\t\tCoprocess::spawn (const std::vector<std::string>& args)\n{\n\tproc_handle = spawn_command(args, stdin_pipe_reader, stdout_pipe_writer, nullptr);\n\tif (stdin_pipe_reader) {\n\t\tCloseHandle(stdin_pipe_reader);\n\t\tstdin_pipe_reader = nullptr;\n\t}\n\tif (stdout_pipe_writer) {\n\t\tCloseHandle(stdout_pipe_writer);\n\t\tstdout_pipe_writer = nullptr;\n\t}\n}\n\nint\t\tCoprocess::wait ()\n{\n\tif (WaitForSingleObject(proc_handle, INFINITE) == WAIT_FAILED) {\n\t\tthrow System_error(\"WaitForSingleObject\", \"\", GetLastError());\n\t}\n\n\tDWORD\t\t\texit_code;\n\tif (!GetExitCodeProcess(proc_handle, &exit_code)) {\n\t\tthrow System_error(\"GetExitCodeProcess\", \"\", GetLastError());\n\t}\n\n\treturn exit_code;\n}\n\nsize_t\t\tCoprocess::write_stdin (void* handle, const void* buf, size_t count)\n{\n\tDWORD\t\tbytes_written;\n\tif (!WriteFile(static_cast<Coprocess*>(handle)->stdin_pipe_writer, buf, count, &bytes_written, nullptr)) {\n\t\tthrow System_error(\"WriteFile\", \"\", GetLastError());\n\t}\n\treturn bytes_written;\n}\n\nsize_t\t\tCoprocess::read_stdout (void* handle, void* buf, size_t count)\n{\n\t// Note that ReadFile on a pipe may return with bytes_read==0 if the other\n\t// end of the pipe writes zero bytes, so retry when this happens.\n\t// When the other end of the pipe actually closes, ReadFile\n\t// fails with ERROR_BROKEN_PIPE.\n\tDWORD bytes_read;\n\tdo {\n\t\tif (!ReadFile(static_cast<Coprocess*>(handle)->stdout_pipe_reader, buf, count, &bytes_read, nullptr)) {\n\t\t\tconst DWORD\tread_error = GetLastError();\n\t\t\tif (read_error != ERROR_BROKEN_PIPE) {\n\t\t\t\tthrow System_error(\"ReadFile\", \"\", read_error);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t} while (bytes_read == 0);\n\treturn bytes_read;\n}\n"
  },
  {
    "path": "coprocess-win32.hpp",
    "content": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_COPROCESS_HPP\n#define GIT_CRYPT_COPROCESS_HPP\n\n#include \"fhstream.hpp\"\n#include <windows.h>\n#include <vector>\n\nclass Coprocess {\n\tHANDLE\t\tproc_handle;\n\n\tHANDLE\t\tstdin_pipe_reader;\n\tHANDLE\t\tstdin_pipe_writer;\n\tofhstream*\tstdin_pipe_ostream;\n\tstatic size_t\twrite_stdin (void*, const void*, size_t);\n\n\tHANDLE\t\tstdout_pipe_reader;\n\tHANDLE\t\tstdout_pipe_writer;\n\tifhstream*\tstdout_pipe_istream;\n\tstatic size_t\tread_stdout (void*, void*, size_t);\n\n\t\t\tCoprocess (const Coprocess&);\t// Disallow copy\n\tCoprocess&\toperator= (const Coprocess&);\t// Disallow assignment\npublic:\n\t\t\tCoprocess ();\n\t\t\t~Coprocess ();\n\n\tstd::ostream*\tstdin_pipe ();\n\tvoid\t\tclose_stdin ();\n\n\tstd::istream*\tstdout_pipe ();\n\tvoid\t\tclose_stdout ();\n\n\tvoid\t\tspawn (const std::vector<std::string>&);\n\n\tint\t\twait ();\n};\n\n#endif\n"
  },
  {
    "path": "coprocess.cpp",
    "content": "#ifdef _WIN32\n#include \"coprocess-win32.cpp\"\n#else\n#include \"coprocess-unix.cpp\"\n#endif\n"
  },
  {
    "path": "coprocess.hpp",
    "content": "#ifdef _WIN32\n#include \"coprocess-win32.hpp\"\n#else\n#include \"coprocess-unix.hpp\"\n#endif\n"
  },
  {
    "path": "crypto-openssl-11.cpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"crypto.hpp\"\n#include \"key.hpp\"\n#include \"util.hpp\"\n#include <openssl/aes.h>\n#include <openssl/sha.h>\n#include <openssl/hmac.h>\n#include <openssl/evp.h>\n#include <openssl/rand.h>\n#include <openssl/err.h>\n#include <sstream>\n#include <cstring>\n\nvoid init_crypto ()\n{\n\tERR_load_crypto_strings();\n}\n\nstruct Aes_ecb_encryptor::Aes_impl {\n\tAES_KEY key;\n};\n\nAes_ecb_encryptor::Aes_ecb_encryptor (const unsigned char* raw_key)\n: impl(new Aes_impl)\n{\n\tif (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &(impl->key)) != 0) {\n\t\tthrow Crypto_error(\"Aes_ctr_encryptor::Aes_ctr_encryptor\", \"AES_set_encrypt_key failed\");\n\t}\n}\n\nAes_ecb_encryptor::~Aes_ecb_encryptor ()\n{\n\t// Note: Explicit destructor necessary because class contains an unique_ptr\n\t// which contains an incomplete type when the unique_ptr is declared.\n\n\texplicit_memset(&impl->key, '\\0', sizeof(impl->key));\n}\n\nvoid Aes_ecb_encryptor::encrypt(const unsigned char* plain, unsigned char* cipher)\n{\n\tAES_encrypt(plain, cipher, &(impl->key));\n}\n\nstruct Hmac_sha1_state::Hmac_impl {\n\tHMAC_CTX *ctx;\n};\n\nHmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len)\n: impl(new Hmac_impl)\n{\n\n\timpl->ctx = HMAC_CTX_new();\n\tHMAC_Init_ex(impl->ctx, key, key_len, EVP_sha1(), nullptr);\n}\n\nHmac_sha1_state::~Hmac_sha1_state ()\n{\n\tHMAC_CTX_free(impl->ctx);\n}\n\nvoid Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len)\n{\n\tHMAC_Update(impl->ctx, buffer, buffer_len);\n}\n\nvoid Hmac_sha1_state::get (unsigned char* digest)\n{\n\tunsigned int len;\n\tHMAC_Final(impl->ctx, digest, &len);\n}\n\n\nvoid random_bytes (unsigned char* buffer, size_t len)\n{\n\tif (RAND_bytes(buffer, len) != 1) {\n\t\tstd::ostringstream\tmessage;\n\t\twhile (unsigned long code = ERR_get_error()) {\n\t\t\tchar\t\terror_string[120];\n\t\t\tERR_error_string_n(code, error_string, sizeof(error_string));\n\t\t\tmessage << \"OpenSSL Error: \" << error_string << \"; \";\n\t\t}\n\t\tthrow Crypto_error(\"random_bytes\", message.str());\n\t}\n}\n"
  },
  {
    "path": "crypto.cpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"crypto.hpp\"\n#include \"util.hpp\"\n#include <cstring>\n\nAes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* nonce)\n: ecb(raw_key)\n{\n\t// Set first 12 bytes of the CTR value to the nonce.\n\t// This stays the same for the entirety of this object's lifetime.\n\tstd::memcpy(ctr_value, nonce, NONCE_LEN);\n\tbyte_counter = 0;\n}\n\nAes_ctr_encryptor::~Aes_ctr_encryptor ()\n{\n\texplicit_memset(pad, '\\0', BLOCK_LEN);\n}\n\nvoid Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, size_t len)\n{\n\tfor (size_t i = 0; i < len; ++i) {\n\t\tif (byte_counter % BLOCK_LEN == 0) {\n\t\t\t// Set last 4 bytes of CTR to the (big-endian) block number (sequentially increasing with each block)\n\t\t\tstore_be32(ctr_value + NONCE_LEN, byte_counter / BLOCK_LEN);\n\n\t\t\t// Generate a new pad\n\t\t\tecb.encrypt(ctr_value, pad);\n\t\t}\n\n\t\t// encrypt one byte\n\t\tout[i] = in[i] ^ pad[byte_counter++ % BLOCK_LEN];\n\n\t\tif (byte_counter == 0) {\n\t\t\tthrow Crypto_error(\"Aes_ctr_encryptor::process\", \"Too much data to encrypt securely\");\n\t\t}\n\t}\n}\n\n// Encrypt/decrypt an entire input stream, writing to the given output stream\nvoid Aes_ctr_encryptor::process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce)\n{\n\tAes_ctr_encryptor\taes(key, nonce);\n\n\tunsigned char\t\tbuffer[1024];\n\twhile (in) {\n\t\tin.read(reinterpret_cast<char*>(buffer), sizeof(buffer));\n\t\taes.process(buffer, buffer, in.gcount());\n\t\tout.write(reinterpret_cast<char*>(buffer), in.gcount());\n\t}\n}\n\n"
  },
  {
    "path": "crypto.hpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_CRYPTO_HPP\n#define GIT_CRYPT_CRYPTO_HPP\n\n#include \"key.hpp\"\n#include <stdint.h>\n#include <stddef.h>\n#include <iosfwd>\n#include <string>\n#include <memory>\n\nvoid init_crypto ();\n\nstruct Crypto_error {\n\tstd::string\twhere;\n\tstd::string\tmessage;\n\n\tCrypto_error (const std::string& w, const std::string& m) : where(w), message(m) { }\n};\n\nclass Aes_ecb_encryptor {\npublic:\n\tenum {\n\t\tKEY_LEN\t\t= AES_KEY_LEN,\n\t\tBLOCK_LEN\t= 16\n\t};\n\nprivate:\n\tstruct Aes_impl;\n\n\tstd::unique_ptr<Aes_impl>\timpl;\n\npublic:\n\tAes_ecb_encryptor (const unsigned char* key);\n\t~Aes_ecb_encryptor ();\n\tvoid encrypt (const unsigned char* plain, unsigned char* cipher);\n};\n\nclass Aes_ctr_encryptor {\npublic:\n\tenum {\n\t\tNONCE_LEN\t= 12,\n\t\tKEY_LEN\t\t= AES_KEY_LEN,\n\t\tBLOCK_LEN\t= 16,\n\t\tMAX_CRYPT_BYTES\t= (1ULL<<32)*16 // Don't encrypt more than this or the CTR value will repeat itself\n\t};\n\nprivate:\n\tAes_ecb_encryptor\tecb;\n\tunsigned char\t\tctr_value[BLOCK_LEN];\t// Current CTR value (used as input to AES to derive pad)\n\tunsigned char\t\tpad[BLOCK_LEN];\t\t// Current encryption pad (output of AES)\n\tuint32_t\t\tbyte_counter;\t\t// How many bytes processed so far?\n\npublic:\n\tAes_ctr_encryptor (const unsigned char* key, const unsigned char* nonce);\n\t~Aes_ctr_encryptor ();\n\n\tvoid process (const unsigned char* in, unsigned char* out, size_t len);\n\n\t// Encrypt/decrypt an entire input stream, writing to the given output stream\n\tstatic void process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce);\n};\n\ntypedef Aes_ctr_encryptor Aes_ctr_decryptor;\n\nclass Hmac_sha1_state {\npublic:\n\tenum {\n\t\tLEN\t= 20,\n\t\tKEY_LEN\t= HMAC_KEY_LEN\n\t};\n\nprivate:\n\tstruct Hmac_impl;\n\n\tstd::unique_ptr<Hmac_impl>\timpl;\n\npublic:\n\tHmac_sha1_state (const unsigned char* key, size_t key_len);\n\t~Hmac_sha1_state ();\n\n\tvoid add (const unsigned char* buffer, size_t buffer_len);\n\tvoid get (unsigned char*);\n};\n\nvoid random_bytes (unsigned char*, size_t);\n\n#endif\n"
  },
  {
    "path": "doc/multiple_keys.md",
    "content": "In addition to the implicit default key, git-crypt supports alternative\nkeys which can be used to encrypt specific files and can be shared with\nspecific GPG users.  This is useful if you want to grant different\ncollaborators access to different sets of files.\n\nTo generate an alternative key named KEYNAME, pass the `-k KEYNAME`\noption to `git-crypt init` as follows:\n\n    git-crypt init -k KEYNAME\n\nTo encrypt a file with an alternative key, use the `git-crypt-KEYNAME`\nfilter in `.gitattributes` as follows:\n\n    secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME\n\nTo export an alternative key or share it with a GPG user, pass the `-k\nKEYNAME` option to `git-crypt export-key` or `git-crypt add-gpg-user`\nas follows:\n\n    git-crypt export-key -k KEYNAME /path/to/keyfile\n    git-crypt add-gpg-user -k KEYNAME GPG_USER_ID\n\nTo unlock a repository with an alternative key, use `git-crypt unlock`\nnormally.  git-crypt will automatically determine which key is being used.\n"
  },
  {
    "path": "fhstream.cpp",
    "content": "/*\n * Copyright (C) 2012, 2015 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Except as contained in this notice, the name(s) of the above copyright\n * holders shall not be used in advertising or otherwise to promote the\n * sale, use or other dealings in this Software without prior written\n * authorization.\n */\n\n#include <cstring>\n#include <algorithm> // for std::min\n\n#include \"fhstream.hpp\"\n\n/*\n * ofhstream\n */\n\nofhbuf::ofhbuf (void* arg_handle, size_t (*arg_write_fun)(void*, const void*, size_t))\n: handle(arg_handle),\n  write_fun(arg_write_fun),\n  buffer(new char[default_buffer_size]),\n  buffer_size(default_buffer_size)\n{\n\treset_buffer();\n}\n\nofhbuf::~ofhbuf ()\n{\n\tif (handle) {\n\t\ttry {\n\t\t\tsync();\n\t\t} catch (...) {\n\t\t\t// Ignore exception since we're in the destructor.\n\t\t\t// To catch write errors, call sync() explicitly.\n\t\t}\n\t}\n\tdelete[] buffer;\n}\n\nofhbuf::int_type\tofhbuf::overflow (ofhbuf::int_type c)\n{\n\tconst char*\tp = pbase();\n\tstd::streamsize\tbytes_to_write = pptr() - p;\n\n\tif (!is_eof(c)) {\n\t      *pptr() = c;\n\t      ++bytes_to_write;\n\t}\n\n\twhile (bytes_to_write > 0) {\n\t\tconst size_t\tbytes_written = write_fun(handle, p, bytes_to_write);\n\t\tbytes_to_write -= bytes_written;\n\t\tp += bytes_written;\n\t}\n\n\treset_buffer();\n\n\treturn traits_type::to_int_type(0);\n}\n\nint\t\tofhbuf::sync ()\n{\n\treturn !is_eof(overflow(traits_type::eof())) ? 0 : -1;\n}\n\nstd::streamsize\tofhbuf::xsputn (const char* s, std::streamsize n)\n{\n\t// Use heuristic to decide whether to write directly or just use buffer\n\t// Write directly only if n >= MIN(4096, available buffer capacity)\n\t// (this is similar to what basic_filebuf does)\n\n\tif (n < std::min<std::streamsize>(4096, epptr() - pptr())) {\n\t\t// Not worth it to do a direct write\n\t\treturn std::streambuf::xsputn(s, n);\n\t}\n\n\t// Before we can do a direct write of this string, we need to flush\n\t// out the current contents of the buffer.\n\tif (pbase() != pptr()) {\n\t\toverflow(traits_type::eof()); // throws an exception or it succeeds\n\t}\n\n\t// Now we can go ahead and write out the string.\n\tsize_t\t\tbytes_to_write = n;\n\n\twhile (bytes_to_write > 0) {\n\t\tconst size_t\tbytes_written = write_fun(handle, s, bytes_to_write);\n\t\tbytes_to_write -= bytes_written;\n\t\ts += bytes_written;\n\t}\n\n\treturn n; // Return the total bytes written\n}\n\nstd::streambuf*\tofhbuf::setbuf (char* s, std::streamsize n)\n{\n\tif (s == 0 && n == 0) {\n\t\t// Switch to unbuffered\n\t\t// This won't take effect until the next overflow or sync\n\t\t// (We defer it taking effect so that write errors can be properly reported)\n\t\t// To cause it to take effect as soon as possible, we artificially reduce the\n\t\t// size of the buffer so it has no space left.  This will trigger an overflow\n\t\t// on the next put.\n\t\tstd::streambuf::setp(pbase(), pptr());\n\t\tstd::streambuf::pbump(pptr() - pbase());\n\t\tbuffer_size = 1;\n\t}\n\treturn this;\n}\n\n\n\n/*\n * ifhstream\n */\n\nifhbuf::ifhbuf (void* arg_handle, size_t (*arg_read_fun)(void*, void*, size_t))\n: handle(arg_handle),\n  read_fun(arg_read_fun),\n  buffer(new char[default_buffer_size + putback_size]),\n  buffer_size(default_buffer_size)\n{\n\treset_buffer(0, 0);\n}\n\nifhbuf::~ifhbuf ()\n{\n\tdelete[] buffer;\n}\n\nifhbuf::int_type\tifhbuf::underflow ()\n{\n\tif (gptr() >= egptr()) { // A true underflow (no bytes in buffer left to read)\n\n\t\t// Move the putback_size most-recently-read characters into the putback area\n\t\tsize_t\t\tnputback = std::min<size_t>(gptr() - eback(), putback_size);\n\t\tstd::memmove(buffer + (putback_size - nputback), gptr() - nputback, nputback);\n\n\t\t// Now read new characters from the file descriptor\n\t\tconst size_t\tnread = read_fun(handle, buffer + putback_size, buffer_size);\n\t\tif (nread == 0) {\n\t\t\t// EOF\n\t\t\treturn traits_type::eof();\n\t\t}\n\n\t\t// Reset the buffer\n\t\treset_buffer(nputback, nread);\n\t}\n\n\t// Return the next character\n\treturn traits_type::to_int_type(*gptr());\n}\n\nstd::streamsize\tifhbuf::xsgetn (char* s, std::streamsize n)\n{\n\t// Use heuristic to decide whether to read directly\n\t// Read directly only if n >= bytes_available + 4096\n\n\tstd::streamsize\tbytes_available = egptr() - gptr();\n\n\tif (n < bytes_available + 4096) {\n\t\t// Not worth it to do a direct read\n\t\treturn std::streambuf::xsgetn(s, n);\n\t}\n\n\tstd::streamsize\ttotal_bytes_read = 0;\n\n\t// First, copy out the bytes currently in the buffer\n\tstd::memcpy(s, gptr(), bytes_available);\n\n\ts += bytes_available;\n\tn -= bytes_available;\n\ttotal_bytes_read += bytes_available;\n\n\t// Now do the direct read\n\twhile (n > 0) {\n\t\tconst size_t\tbytes_read = read_fun(handle, s, n);\n\t\tif (bytes_read == 0) {\n\t\t\t// EOF\n\t\t\tbreak;\n\t\t}\n\n\t\ts += bytes_read;\n\t\tn -= bytes_read;\n\t\ttotal_bytes_read += bytes_read;\n\t}\n\n\t// Fill up the putback area with the most recently read characters\n\tsize_t\t\tnputback = std::min<size_t>(total_bytes_read, putback_size);\n\tstd::memcpy(buffer + (putback_size - nputback), s - nputback, nputback);\n\n\t// Reset the buffer with no bytes available for reading, but with some putback characters\n\treset_buffer(nputback, 0);\n\n\t// Return the total number of bytes read\n\treturn total_bytes_read;\n}\n\nstd::streambuf*\tifhbuf::setbuf (char* s, std::streamsize n)\n{\n\tif (s == 0 && n == 0) {\n\t\t// Switch to unbuffered\n\t\t// This won't take effect until the next underflow (we don't want to\n\t\t// lose what's currently in the buffer!)\n\t\tbuffer_size = 1;\n\t}\n\treturn this;\n}\n"
  },
  {
    "path": "fhstream.hpp",
    "content": "/*\n * Copyright (C) 2012, 2015 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Except as contained in this notice, the name(s) of the above copyright\n * holders shall not be used in advertising or otherwise to promote the\n * sale, use or other dealings in this Software without prior written\n * authorization.\n */\n\n#ifndef GIT_CRYPT_FHSTREAM_HPP\n#define GIT_CRYPT_FHSTREAM_HPP\n\n#include <ostream>\n#include <istream>\n#include <streambuf>\n\n/*\n * ofhstream\n */\nclass ofhbuf : public std::streambuf {\n\tenum { default_buffer_size = 8192 };\n\n\tvoid*\t\t\thandle;\n\tsize_t\t\t\t(*write_fun)(void*, const void*, size_t);\n\tchar*\t\t\tbuffer;\n\tsize_t\t\t\tbuffer_size;\n\n\tinline void reset_buffer ()\n\t{\n\t\tstd::streambuf::setp(buffer, buffer + buffer_size - 1);\n\t}\n\tstatic inline bool is_eof (int_type ch) { return traits_type::eq_int_type(ch, traits_type::eof()); }\n\n\t// Disallow copy\n#if __cplusplus >= 201103L /* C++11 */\n\tofhbuf (const ofhbuf&) = delete;\n\tofhbuf& operator= (const ofhbuf&) = delete;\n#else\n\tofhbuf (const ofhbuf&);\n\tofhbuf& operator= (const ofhbuf&);\n#endif\n\nprotected:\n\tvirtual int_type\toverflow (int_type ch =traits_type::eof());\n\tvirtual int\t\tsync ();\n\tvirtual std::streamsize\txsputn (const char*, std::streamsize);\n\tvirtual\tstd::streambuf*\tsetbuf (char*, std::streamsize);\n\npublic:\n\tofhbuf (void*, size_t (*)(void*, const void*, size_t));\n\t~ofhbuf (); // WARNING: calls sync() and ignores exceptions\n};\n\nclass ofhstream : public std::ostream {\n\tmutable ofhbuf\tbuf;\npublic:\n\tofhstream (void* handle, size_t (*write_fun)(void*, const void*, size_t))\n\t: std::ostream(0), buf(handle, write_fun)\n\t{\n\t\tstd::ostream::rdbuf(&buf);\n\t}\n\n\tofhbuf*\trdbuf () const { return &buf; }\n};\n\n\n/*\n * ifhstream\n */\nclass ifhbuf : public std::streambuf {\n\tenum {\n\t\tdefault_buffer_size = 8192,\n\t\tputback_size = 4\n\t};\n\n\tvoid*\t\t\thandle;\n\tsize_t\t\t\t(*read_fun)(void*, void*, size_t);\n\tchar*\t\t\tbuffer;\n\tsize_t\t\t\tbuffer_size;\n\n\tinline void reset_buffer (size_t nputback, size_t nread)\n\t{\n\t\tstd::streambuf::setg(buffer + (putback_size - nputback), buffer + putback_size, buffer + putback_size + nread);\n\t}\n\t// Disallow copy\n#if __cplusplus >= 201103L /* C++11 */\n\tifhbuf (const ifhbuf&) = delete;\n\tifhbuf& operator= (const ifhbuf&) = delete;\n#else\n\tifhbuf (const ifhbuf&);\n\tifhbuf& operator= (const ifhbuf&);\n#endif\n\nprotected:\n\tvirtual int_type\tunderflow ();\n\tvirtual std::streamsize\txsgetn (char*, std::streamsize);\n\tvirtual\tstd::streambuf*\tsetbuf (char*, std::streamsize);\n\npublic:\n\tifhbuf (void*, size_t (*)(void*, void*, size_t));\n\t~ifhbuf (); // Can't fail\n};\n\nclass ifhstream : public std::istream {\n\tmutable ifhbuf\tbuf;\npublic:\n\texplicit ifhstream (void* handle, size_t (*read_fun)(void*, void*, size_t))\n\t: std::istream(0), buf(handle, read_fun)\n\t{\n\t\tstd::istream::rdbuf(&buf);\n\t}\n\n\tifhbuf*\trdbuf () const { return &buf; }\n};\n\n#endif\n"
  },
  {
    "path": "git-crypt.cpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"git-crypt.hpp\"\n#include \"commands.hpp\"\n#include \"util.hpp\"\n#include \"crypto.hpp\"\n#include \"key.hpp\"\n#include \"gpg.hpp\"\n#include \"parse_options.hpp\"\n#include <cstring>\n#include <unistd.h>\n#include <iostream>\n#include <string.h>\n\nconst char*\targv0;\n\nstatic void print_usage (std::ostream& out)\n{\n\tout << \"Usage: \" << argv0 << \" COMMAND [ARGS ...]\" << std::endl;\n\tout << std::endl;\n\t//     |--------------------------------------------------------------------------------| 80 characters\n\tout << \"Common commands:\" << std::endl;\n\tout << \"  init                 generate a key and prepare repo to use git-crypt\" << std::endl;\n\tout << \"  status               display which files are encrypted\" << std::endl;\n\t//out << \"  refresh              ensure all files in the repo are properly decrypted\" << std::endl;\n\tout << \"  lock                 de-configure git-crypt and re-encrypt files in work tree\" << std::endl;\n\tout << std::endl;\n\tout << \"GPG commands:\" << std::endl;\n\tout << \"  add-gpg-user USERID  add the user with the given GPG user ID as a collaborator\" << std::endl;\n\t//out << \"  rm-gpg-user USERID   revoke collaborator status from the given GPG user ID\" << std::endl;\n\t//out << \"  ls-gpg-users         list the GPG key IDs of collaborators\" << std::endl;\n\tout << \"  unlock               decrypt this repo using the in-repo GPG-encrypted key\" << std::endl;\n\tout << std::endl;\n\tout << \"Symmetric key commands:\" << std::endl;\n\tout << \"  export-key FILE      export this repo's symmetric key to the given file\" << std::endl;\n\tout << \"  unlock KEYFILE       decrypt this repo using the given symmetric key\" << std::endl;\n\tout << std::endl;\n\tout << \"Legacy commands:\" << std::endl;\n\tout << \"  init KEYFILE         alias for 'unlock KEYFILE'\" << std::endl;\n\tout << \"  keygen KEYFILE       generate a git-crypt key in the given file\" << std::endl;\n\tout << \"  migrate-key OLD NEW  migrate the legacy key file OLD to the new format in NEW\" << std::endl;\n\t/*\n\tout << std::endl;\n\tout << \"Plumbing commands (not to be used directly):\" << std::endl;\n\tout << \"   clean [LEGACY-KEYFILE]\" << std::endl;\n\tout << \"   smudge [LEGACY-KEYFILE]\" << std::endl;\n\tout << \"   diff [LEGACY-KEYFILE] FILE\" << std::endl;\n\t*/\n\tout << std::endl;\n\tout << \"See 'git-crypt help COMMAND' for more information on a specific command.\" << std::endl;\n}\n\nstatic void print_version (std::ostream& out)\n{\n\tout << \"git-crypt \" << VERSION << std::endl;\n}\n\nstatic bool help_for_command (const char* command, std::ostream& out)\n{\n\tif (std::strcmp(command, \"init\") == 0) {\n\t\thelp_init(out);\n\t} else if (std::strcmp(command, \"unlock\") == 0) {\n\t\thelp_unlock(out);\n\t} else if (std::strcmp(command, \"lock\") == 0) {\n\t\thelp_lock(out);\n\t} else if (std::strcmp(command, \"add-gpg-user\") == 0) {\n\t\thelp_add_gpg_user(out);\n\t} else if (std::strcmp(command, \"rm-gpg-user\") == 0) {\n\t\thelp_rm_gpg_user(out);\n\t} else if (std::strcmp(command, \"ls-gpg-users\") == 0) {\n\t\thelp_ls_gpg_users(out);\n\t} else if (std::strcmp(command, \"export-key\") == 0) {\n\t\thelp_export_key(out);\n\t} else if (std::strcmp(command, \"keygen\") == 0) {\n\t\thelp_keygen(out);\n\t} else if (std::strcmp(command, \"migrate-key\") == 0) {\n\t\thelp_migrate_key(out);\n\t} else if (std::strcmp(command, \"refresh\") == 0) {\n\t\thelp_refresh(out);\n\t} else if (std::strcmp(command, \"status\") == 0) {\n\t\thelp_status(out);\n\t} else {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic int help (int argc, const char** argv)\n{\n\tif (argc == 0) {\n\t\tprint_usage(std::cout);\n\t} else {\n\t\tif (!help_for_command(argv[0], std::cout)) {\n\t\t\tstd::clog << \"Error: '\" << argv[0] << \"' is not a git-crypt command. See 'git-crypt help'.\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nstatic int version (int argc, const char** argv)\n{\n\tprint_version(std::cout);\n\treturn 0;\n}\n\n\nint main (int argc, const char** argv)\ntry {\n\targv0 = argv[0];\n\n\t/*\n\t * General initialization\n\t */\n\n\tinit_std_streams();\n\tinit_crypto();\n\n\t/*\n\t * Parse command line arguments\n\t */\n\tint\t\t\targ_index = 1;\n\twhile (arg_index < argc && argv[arg_index][0] == '-') {\n\t\tif (std::strcmp(argv[arg_index], \"--help\") == 0) {\n\t\t\tprint_usage(std::clog);\n\t\t\treturn 0;\n\t\t} else if (std::strcmp(argv[arg_index], \"--version\") == 0) {\n\t\t\tprint_version(std::clog);\n\t\t\treturn 0;\n\t\t} else if (std::strcmp(argv[arg_index], \"--\") == 0) {\n\t\t\t++arg_index;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tstd::clog << argv0 << \": \" << argv[arg_index] << \": Unknown option\" << std::endl;\n\t\t\tprint_usage(std::clog);\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\targc -= arg_index;\n\targv += arg_index;\n\n\tif (argc == 0) {\n\t\tprint_usage(std::clog);\n\t\treturn 2;\n\t}\n\n\t/*\n\t * Pass off to command handler\n\t */\n\tconst char*\t\tcommand = argv[0];\n\t--argc;\n\t++argv;\n\n\ttry {\n\t\t// Public commands:\n\t\tif (std::strcmp(command, \"help\") == 0) {\n\t\t\treturn help(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"version\") == 0) {\n\t\t\treturn version(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"init\") == 0) {\n\t\t\treturn init(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"unlock\") == 0) {\n\t\t\treturn unlock(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"lock\") == 0) {\n\t\t\treturn lock(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"add-gpg-user\") == 0) {\n\t\t\treturn add_gpg_user(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"rm-gpg-user\") == 0) {\n\t\t\treturn rm_gpg_user(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"ls-gpg-users\") == 0) {\n\t\t\treturn ls_gpg_users(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"export-key\") == 0) {\n\t\t\treturn export_key(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"keygen\") == 0) {\n\t\t\treturn keygen(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"migrate-key\") == 0) {\n\t\t\treturn migrate_key(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"refresh\") == 0) {\n\t\t\treturn refresh(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"status\") == 0) {\n\t\t\treturn status(argc, argv);\n\t\t}\n\t\t// Plumbing commands (executed by git, not by user):\n\t\tif (std::strcmp(command, \"clean\") == 0) {\n\t\t\treturn clean(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"smudge\") == 0) {\n\t\t\treturn smudge(argc, argv);\n\t\t}\n\t\tif (std::strcmp(command, \"diff\") == 0) {\n\t\t\treturn diff(argc, argv);\n\t\t}\n\t} catch (const Option_error& e) {\n\t\tstd::clog << \"git-crypt: Error: \" << e.option_name << \": \" << e.message << std::endl;\n\t\thelp_for_command(command, std::clog);\n\t\treturn 2;\n\t}\n\n\tstd::clog << \"Error: '\" << command << \"' is not a git-crypt command. See 'git-crypt help'.\" << std::endl;\n\treturn 2;\n\n} catch (const Error& e) {\n\tstd::cerr << \"git-crypt: Error: \" << e.message << std::endl;\n\treturn 1;\n} catch (const Gpg_error& e) {\n\tstd::cerr << \"git-crypt: GPG error: \" << e.message << std::endl;\n\treturn 1;\n} catch (const System_error& e) {\n\tstd::cerr << \"git-crypt: System error: \" << e.message() << std::endl;\n\treturn 1;\n} catch (const Crypto_error& e) {\n\tstd::cerr << \"git-crypt: Crypto error: \" << e.where << \": \" << e.message << std::endl;\n\treturn 1;\n} catch (Key_file::Incompatible) {\n\tstd::cerr << \"git-crypt: This repository contains a incompatible key file.  Please upgrade git-crypt.\" << std::endl;\n\treturn 1;\n} catch (Key_file::Malformed) {\n\tstd::cerr << \"git-crypt: This repository contains a malformed key file.  It may be corrupted.\" << std::endl;\n\treturn 1;\n} catch (const std::ios_base::failure& e) {\n\tstd::cerr << \"git-crypt: I/O error: \" << e.what() << std::endl;\n\treturn 1;\n}\n\n\n"
  },
  {
    "path": "git-crypt.hpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_GIT_CRYPT_HPP\n#define GIT_CRYPT_GIT_CRYPT_HPP\n\n#define VERSION \"0.8.0\"\n\nextern const char*\targv0;\t// initialized in main() to argv[0]\n\n#endif\n"
  },
  {
    "path": "gpg.cpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"gpg.hpp\"\n#include \"util.hpp\"\n#include \"commands.hpp\"\n#include <sstream>\n\nstatic std::string gpg_get_executable()\n{\n\tstd::string gpgbin = \"gpg\";\n\ttry {\n\t\tgpgbin = get_git_config(\"gpg.program\");\n\t} catch (...) {\n\t}\n\treturn gpgbin;\n}\nstatic std::string gpg_nth_column (const std::string& line, unsigned int col)\n{\n\tstd::string::size_type\tpos = 0;\n\n\tfor (unsigned int i = 0; i < col; ++i) {\n\t\tpos = line.find_first_of(':', pos);\n\t\tif (pos == std::string::npos) {\n\t\t\tthrow Gpg_error(\"Malformed output from gpg\");\n\t\t}\n\t\tpos = pos + 1;\n\t}\n\n\tconst std::string::size_type\tend_pos = line.find_first_of(':', pos);\n\n\treturn end_pos != std::string::npos ?\n\t       line.substr(pos, end_pos - pos) :\n\t       line.substr(pos);\n}\n\n// given a key fingerprint, return the key's UID (e.g. \"John Smith <jsmith@example.com>\")\nstd::string gpg_get_uid (const std::string& fingerprint)\n{\n\t// gpg --batch --with-colons --fixed-list-mode --list-keys 0x7A399B2DB06D039020CD1CE1D0F3702D61489532\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(gpg_get_executable());\n\tcommand.push_back(\"--batch\");\n\tcommand.push_back(\"--with-colons\");\n\tcommand.push_back(\"--fixed-list-mode\");\n\tcommand.push_back(\"--list-keys\");\n\tcommand.push_back(\"0x\" + fingerprint);\n\tstd::stringstream\t\tcommand_output;\n\tif (!successful_exit(exec_command(command, command_output))) {\n\t\t// This could happen if the keyring does not contain a public key with this fingerprint\n\t\treturn \"\";\n\t}\n\n\twhile (command_output.peek() != -1) {\n\t\tstd::string\t\tline;\n\t\tstd::getline(command_output, line);\n\t\tif (line.substr(0, 4) == \"uid:\") {\n\t\t\t// uid:u::::1395975462::AB97D6E3E5D8789988CA55E5F77D9E7397D05229::John Smith <jsmith@example.com>:\n\t\t\t// want the 9th column (counting from 0)\n\t\t\treturn gpg_nth_column(line, 9);\n\t\t}\n\t}\n\t\n\treturn \"\";\n}\n\n// return a list of fingerprints of public keys matching the given search query (such as jsmith@example.com)\nstd::vector<std::string> gpg_lookup_key (const std::string& query)\n{\n\tstd::vector<std::string>\tfingerprints;\n\n\t// gpg --batch --with-colons --fingerprint --list-keys jsmith@example.com\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(gpg_get_executable());\n\tcommand.push_back(\"--batch\");\n\tcommand.push_back(\"--with-colons\");\n\tcommand.push_back(\"--fingerprint\");\n\tcommand.push_back(\"--list-keys\");\n\tcommand.push_back(query);\n\tstd::stringstream\t\tcommand_output;\n\tif (successful_exit(exec_command(command, command_output))) {\n\t\tbool\t\t\tis_pubkey = false;\n\t\twhile (command_output.peek() != -1) {\n\t\t\tstd::string\t\tline;\n\t\t\tstd::getline(command_output, line);\n\t\t\tif (line.substr(0, 4) == \"pub:\") {\n\t\t\t\tis_pubkey = true;\n\t\t\t} else if (line.substr(0, 4) == \"sub:\") {\n\t\t\t\tis_pubkey = false;\n\t\t\t} else if (is_pubkey && line.substr(0, 4) == \"fpr:\") {\n\t\t\t\t// fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532:\n\t\t\t\t// want the 9th column (counting from 0)\n\t\t\t\tfingerprints.push_back(gpg_nth_column(line, 9));\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn fingerprints;\n}\n\nstd::vector<std::string> gpg_list_secret_keys ()\n{\n\t// gpg --batch --with-colons --list-secret-keys --fingerprint\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(gpg_get_executable());\n\tcommand.push_back(\"--batch\");\n\tcommand.push_back(\"--with-colons\");\n\tcommand.push_back(\"--list-secret-keys\");\n\tcommand.push_back(\"--fingerprint\");\n\tstd::stringstream\t\tcommand_output;\n\tif (!successful_exit(exec_command(command, command_output))) {\n\t\tthrow Gpg_error(\"gpg --list-secret-keys failed\");\n\t}\n\n\tstd::vector<std::string>\tsecret_keys;\n\n\twhile (command_output.peek() != -1) {\n\t\tstd::string\t\tline;\n\t\tstd::getline(command_output, line);\n\t\tif (line.substr(0, 4) == \"fpr:\") {\n\t\t\t// fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532:\n\t\t\t// want the 9th column (counting from 0)\n\t\t\tsecret_keys.push_back(gpg_nth_column(line, 9));\n\t\t}\n\t}\n\t\n\treturn secret_keys;\n}\n\nvoid gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len)\n{\n\t// gpg --batch -o FILENAME -r RECIPIENT -e\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(gpg_get_executable());\n\tcommand.push_back(\"--batch\");\n\tif (key_is_trusted) {\n\t\tcommand.push_back(\"--trust-model\");\n\t\tcommand.push_back(\"always\");\n\t}\n\tcommand.push_back(\"-o\");\n\tcommand.push_back(filename);\n\tcommand.push_back(\"-r\");\n\tcommand.push_back(\"0x\" + recipient_fingerprint);\n\tcommand.push_back(\"-e\");\n\tif (!successful_exit(exec_command_with_input(command, p, len))) {\n\t\tthrow Gpg_error(\"Failed to encrypt\");\n\t}\n}\n\nvoid gpg_decrypt_from_file (const std::string& filename, std::ostream& output)\n{\n\t// gpg -q -d FILENAME\n\tstd::vector<std::string>\tcommand;\n\tcommand.push_back(gpg_get_executable());\n\tcommand.push_back(\"-q\");\n\tcommand.push_back(\"-d\");\n\tcommand.push_back(filename);\n\tif (!successful_exit(exec_command(command, output))) {\n\t\tthrow Gpg_error(\"Failed to decrypt\");\n\t}\n}\n\n"
  },
  {
    "path": "gpg.hpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_GPG_HPP\n#define GIT_CRYPT_GPG_HPP\n\n#include <string>\n#include <vector>\n#include <cstddef>\n\nstruct Gpg_error {\n\tstd::string\tmessage;\n\n\texplicit Gpg_error (std::string m) : message(m) { }\n};\n\nstd::string\t\t\tgpg_get_uid (const std::string& fingerprint);\nstd::vector<std::string>\tgpg_lookup_key (const std::string& query);\nstd::vector<std::string>\tgpg_list_secret_keys ();\nvoid\t\t\t\tgpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len);\nvoid\t\t\t\tgpg_decrypt_from_file (const std::string& filename, std::ostream&);\n\n#endif\n"
  },
  {
    "path": "key.cpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"key.hpp\"\n#include \"util.hpp\"\n#include \"crypto.hpp\"\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <stdint.h>\n#include <fstream>\n#include <istream>\n#include <ostream>\n#include <sstream>\n#include <cstring>\n#include <stdexcept>\n#include <vector>\n\nKey_file::Entry::Entry ()\n{\n\tversion = 0;\n\texplicit_memset(aes_key, 0, AES_KEY_LEN);\n\texplicit_memset(hmac_key, 0, HMAC_KEY_LEN);\n}\n\nvoid\t\tKey_file::Entry::load (std::istream& in)\n{\n\twhile (true) {\n\t\tuint32_t\tfield_id;\n\t\tif (!read_be32(in, field_id)) {\n\t\t\tthrow Malformed();\n\t\t}\n\t\tif (field_id == KEY_FIELD_END) {\n\t\t\tbreak;\n\t\t}\n\t\tuint32_t\tfield_len;\n\t\tif (!read_be32(in, field_len)) {\n\t\t\tthrow Malformed();\n\t\t}\n\n\t\tif (field_id == KEY_FIELD_VERSION) {\n\t\t\tif (field_len != 4) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t\tif (!read_be32(in, version)) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t} else if (field_id == KEY_FIELD_AES_KEY) {\n\t\t\tif (field_len != AES_KEY_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t\tin.read(reinterpret_cast<char*>(aes_key), AES_KEY_LEN);\n\t\t\tif (in.gcount() != AES_KEY_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t} else if (field_id == KEY_FIELD_HMAC_KEY) {\n\t\t\tif (field_len != HMAC_KEY_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t\tin.read(reinterpret_cast<char*>(hmac_key), HMAC_KEY_LEN);\n\t\t\tif (in.gcount() != HMAC_KEY_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t} else if (field_id & 1) { // unknown critical field\n\t\t\tthrow Incompatible();\n\t\t} else {\n\t\t\t// unknown non-critical field - safe to ignore\n\t\t\tif (field_len > MAX_FIELD_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t\tin.ignore(field_len);\n\t\t\tif (in.gcount() != static_cast<std::streamsize>(field_len)) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid\t\tKey_file::Entry::load_legacy (uint32_t arg_version, std::istream& in)\n{\n\tversion = arg_version;\n\n\t// First comes the AES key\n\tin.read(reinterpret_cast<char*>(aes_key), AES_KEY_LEN);\n\tif (in.gcount() != AES_KEY_LEN) {\n\t\tthrow Malformed();\n\t}\n\n\t// Then the HMAC key\n\tin.read(reinterpret_cast<char*>(hmac_key), HMAC_KEY_LEN);\n\tif (in.gcount() != HMAC_KEY_LEN) {\n\t\tthrow Malformed();\n\t}\n\n\tif (in.peek() != -1) {\n\t\t// Trailing data is a good indication that we are not actually reading a\n\t\t// legacy key file.  (This is important to check since legacy key files\n\t\t// did not have any sort of file header.)\n\t\tthrow Malformed();\n\t}\n}\n\nvoid\t\tKey_file::Entry::store (std::ostream& out) const\n{\n\t// Version\n\twrite_be32(out, KEY_FIELD_VERSION);\n\twrite_be32(out, 4);\n\twrite_be32(out, version);\n\n\t// AES key\n\twrite_be32(out, KEY_FIELD_AES_KEY);\n\twrite_be32(out, AES_KEY_LEN);\n\tout.write(reinterpret_cast<const char*>(aes_key), AES_KEY_LEN);\n\n\t// HMAC key\n\twrite_be32(out, KEY_FIELD_HMAC_KEY);\n\twrite_be32(out, HMAC_KEY_LEN);\n\tout.write(reinterpret_cast<const char*>(hmac_key), HMAC_KEY_LEN);\n\n\t// End\n\twrite_be32(out, KEY_FIELD_END);\n}\n\nvoid\t\tKey_file::Entry::generate (uint32_t arg_version)\n{\n\tversion = arg_version;\n\trandom_bytes(aes_key, AES_KEY_LEN);\n\trandom_bytes(hmac_key, HMAC_KEY_LEN);\n}\n\nconst Key_file::Entry*\tKey_file::get_latest () const\n{\n\treturn is_filled() ? get(latest()) : 0;\n}\n\nconst Key_file::Entry*\tKey_file::get (uint32_t version) const\n{\n\tMap::const_iterator\tit(entries.find(version));\n\treturn it != entries.end() ? &it->second : 0;\n}\n\nvoid\t\tKey_file::add (const Entry& entry)\n{\n\tentries[entry.version] = entry;\n}\n\n\nvoid\t\tKey_file::load_legacy (std::istream& in)\n{\n\tentries[0].load_legacy(0, in);\n}\n\nvoid\t\tKey_file::load (std::istream& in)\n{\n\tunsigned char\tpreamble[16];\n\tin.read(reinterpret_cast<char*>(preamble), 16);\n\tif (in.gcount() != 16) {\n\t\tthrow Malformed();\n\t}\n\tif (std::memcmp(preamble, \"\\0GITCRYPTKEY\", 12) != 0) {\n\t\tthrow Malformed();\n\t}\n\tif (load_be32(preamble + 12) != FORMAT_VERSION) {\n\t\tthrow Incompatible();\n\t}\n\tload_header(in);\n\twhile (in.peek() != -1) {\n\t\tEntry\t\tentry;\n\t\tentry.load(in);\n\t\tadd(entry);\n\t}\n}\n\nvoid\t\tKey_file::load_header (std::istream& in)\n{\n\twhile (true) {\n\t\tuint32_t\tfield_id;\n\t\tif (!read_be32(in, field_id)) {\n\t\t\tthrow Malformed();\n\t\t}\n\t\tif (field_id == HEADER_FIELD_END) {\n\t\t\tbreak;\n\t\t}\n\t\tuint32_t\tfield_len;\n\t\tif (!read_be32(in, field_len)) {\n\t\t\tthrow Malformed();\n\t\t}\n\n\t\tif (field_id == HEADER_FIELD_KEY_NAME) {\n\t\t\tif (field_len > KEY_NAME_MAX_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t\tif (field_len == 0) {\n\t\t\t\t// special case field_len==0 to avoid possible undefined behavior\n\t\t\t\t// edge cases with an empty std::vector (particularly, &bytes[0]).\n\t\t\t\tkey_name.clear();\n\t\t\t} else {\n\t\t\t\tstd::vector<char>\tbytes(field_len);\n\t\t\t\tin.read(&bytes[0], field_len);\n\t\t\t\tif (in.gcount() != static_cast<std::streamsize>(field_len)) {\n\t\t\t\t\tthrow Malformed();\n\t\t\t\t}\n\t\t\t\tkey_name.assign(&bytes[0], field_len);\n\t\t\t}\n\t\t\tif (!validate_key_name(key_name.c_str())) {\n\t\t\t\tkey_name.clear();\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t} else if (field_id & 1) { // unknown critical field\n\t\t\tthrow Incompatible();\n\t\t} else {\n\t\t\t// unknown non-critical field - safe to ignore\n\t\t\tif (field_len > MAX_FIELD_LEN) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t\tin.ignore(field_len);\n\t\t\tif (in.gcount() != static_cast<std::streamsize>(field_len)) {\n\t\t\t\tthrow Malformed();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid\t\tKey_file::store (std::ostream& out) const\n{\n\tout.write(\"\\0GITCRYPTKEY\", 12);\n\twrite_be32(out, FORMAT_VERSION);\n\tif (!key_name.empty()) {\n\t\twrite_be32(out, HEADER_FIELD_KEY_NAME);\n\t\twrite_be32(out, key_name.size());\n\t\tout.write(key_name.data(), key_name.size());\n\t}\n\twrite_be32(out, HEADER_FIELD_END);\n\tfor (Map::const_iterator it(entries.begin()); it != entries.end(); ++it) {\n\t\tit->second.store(out);\n\t}\n}\n\nbool\t\tKey_file::load_from_file (const char* key_file_name)\n{\n\tstd::ifstream\tkey_file_in(key_file_name, std::fstream::binary);\n\tif (!key_file_in) {\n\t\treturn false;\n\t}\n\tload(key_file_in);\n\treturn true;\n}\n\nbool\t\tKey_file::store_to_file (const char* key_file_name) const\n{\n\tcreate_protected_file(key_file_name);\n\tstd::ofstream\tkey_file_out(key_file_name, std::fstream::binary);\n\tif (!key_file_out) {\n\t\treturn false;\n\t}\n\tstore(key_file_out);\n\tkey_file_out.close();\n\tif (!key_file_out) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstd::string\tKey_file::store_to_string () const\n{\n\tstd::ostringstream\tss;\n\tstore(ss);\n\treturn ss.str();\n}\n\nvoid\t\tKey_file::generate ()\n{\n\tuint32_t\tversion(is_empty() ? 0 : latest() + 1);\n\tentries[version].generate(version);\n}\n\nuint32_t\tKey_file::latest () const\n{\n\tif (is_empty()) {\n\t\tthrow std::invalid_argument(\"Key_file::latest\");\n\t}\n\treturn entries.begin()->first;\n}\n\nbool validate_key_name (const char* key_name, std::string* reason)\n{\n\tif (!*key_name) {\n\t\tif (reason) { *reason = \"Key name may not be empty\"; }\n\t\treturn false;\n\t}\n\n\tif (std::strcmp(key_name, \"default\") == 0) {\n\t\tif (reason) { *reason = \"`default' is not a legal key name\"; }\n\t\treturn false;\n\t}\n\t// Need to be restrictive with key names because they're used as part of a Git filter name\n\tsize_t\t\tlen = 0;\n\twhile (char c = *key_name++) {\n\t\tif (!std::isalnum(c) && c != '-' && c != '_') {\n\t\t\tif (reason) { *reason = \"Key names may contain only A-Z, a-z, 0-9, '-', and '_'\"; }\n\t\t\treturn false;\n\t\t}\n\t\tif (++len > KEY_NAME_MAX_LEN) {\n\t\t\tif (reason) { *reason = \"Key name is too long\"; }\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n"
  },
  {
    "path": "key.hpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_KEY_HPP\n#define GIT_CRYPT_KEY_HPP\n\n#include <map>\n#include <functional>\n#include <stdint.h>\n#include <iosfwd>\n#include <string>\n\nenum {\n\tHMAC_KEY_LEN = 64,\n\tAES_KEY_LEN = 32\n};\n\nstruct Key_file {\npublic:\n\tstruct Entry {\n\t\tuint32_t\t\tversion;\n\t\tunsigned char\t\taes_key[AES_KEY_LEN];\n\t\tunsigned char\t\thmac_key[HMAC_KEY_LEN];\n\n\t\tEntry ();\n\n\t\tvoid\t\t\tload (std::istream&);\n\t\tvoid\t\t\tload_legacy (uint32_t version, std::istream&);\n\t\tvoid\t\t\tstore (std::ostream&) const;\n\t\tvoid\t\t\tgenerate (uint32_t version);\n\t};\n\n\tstruct Malformed { }; // exception class\n\tstruct Incompatible { }; // exception class\n\n\tconst Entry*\t\t\tget_latest () const;\n\n\tconst Entry*\t\t\tget (uint32_t version) const;\n\tvoid\t\t\t\tadd (const Entry&);\n\n\tvoid\t\t\t\tload_legacy (std::istream&);\n\tvoid\t\t\t\tload (std::istream&);\n\tvoid\t\t\t\tstore (std::ostream&) const;\n\n\tbool\t\t\t\tload_from_file (const char* filename);\n\tbool\t\t\t\tstore_to_file (const char* filename) const;\n\n\tstd::string\t\t\tstore_to_string () const;\n\n\tvoid\t\t\t\tgenerate ();\n\n\tbool\t\t\t\tis_empty () const { return entries.empty(); }\n\tbool\t\t\t\tis_filled () const { return !is_empty(); }\n\n\tuint32_t\t\t\tlatest () const;\n\n\tvoid\t\t\t\tset_key_name (const char* k) { key_name = k ? k : \"\"; }\n\tconst char*\t\t\tget_key_name () const { return key_name.empty() ? 0 : key_name.c_str(); }\nprivate:\n\ttypedef std::map<uint32_t, Entry, std::greater<uint32_t> > Map;\n\tenum { FORMAT_VERSION = 2 };\n\n\tMap\t\t\t\tentries;\n\tstd::string\t\t\tkey_name;\n\n\tvoid\t\t\t\tload_header (std::istream&);\n\n\tenum {\n\t\tHEADER_FIELD_END\t= 0,\n\t\tHEADER_FIELD_KEY_NAME\t= 1\n\t};\n\tenum {\n\t\tKEY_FIELD_END\t\t= 0,\n\t\tKEY_FIELD_VERSION\t= 1,\n\t\tKEY_FIELD_AES_KEY\t= 3,\n\t\tKEY_FIELD_HMAC_KEY\t= 5\n\t};\n\tenum {\n\t\tMAX_FIELD_LEN\t\t= 1<<20\n\t};\n};\n\nenum {\n\tKEY_NAME_MAX_LEN = 128\n};\n\nbool validate_key_name (const char* key_name, std::string* reason =0);\n\n#endif\n"
  },
  {
    "path": "man/git-crypt.xml",
    "content": "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" \"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">\n<refentry>\n\t<!--\n\t\tCopyright (c) 2015 Andrew Ayer\n\n\t\tSee COPYING file for license information.\n\t-->\n\t<refentryinfo>\n\t\t<title>git-crypt</title>\n\t\t<date>2022-04-21</date>\n\t\t<productname>git-crypt 0.8.0</productname>\n\n\t\t<author>\n\t\t\t<othername>Andrew Ayer</othername>\n\t\t\t<contrib></contrib>\n\t\t\t<email>agwa@andrewayer.name</email>\n\t\t\t<uri>https://www.agwa.name</uri>\n\t\t</author>\n\t</refentryinfo>\n\n\t<refmeta>\n\t\t<refentrytitle>git-crypt</refentrytitle>\n\t\t<manvolnum>1</manvolnum>\n\t</refmeta>\n\n\t<refnamediv>\n\t\t<refname>git-crypt</refname>\n\t\t<refpurpose>transparent file encryption in Git</refpurpose>\n\t</refnamediv>\n\n\t<refsynopsisdiv>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt <arg choice=\"opt\"><replaceable>OPTIONS</replaceable></arg> <arg choice=\"plain\"><replaceable>COMMAND</replaceable></arg> <arg choice=\"opt\" rep=\"repeat\"><replaceable>ARGS</replaceable></arg></command>\n\t\t</cmdsynopsis>\n\t</refsynopsisdiv>\n\n\t<refsynopsisdiv>\n\t\t<title>Common commands</title>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt init</command>\n\t\t</cmdsynopsis>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt status</command>\n\t\t</cmdsynopsis>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt lock</command>\n\t\t</cmdsynopsis>\n\t</refsynopsisdiv>\n\t<refsynopsisdiv>\n\t\t<title>GPG commands</title>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt add-gpg-user <arg choice=\"plain\"><replaceable>GPG_USER_ID</replaceable></arg></command>\n\t\t</cmdsynopsis>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt unlock</command>\n\t\t</cmdsynopsis>\n\t</refsynopsisdiv>\n\t<refsynopsisdiv>\n\t\t<title>Symmetric key commands</title>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt export-key <arg choice=\"plain\"><replaceable>OUTPUT_KEY_FILE</replaceable></arg></command>\n\t\t</cmdsynopsis>\n\t\t<cmdsynopsis>\n\t\t\t<command>git-crypt unlock <arg choice=\"plain\"><replaceable>KEY_FILE</replaceable></arg></command>\n\t\t</cmdsynopsis>\n\t</refsynopsisdiv>\n\n\t<refsect1>\n\t\t<title>Description</title>\n\n\t\t<para>\n\t\t\t<command>git-crypt</command> enables transparent encryption and decryption\n\t\t\tof files in a git repository. Files which you choose to protect are encrypted when committed,\n\t\t\tand decrypted when checked out. git-crypt lets you freely share a repository containing a mix of\n\t\t\tpublic and private content. git-crypt gracefully degrades, so developers without the secret key\n\t\t\tcan still clone and commit to a repository with encrypted files. This lets you store your secret\n\t\t\tmaterial (such as keys or passwords) in the same repository as your code, without requiring you\n\t\t\tto lock down your entire repository.  \n\t\t</para>\n\t</refsect1>\n\n\t<refsect1>\n\t\t<title>Commands</title>\n\n\t\t<para>\n\t\t\t<command>git-crypt</command> is logically divided into several sub-commands which\n\t\t\tperform distinct tasks.  Each sub-command, and its arguments,\n\t\t\tare documented below.  Note that arguments and options to sub-commands must be\n\t\t\tspecified on the command line <emphasis>after</emphasis> the name of the sub-command.\n\t\t</para>\n\n\t\t<variablelist>\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>init <arg choice=\"opt\"><replaceable>OPTIONS</replaceable></arg></option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tGenerate a key and prepare the current Git repository to use git-crypt.\n\t\t\t\t\t</para>\n\n\t\t\t\t\t<para>\n\t\t\t\t\t\tThe following options are understood:\n\t\t\t\t\t</para>\n\t\t\t\t\t<variablelist>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-k</option> <replaceable>KEY_NAME</replaceable></term>\n\t\t\t\t\t\t\t<term><option>--key-name</option> <replaceable>KEY_NAME</replaceable></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tInitialize the given key instead of the default key.  git-crypt\n\t\t\t\t\t\t\t\t\tsupports multiple keys per repository, allowing you to share\n\t\t\t\t\t\t\t\t\tdifferent files with different sets of collaborators.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t</variablelist>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>status <arg choice=\"opt\"><replaceable>OPTIONS</replaceable></arg></option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tDisplay a list of files in the repository, with their status (encrypted or unencrypted).\n\t\t\t\t\t</para>\n\n\t\t\t\t\t<para>\n\t\t\t\t\t\tThe following options are understood:\n\t\t\t\t\t</para>\n\t\t\t\t\t<variablelist>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-e</option></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tShow only encrypted files.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-u</option></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tShow only unencrypted files.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-f</option></term>\n\t\t\t\t\t\t\t<term><option>--fix</option></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tEncrypt files that should be encrypted but were\n\t\t\t\t\t\t\t\t\tcommitted to the repository or added to the index\n\t\t\t\t\t\t\t\t\twithout encryption.  (This can happen if a file\n\t\t\t\t\t\t\t\t\tis added before git-crypt is initialized or before\n\t\t\t\t\t\t\t\t\tthe file is added to the gitattributes file.)\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t</variablelist>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>add-gpg-user <arg choice=\"opt\"><replaceable>OPTIONS</replaceable></arg> <arg choice=\"plain\" rep=\"repeat\"><replaceable>GPG_USER_ID</replaceable></arg></option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tAdd the users with the given GPG user IDs as collaborators.  Specifically,\n\t\t\t\t\t\tgit-crypt uses <citerefentry><refentrytitle>gpg</refentrytitle><manvolnum>1</manvolnum></citerefentry>\n\t\t\t\t\t\tto encrypt the shared symmetric key\n\t\t\t\t\t\tto the public keys of each GPG user ID, and stores the GPG-encrypted\n\t\t\t\t\t\tkeys in the <filename>.git-crypt</filename> directory at the root of the repository.\n\t\t\t\t\t</para>\n\n\t\t\t\t\t<para>\n\t\t\t\t\t\t<replaceable>GPG_USER_ID</replaceable> can be a key ID, a full fingerprint, an email address, or anything\n\t\t\t\t\t\telse that uniquely identifies a public key to GPG (see \"HOW TO SPECIFY\n\t\t\t\t\t\tA USER ID\" in the <citerefentry><refentrytitle>gpg</refentrytitle><manvolnum>1</manvolnum></citerefentry>\n\t\t\t\t\t\tman page).\n\t\t\t\t\t</para>\n\n\t\t\t\t\t<para>\n\t\t\t\t\t\tThe following options are understood:\n\t\t\t\t\t</para>\n\t\t\t\t\t<variablelist>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-k</option> <replaceable>KEY_NAME</replaceable></term>\n\t\t\t\t\t\t\t<term><option>--key-name</option> <replaceable>KEY_NAME</replaceable></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tGrant access to the given key, rather than the default key.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-n</option></term>\n\t\t\t\t\t\t\t<term><option>--no-commit</option></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tDon't automatically commit the changes to the <filename>.git-crypt</filename>\n\t\t\t\t\t\t\t\t\tdirectory.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>--trusted</option></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tAssume that the GPG keys specified on the command line are trusted;\n\t\t\t\t\t\t\t\t\ti.e. they actually belong to the users that they claim to belong to.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tWithout this option, git-crypt uses the same trust model as GPG,\n\t\t\t\t\t\t\t\t\twhich is based on the Web of Trust by default.  Under this\n\t\t\t\t\t\t\t\t\tmodel, git-crypt will reject GPG keys that do not have\n\t\t\t\t\t\t\t\t\ttrusted signatures.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tIf you don't want to use the Web of Trust, you can either change\n\t\t\t\t\t\t\t\t\tGPG's trust model by setting the <option>trust-model</option>\n\t\t\t\t\t\t\t\t\toption in <filename>~/.gnupg/gpg.conf</filename> (see\n\t\t\t\t\t\t\t\t\t<citerefentry><refentrytitle>gpg</refentrytitle><manvolnum>1</manvolnum></citerefentry>),\n\t\t\t\t\t\t\t\t\tor use the <option>--trusted</option> option to <command>add-gpg-user</command>\n\t\t\t\t\t\t\t\t\ton a case-by-case basis.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t</variablelist>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>unlock <!--<arg choice=\"opt\"><replaceable>OPTIONS</replaceable></arg> --><arg choice=\"opt\" rep=\"repeat\"><replaceable>KEY_FILE</replaceable></arg></option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tDecrypt the repository.  If one or more key files are specified on the command line,\n\t\t\t\t\t\tgit-crypt attempts to decrypt using those shared symmetric keys.  If no key files\n\t\t\t\t\t\tare specified, git-crypt attempts to decrypt using a GPG-encrypted key stored in\n\t\t\t\t\t\tthe repository's .git-crypt directory.\n\t\t\t\t\t</para>\n\n\t\t\t\t\t<para>\n\t\t\t\t\t\tThis command takes no options.\n\t\t\t\t\t</para>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>export-key <arg choice=\"opt\"><replaceable>OPTIONS</replaceable></arg> <arg choice=\"plain\"><replaceable>FILENAME</replaceable></arg></option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tExport the repository's shared symmetric key to the given file.\n\t\t\t\t\t</para>\n\n\t\t\t\t\t<para>\n\t\t\t\t\t\tThe following options are understood:\n\t\t\t\t\t</para>\n\t\t\t\t\t<variablelist>\n\t\t\t\t\t\t<varlistentry>\n\t\t\t\t\t\t\t<term><option>-k</option> <replaceable>KEY_NAME</replaceable></term>\n\t\t\t\t\t\t\t<term><option>--key-name</option> <replaceable>KEY_NAME</replaceable></term>\n\n\t\t\t\t\t\t\t<listitem>\n\t\t\t\t\t\t\t\t<para>\n\t\t\t\t\t\t\t\t\tExport the given key, rather than the default key.\n\t\t\t\t\t\t\t\t</para>\n\t\t\t\t\t\t\t</listitem>\n\t\t\t\t\t\t</varlistentry>\n\t\t\t\t\t</variablelist>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>help <arg choice=\"opt\"><replaceable>COMMAND</replaceable></arg></option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tDisplay help for the given <arg choice=\"plain\"><replaceable>COMMAND</replaceable></arg>,\n\t\t\t\t\t\tor an overview of all commands if no command is specified.\n\t\t\t\t\t</para>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t\t<varlistentry>\n\t\t\t\t<term><option>version</option></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>\n\t\t\t\t\t\tPrint the currently-installed version of <command>git-crypt</command>.\n\t\t\t\t\t\tThe format of the output is always \"git-crypt\", followed by a space,\n\t\t\t\t\t\tfollowed by the dotted version number.\n\t\t\t\t\t</para>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\n\t\t</variablelist>\n\t</refsect1>\n\n\t<refsect1>\n\t\t<title>Using git-crypt</title>\n\n\t\t<para>\n\t\t\tFirst, you prepare a repository to use git-crypt by running <command>git-crypt init</command>.\n\t\t</para>\n\n\t\t<para>\n\t\t\tThen, you specify the files to encrypt by creating a\n\t\t\t<citerefentry><refentrytitle>gitattributes</refentrytitle><manvolnum>5</manvolnum></citerefentry> file.\n\t\t\tEach file which you want to encrypt should be assigned the \"<literal>filter=git-crypt diff=git-crypt</literal>\"\n\t\t\tattributes.  For example:\n\t\t</para>\n\n\t\t<screen>secretfile filter=git-crypt diff=git-crypt&#10;*.key filter=git-crypt diff=git-crypt</screen>\n\n\t\t<para>\n\t\t\tLike a <filename>.gitignore</filename> file, <filename>.gitattributes</filename> files can match wildcards and\n\t\t\tshould be checked into the repository.  Make sure you don't accidentally encrypt the\n\t\t\t<filename>.gitattributes</filename> file itself (or other git files like <filename>.gitignore</filename>\n\t\t\tor <filename>.gitmodules</filename>).  Make sure your <filename>.gitattributes</filename> rules\n\t\t\tare in place <emphasis>before</emphasis> you add sensitive files, or those files won't be encrypted!\n\t\t</para>\n\n\t\t<para>\n\t\t\tTo share the repository with others (or with yourself) using GPG, run:\n\t\t</para>\n\n\t\t<screen>git-crypt add-gpg-user <replaceable>GPG_USER_ID</replaceable></screen>\n\n\t\t<para>\n\t\t\t<replaceable>GPG_USER_ID</replaceable> can be a key ID, a full fingerprint, an email address, or anything\n\t\t\telse that uniquely identifies a public key to GPG.  Note: <command>git-crypt add-gpg-user</command> will\n\t\t\tadd and commit a GPG-encrypted key file in the <filename>.git-crypt</filename> directory of\n\t\t\tthe root of your repository.\n\t\t</para>\n\n\t\t<para>\n\t\t\tAlternatively, you can export a symmetric secret key, which you must\n\t\t\tsecurely convey to collaborators (GPG is not required, and no files\n\t\t\tare added to your repository):\n\t\t</para>\n\n\t\t<screen>git-crypt export-key <replaceable>/path/to/key</replaceable></screen>\n\n\t\t<para>\n\t\t\tAfter cloning a repository with encrypted files, unlock with with GPG:\n\t\t</para>\n\n\t\t<screen>git-crypt unlock</screen>\n\n\t\t<para>\n\t\t\tOr with a symmetric key:\n\t\t</para>\n\n\t\t<screen>git-crypt unlock /path/to/key</screen>\n\n\t\t<para>\n\t\t\tThat's all you need to do - after git-crypt is set up (either with\n\t\t\t<command>git-crypt init</command> or <command>git-crypt unlock</command>),\n\t\t\tyou can use git normally - encryption and decryption happen transparently.\n\t\t</para>\n\n\t</refsect1>\n\n\t<refsect1>\n\t\t<title>The .gitattributes file</title>\n\n\t\t<para>\n\t\t\tThe <filename>.gitattributes</filename> file is documented in\n\t\t\t<citerefentry><refentrytitle>gitattributes</refentrytitle><manvolnum>5</manvolnum></citerefentry>.\n\t\t\tThe file pattern format is the same as the one used by <filename>.gitignore</filename>,\n\t\t\tas documented in <citerefentry><refentrytitle>gitignore</refentrytitle><manvolnum>5</manvolnum></citerefentry>,\n\t\t\twith the exception that specifying merely a directory (e.g. \"<literal>/dir/</literal>\")\n\t\t\tis <emphasis>not</emphasis> sufficient to encrypt all files beneath it.\n\t\t</para>\n\n\t\t<para>\n\t\t\tAlso note that the pattern \"<literal>dir/*</literal>\" does not match files under\n\t\t\tsub-directories of dir/.  To encrypt an entire sub-tree dir/, place the\n\t\t\tfollowing in <filename>dir/.gitattributes</filename>:\n\t\t</para>\n\n\t\t<screen>* filter=git-crypt diff=git-crypt&#10;.gitattributes !filter !diff</screen>\n\n\t\t<para>\n\t\t\tThe second pattern is essential for ensuring that <filename>.gitattributes</filename> itself\n\t\t\tis not encrypted.\n\t\t</para>\n\t</refsect1>\n\n\t<refsect1>\n\t\t<title>Multiple Key Support</title>\n\n\t\t<para>\n\t\t\tIn addition to the implicit default key, git-crypt supports alternative\n\t\t\tkeys which can be used to encrypt specific files and can be shared with\n\t\t\tspecific GPG users.  This is useful if you want to grant different\n\t\t\tcollaborators access to different sets of files.\n\t\t</para>\n\n\t\t<para>\n\t\t\tTo generate an alternative key named <replaceable>KEYNAME</replaceable>,\n\t\t\tpass the <command>-k <replaceable>KEYNAME</replaceable></command>\n\t\t\toption to <command>git-crypt init</command> as follows:\n\t\t</para>\n\n\t\t<screen>git-crypt init -k <replaceable>KEYNAME</replaceable></screen>\n\n\t\t<para>\n\t\t\tTo encrypt a file with an alternative key, use the <literal>git-crypt-<replaceable>KEYNAME</replaceable></literal>\n\t\t\tfilter in <filename>.gitattributes</filename> as follows:\n\t\t</para>\n\n\t\t<screen><replaceable>secretfile</replaceable> filter=git-crypt-<replaceable>KEYNAME</replaceable> diff=git-crypt-<replaceable>KEYNAME</replaceable></screen>\n\n\t\t<para>\n\t\t\tTo export an alternative key or share it with a GPG user, pass the\n\t\t\t<command>-k <replaceable>KEYNAME</replaceable></command> option to\n\t\t\t<command>git-crypt export-key</command> or <command>git-crypt add-gpg-user</command>\n\t\t\tas follows:\n\t\t</para>\n\n\t\t<screen>git-crypt export-key -k <replaceable>KEYNAME</replaceable> <filename><replaceable>/path/to/keyfile</replaceable></filename>&#10;git-crypt add-gpg-user -k <replaceable>KEYNAME</replaceable> <replaceable>GPG_USER_ID</replaceable></screen>\n\n\t\t<para>\n\t\t\tTo unlock a repository with an alternative key, use <command>git-crypt unlock</command>\n\t\t\tnormally.  git-crypt will automatically determine which key is being used.\n\t\t</para>\n\t</refsect1>\n\t<!--\n\t<refsect1>\n\t\t<title>Global options</title>\n\n\t\t<para>\n\t\t\tThe following options are understood by <command>git-crypt</command> and can\n\t\t\tbe used with any sub-command.  Since they apply globally\n\t\t\tto <command>git-crypt</command>, they must be specified on the command line\n\t\t\t<emphasis>before</emphasis> the sub-command name.\n\t\t</para>\n\t\t<variablelist>\n\t\t</variablelist>\n\t</refsect1>\n\t-->\n\n\t<!--\n\t<refsect1>\n\t\t<title>Files</title>\n\t\t<variablelist>\n\t\t\t<varlistentry>\n\t\t\t\t<term><filename>/path/to/file</filename></term>\n\t\t\t\t<listitem><para>Description.</para></listitem>\n\t\t\t</varlistentry>\n\t\t</variablelist>\n\t</refsect1>\n\t-->\n\n\t<!--\n\t<refsect1>\n\t\t<title>Environment Variables</title>\n\n\t\t<variablelist class='environment-variables'>\n\t\t\t<varlistentry>\n\t\t\t\t<term><varname>NAME</varname></term>\n\t\t\t\t<listitem>\n\t\t\t\t\t<para>Description.</para>\n\t\t\t\t</listitem>\n\t\t\t</varlistentry>\n\t\t</variablelist>\n\t</refsect1>\n\t-->\n\n\t<!-- TODO: examples section\n\t<refsect1>\n\t\t<title>Examples</title>\n\n\t\t<para>Hello world?</para>\n\t</refsect1>\n\t-->\n\n\t<refsect1>\n\t\t<title>See Also</title>\n\t\t<para>\n\t\t\t<citerefentry><refentrytitle>git</refentrytitle><manvolnum>1</manvolnum></citerefentry>,\n\t\t\t<citerefentry><refentrytitle>gitattributes</refentrytitle><manvolnum>5</manvolnum></citerefentry>,\n\t\t\t<ulink url=\"https://www.agwa.name/projects/git-crypt\">git-crypt home page</ulink>,\n\t\t\t<ulink url=\"https://github.com/AGWA/git-crypt\">GitHub repository</ulink>\n\t\t</para>\n\t</refsect1>\n\n</refentry>\n"
  },
  {
    "path": "man/man1/.gitignore",
    "content": "git-crypt.1\n"
  },
  {
    "path": "parse_options.cpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Except as contained in this notice, the name(s) of the above copyright\n * holders shall not be used in advertising or otherwise to promote the\n * sale, use or other dealings in this Software without prior written\n * authorization.\n */\n\n#include \"parse_options.hpp\"\n#include <cstring>\n\n\nstatic const Option_def* find_option (const Options_list& options, const std::string& name)\n{\n\tfor (Options_list::const_iterator opt(options.begin()); opt != options.end(); ++opt) {\n\t\tif (opt->name == name) {\n\t\t\treturn &*opt;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint parse_options (const Options_list& options, int argc, const char** argv)\n{\n\tint\targi = 0;\n\n\twhile (argi < argc && argv[argi][0] == '-' && argv[argi][1] != '\\0') {\n\t\tif (std::strcmp(argv[argi], \"--\") == 0) {\n\t\t\t++argi;\n\t\t\tbreak;\n\t\t} else if (std::strncmp(argv[argi], \"--\", 2) == 0) {\n\t\t\tstd::string\t\t\toption_name;\n\t\t\tconst char*\t\t\toption_value = 0;\n\t\t\tif (const char* eq = std::strchr(argv[argi], '=')) {\n\t\t\t\toption_name.assign(argv[argi], eq);\n\t\t\t\toption_value = eq + 1;\n\t\t\t} else {\n\t\t\t\toption_name = argv[argi];\n\t\t\t}\n\t\t\t++argi;\n\n\t\t\tconst Option_def*\t\topt(find_option(options, option_name));\n\t\t\tif (!opt) {\n\t\t\t\tthrow Option_error(option_name, \"Invalid option\");\n\t\t\t}\n\n\t\t\tif (opt->is_set) {\n\t\t\t\t*opt->is_set = true;\n\t\t\t}\n\t\t\tif (opt->value) {\n\t\t\t\tif (option_value) {\n\t\t\t\t\t*opt->value = option_value;\n\t\t\t\t} else {\n\t\t\t\t\tif (argi >= argc) {\n\t\t\t\t\t\tthrow Option_error(option_name, \"Option requires a value\");\n\t\t\t\t\t}\n\t\t\t\t\t*opt->value = argv[argi];\n\t\t\t\t\t++argi;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (option_value) {\n\t\t\t\t\tthrow Option_error(option_name, \"Option takes no value\");\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst char*\t\t\targ = argv[argi] + 1;\n\t\t\t++argi;\n\t\t\twhile (*arg) {\n\t\t\t\tstd::string\t\toption_name(\"-\");\n\t\t\t\toption_name.push_back(*arg);\n\t\t\t\t++arg;\n\n\t\t\t\tconst Option_def*\topt(find_option(options, option_name));\n\t\t\t\tif (!opt) {\n\t\t\t\t\tthrow Option_error(option_name, \"Invalid option\");\n\t\t\t\t}\n\t\t\t\tif (opt->is_set) {\n\t\t\t\t\t*opt->is_set = true;\n\t\t\t\t}\n\t\t\t\tif (opt->value) {\n\t\t\t\t\tif (*arg) {\n\t\t\t\t\t\t*opt->value = arg;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (argi >= argc) {\n\t\t\t\t\t\t\tthrow Option_error(option_name, \"Option requires a value\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t*opt->value = argv[argi];\n\t\t\t\t\t\t++argi;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn argi;\n}\n"
  },
  {
    "path": "parse_options.hpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Except as contained in this notice, the name(s) of the above copyright\n * holders shall not be used in advertising or otherwise to promote the\n * sale, use or other dealings in this Software without prior written\n * authorization.\n */\n\n#ifndef PARSE_OPTIONS_HPP\n#define PARSE_OPTIONS_HPP\n\n#include <string>\n#include <vector>\n\nstruct Option_def {\n\tstd::string\tname;\n\tbool*\t\tis_set;\n\tconst char**\tvalue;\n\n\tOption_def () : is_set(0), value(0) { }\n\tOption_def (const std::string& arg_name, bool* arg_is_set)\n\t: name(arg_name), is_set(arg_is_set), value(0) { }\n\tOption_def (const std::string& arg_name, const char** arg_value)\n\t: name(arg_name), is_set(0), value(arg_value) { }\n};\n\ntypedef std::vector<Option_def> Options_list;\n\nint parse_options (const Options_list& options, int argc, const char** argv);\n\nstruct Option_error {\n\tstd::string\toption_name;\n\tstd::string\tmessage;\n\n\tOption_error (const std::string& n, const std::string& m) : option_name(n), message(m) { }\n};\n\n#endif\n"
  },
  {
    "path": "util-unix.cpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <sys/time.h>\n#include <errno.h>\n#include <utime.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <limits.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <dirent.h>\n#include <vector>\n#include <string>\n#include <cstring>\n#include <cstddef>\n#include <algorithm>\n\nstd::string System_error::message () const\n{\n\tstd::string\tmesg(action);\n\tif (!target.empty()) {\n\t\tmesg += \": \";\n\t\tmesg += target;\n\t}\n\tif (error) {\n\t\tmesg += \": \";\n\t\tmesg += strerror(error);\n\t}\n\treturn mesg;\n}\n\nvoid\ttemp_fstream::open (std::ios_base::openmode mode)\n{\n\tclose();\n\n\tconst char*\t\ttmpdir = getenv(\"TMPDIR\");\n\tsize_t\t\t\ttmpdir_len = tmpdir ? std::strlen(tmpdir) : 0;\n\tif (tmpdir_len == 0 || tmpdir_len > 4096) {\n\t\t// no $TMPDIR or it's excessively long => fall back to /tmp\n\t\ttmpdir = \"/tmp\";\n\t\ttmpdir_len = 4;\n\t}\n\tstd::vector<char>\tpath_buffer(tmpdir_len + 18);\n\tchar*\t\t\tpath = &path_buffer[0];\n\tstd::strcpy(path, tmpdir);\n\tstd::strcpy(path + tmpdir_len, \"/git-crypt.XXXXXX\");\n\tmode_t\t\t\told_umask = umask(0077);\n\tint\t\t\tfd = mkstemp(path);\n\tif (fd == -1) {\n\t\tint\t\tmkstemp_errno = errno;\n\t\tumask(old_umask);\n\t\tthrow System_error(\"mkstemp\", \"\", mkstemp_errno);\n\t}\n\tumask(old_umask);\n\tstd::fstream::open(path, mode);\n\tif (!std::fstream::is_open()) {\n\t\tunlink(path);\n\t\t::close(fd);\n\t\tthrow System_error(\"std::fstream::open\", path, 0);\n\t}\n\tunlink(path);\n\t::close(fd);\n}\n\nvoid\ttemp_fstream::close ()\n{\n\tif (std::fstream::is_open()) {\n\t\tstd::fstream::close();\n\t}\n}\n\nvoid\tmkdir_parent (const std::string& path)\n{\n\tstd::string::size_type\t\tslash(path.find('/', 1));\n\twhile (slash != std::string::npos) {\n\t\tstd::string\t\tprefix(path.substr(0, slash));\n\t\tstruct stat\t\tstatus;\n\t\tif (stat(prefix.c_str(), &status) == 0) {\n\t\t\t// already exists - make sure it's a directory\n\t\t\tif (!S_ISDIR(status.st_mode)) {\n\t\t\t\tthrow System_error(\"mkdir_parent\", prefix, ENOTDIR);\n\t\t\t}\n\t\t} else {\n\t\t\tif (errno != ENOENT) {\n\t\t\t\tthrow System_error(\"mkdir_parent\", prefix, errno);\n\t\t\t}\n\t\t\t// doesn't exist - mkdir it\n\t\t\tif (mkdir(prefix.c_str(), 0777) == -1) {\n\t\t\t\tthrow System_error(\"mkdir\", prefix, errno);\n\t\t\t}\n\t\t}\n\n\t\tslash = path.find('/', slash + 1);\n\t}\n}\n\nstd::string our_exe_path ()\n{\n\tif (argv0[0] == '/') {\n\t\t// argv[0] starts with / => it's an absolute path\n\t\treturn argv0;\n\t} else if (std::strchr(argv0, '/')) {\n\t\t// argv[0] contains / => it a relative path that should be resolved\n\t\tchar*\t\tresolved_path_p = realpath(argv0, nullptr);\n\t\tstd::string\tresolved_path(resolved_path_p);\n\t\tfree(resolved_path_p);\n\t\treturn resolved_path;\n\t} else {\n\t\t// argv[0] is just a bare filename => not much we can do\n\t\treturn argv0;\n\t}\n}\n\nint\texit_status (int wait_status)\n{\n\treturn wait_status != -1 && WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : -1;\n}\n\nvoid\ttouch_file (const std::string& filename)\n{\n\tif (utimes(filename.c_str(), nullptr) == -1 && errno != ENOENT) {\n\t\tthrow System_error(\"utimes\", filename, errno);\n\t}\n}\n\nvoid\tremove_file (const std::string& filename)\n{\n\tif (unlink(filename.c_str()) == -1 && errno != ENOENT) {\n\t\tthrow System_error(\"unlink\", filename, errno);\n\t}\n}\n\nstatic void\tinit_std_streams_platform ()\n{\n}\n\nvoid\tcreate_protected_file (const char* path)\n{\n\tint\tfd = open(path, O_WRONLY | O_CREAT, 0600);\n\tif (fd == -1) {\n\t\tthrow System_error(\"open\", path, errno);\n\t}\n\tclose(fd);\n}\n\nint util_rename (const char* from, const char* to)\n{\n\treturn rename(from, to);\n}\n\nstd::vector<std::string> get_directory_contents (const char* path)\n{\n\tstd::vector<std::string>\t\tcontents;\n\n\tDIR*\t\t\t\t\tdir = opendir(path);\n\tif (!dir) {\n\t\tthrow System_error(\"opendir\", path, errno);\n\t}\n\ttry {\n\t\terrno = 0;\n\t\t// Note: readdir is reentrant in new implementations. In old implementations,\n\t\t// it might not be, but git-crypt isn't multi-threaded so that's OK.\n\t\t// We don't use readdir_r because it's buggy and deprecated:\n\t\t//  https://womble.decadent.org.uk/readdir_r-advisory.html\n\t\t//  http://austingroupbugs.net/view.php?id=696\n\t\t//  http://man7.org/linux/man-pages/man3/readdir_r.3.html\n\t\twhile (struct dirent* ent = readdir(dir)) {\n\t\t\tif (!(std::strcmp(ent->d_name, \".\") == 0 || std::strcmp(ent->d_name, \"..\") == 0)) {\n\t\t\t\tcontents.push_back(ent->d_name);\n\t\t\t}\n\t\t}\n\n\t\tif (errno) {\n\t\t\tthrow System_error(\"readdir\", path, errno);\n\t\t}\n\n\t} catch (...) {\n\t\tclosedir(dir);\n\t\tthrow;\n\t}\n\tclosedir(dir);\n\n\tstd::sort(contents.begin(), contents.end());\n\treturn contents;\n}\n"
  },
  {
    "path": "util-win32.cpp",
    "content": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include <io.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <windows.h>\n#include <vector>\n#include <cstring>\n\nstd::string System_error::message () const\n{\n\tstd::string\tmesg(action);\n\tif (!target.empty()) {\n\t\tmesg += \": \";\n\t\tmesg += target;\n\t}\n\tif (error) {\n\t\tLPTSTR\terror_message;\n\t\tFormatMessageA(\n\t\t\tFORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n\t\t\tnullptr,\n\t\t\terror,\n\t\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n\t\t\treinterpret_cast<LPTSTR>(&error_message),\n\t\t\t0,\n\t\t\tnullptr);\n\t\tmesg += error_message;\n\t\tLocalFree(error_message);\n\t}\n\treturn mesg;\n}\n\nvoid\ttemp_fstream::open (std::ios_base::openmode mode)\n{\n\tclose();\n\n\tchar\t\t\ttmpdir[MAX_PATH + 1];\n\n\tDWORD\t\t\tret = GetTempPath(sizeof(tmpdir), tmpdir);\n\tif (ret == 0) {\n\t\tthrow System_error(\"GetTempPath\", \"\", GetLastError());\n\t} else if (ret > sizeof(tmpdir) - 1) {\n\t\tthrow System_error(\"GetTempPath\", \"\", ERROR_BUFFER_OVERFLOW);\n\t}\n\n\tchar\t\t\ttmpfilename[MAX_PATH + 1];\n\tif (GetTempFileName(tmpdir, TEXT(\"git-crypt\"), 0, tmpfilename) == 0) {\n\t\tthrow System_error(\"GetTempFileName\", \"\", GetLastError());\n\t}\n\n\tfilename = tmpfilename;\n\n\tstd::fstream::open(filename.c_str(), mode);\n\tif (!std::fstream::is_open()) {\n\t\tDeleteFile(filename.c_str());\n\t\tthrow System_error(\"std::fstream::open\", filename, 0);\n\t}\n}\n\nvoid\ttemp_fstream::close ()\n{\n\tif (std::fstream::is_open()) {\n\t\tstd::fstream::close();\n\t\tDeleteFile(filename.c_str());\n\t}\n}\n\nvoid\tmkdir_parent (const std::string& path)\n{\n\tstd::string::size_type\t\tslash(path.find('/', 1));\n\twhile (slash != std::string::npos) {\n\t\tstd::string\t\tprefix(path.substr(0, slash));\n\t\tif (GetFileAttributes(prefix.c_str()) == INVALID_FILE_ATTRIBUTES) {\n\t\t\t// prefix does not exist, so try to create it\n\t\t\tif (!CreateDirectory(prefix.c_str(), nullptr)) {\n\t\t\t\tthrow System_error(\"CreateDirectory\", prefix, GetLastError());\n\t\t\t}\n\t\t}\n\n\t\tslash = path.find('/', slash + 1);\n\t}\n}\n\nstd::string our_exe_path ()\n{\n\tstd::vector<char>\tbuffer(128);\n\tsize_t\t\t\tlen;\n\n\twhile ((len = GetModuleFileNameA(nullptr, &buffer[0], buffer.size())) == buffer.size()) {\n\t\t// buffer may have been truncated - grow and try again\n\t\tbuffer.resize(buffer.size() * 2);\n\t}\n\tif (len == 0) {\n\t\tthrow System_error(\"GetModuleFileNameA\", \"\", GetLastError());\n\t}\n\n\treturn std::string(buffer.begin(), buffer.begin() + len);\n}\n\nint exit_status (int status)\n{\n\treturn status;\n}\n\nvoid\ttouch_file (const std::string& filename)\n{\n\tHANDLE\tfh = CreateFileA(filename.c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);\n\tif (fh == INVALID_HANDLE_VALUE) {\n\t\tDWORD\terror = GetLastError();\n\t\tif (error == ERROR_FILE_NOT_FOUND) {\n\t\t\treturn;\n\t\t} else {\n\t\t\tthrow System_error(\"CreateFileA\", filename, error);\n\t\t}\n\t}\n\tSYSTEMTIME\tsystem_time;\n\tGetSystemTime(&system_time);\n\tFILETIME\tfile_time;\n\tSystemTimeToFileTime(&system_time, &file_time);\n\n\tif (!SetFileTime(fh, nullptr, nullptr, &file_time)) {\n\t\tDWORD\terror = GetLastError();\n\t\tCloseHandle(fh);\n\t\tthrow System_error(\"SetFileTime\", filename, error);\n\t}\n\tCloseHandle(fh);\n}\n\nvoid\tremove_file (const std::string& filename)\n{\n\tif (!DeleteFileA(filename.c_str())) {\n\t\tDWORD\terror = GetLastError();\n\t\tif (error == ERROR_FILE_NOT_FOUND) {\n\t\t\treturn;\n\t\t} else {\n\t\t\tthrow System_error(\"DeleteFileA\", filename, error);\n\t\t}\n\t}\n}\n\nstatic void\tinit_std_streams_platform ()\n{\n\t_setmode(_fileno(stdin), _O_BINARY);\n\t_setmode(_fileno(stdout), _O_BINARY);\n}\n\nvoid create_protected_file (const char* path) // TODO\n{\n}\n\nint util_rename (const char* from, const char* to)\n{\n\t// On Windows OS, it is necessary to ensure target file doesn't exist\n\tunlink(to);\n\treturn rename(from, to);\n}\n\nstd::vector<std::string> get_directory_contents (const char* path)\n{\n\tstd::vector<std::string>\tfilenames;\n\tstd::string\t\t\tpatt(path);\n\tif (!patt.empty() && patt[patt.size() - 1] != '/' && patt[patt.size() - 1] != '\\\\') {\n\t\tpatt.push_back('\\\\');\n\t}\n\tpatt.push_back('*');\n\n\tWIN32_FIND_DATAA\t\tffd;\n\tHANDLE\t\t\t\th = FindFirstFileA(patt.c_str(), &ffd);\n\tif (h == INVALID_HANDLE_VALUE) {\n\t\tthrow System_error(\"FindFirstFileA\", patt, GetLastError());\n\t}\n\tdo {\n\t\tif (std::strcmp(ffd.cFileName, \".\") != 0 && std::strcmp(ffd.cFileName, \"..\") != 0) {\n\t\t\tfilenames.push_back(ffd.cFileName);\n\t\t}\n\t} while (FindNextFileA(h, &ffd) != 0);\n\n\tDWORD\t\t\t\terr = GetLastError();\n\tif (err != ERROR_NO_MORE_FILES) {\n\t\tthrow System_error(\"FileNextFileA\", patt, err);\n\t}\n\tFindClose(h);\n\treturn filenames;\n}\n"
  },
  {
    "path": "util.cpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#include \"git-crypt.hpp\"\n#include \"util.hpp\"\n#include \"coprocess.hpp\"\n#include <string>\n#include <iostream>\n\nint exec_command (const std::vector<std::string>& args)\n{\n\tCoprocess\tproc;\n\tproc.spawn(args);\n\treturn proc.wait();\n}\n\nint exec_command (const std::vector<std::string>& args, std::ostream& output)\n{\n\tCoprocess\tproc;\n\tstd::istream*\tproc_stdout = proc.stdout_pipe();\n\tproc.spawn(args);\n\toutput << proc_stdout->rdbuf();\n\treturn proc.wait();\n}\n\nint exec_command_with_input (const std::vector<std::string>& args, const char* p, size_t len)\n{\n\tCoprocess\tproc;\n\tstd::ostream*\tproc_stdin = proc.stdin_pipe();\n\tproc.spawn(args);\n\tproc_stdin->write(p, len);\n\tproc.close_stdin();\n\treturn proc.wait();\n}\n\nstd::string\tescape_shell_arg (const std::string& str)\n{\n\tstd::string\tnew_str;\n\tnew_str.push_back('\"');\n\tfor (std::string::const_iterator it(str.begin()); it != str.end(); ++it) {\n\t\tif (*it == '\"' || *it == '\\\\' || *it == '$' || *it == '`') {\n\t\t\tnew_str.push_back('\\\\');\n\t\t}\n\t\tnew_str.push_back(*it);\n\t}\n\tnew_str.push_back('\"');\n\treturn new_str;\n}\n\nuint32_t\tload_be32 (const unsigned char* p)\n{\n\treturn (static_cast<uint32_t>(p[3]) << 0) |\n\t       (static_cast<uint32_t>(p[2]) << 8) |\n\t       (static_cast<uint32_t>(p[1]) << 16) |\n\t       (static_cast<uint32_t>(p[0]) << 24);\n}\n\nvoid\t\tstore_be32 (unsigned char* p, uint32_t i)\n{\n\tp[3] = i; i >>= 8;\n\tp[2] = i; i >>= 8;\n\tp[1] = i; i >>= 8;\n\tp[0] = i;\n}\n\nbool\t\tread_be32 (std::istream& in, uint32_t& i)\n{\n\tunsigned char buffer[4];\n\tin.read(reinterpret_cast<char*>(buffer), 4);\n\tif (in.gcount() != 4) {\n\t\treturn false;\n\t}\n\ti = load_be32(buffer);\n\treturn true;\n}\n\nvoid\t\twrite_be32 (std::ostream& out, uint32_t i)\n{\n\tunsigned char buffer[4];\n\tstore_be32(buffer, i);\n\tout.write(reinterpret_cast<const char*>(buffer), 4);\n}\n\nvoid*\t\texplicit_memset (void* s, int c, std::size_t n)\n{\n\tvolatile unsigned char* p = reinterpret_cast<unsigned char*>(s);\n\n\twhile (n--) {\n\t\t*p++ = c;\n\t}\n\n\treturn s;\n}\n\nstatic bool\tleakless_equals_char (const unsigned char* a, const unsigned char* b, std::size_t len)\n{\n\tvolatile int\tdiff = 0;\n\n\twhile (len > 0) {\n\t\tdiff |= *a++ ^ *b++;\n\t\t--len;\n\t}\n\n\treturn diff == 0;\n}\n\nbool \t\tleakless_equals (const void* a, const void* b, std::size_t len)\n{\n\treturn leakless_equals_char(reinterpret_cast<const unsigned char*>(a), reinterpret_cast<const unsigned char*>(b), len);\n}\n\nstatic void\tinit_std_streams_platform (); // platform-specific initialization\n\nvoid\t\tinit_std_streams ()\n{\n\t// The following two lines are essential for achieving good performance:\n\tstd::ios_base::sync_with_stdio(false);\n\tstd::cin.tie(0);\n\n\tstd::cin.exceptions(std::ios_base::badbit);\n\tstd::cout.exceptions(std::ios_base::badbit);\n\n\tinit_std_streams_platform();\n}\n\n#ifdef _WIN32\n#include \"util-win32.cpp\"\n#else\n#include \"util-unix.cpp\"\n#endif\n"
  },
  {
    "path": "util.hpp",
    "content": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * git-crypt is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with git-crypt.  If not, see <http://www.gnu.org/licenses/>.\n *\n * Additional permission under GNU GPL version 3 section 7:\n *\n * If you modify the Program, or any covered work, by linking or\n * combining it with the OpenSSL project's OpenSSL library (or a\n * modified version of that library), containing parts covered by the\n * terms of the OpenSSL or SSLeay licenses, the licensors of the Program\n * grant you additional permission to convey the resulting work.\n * Corresponding Source for a non-source form of such a combination\n * shall include the source code for the parts of OpenSSL used as well\n * as that of the covered work.\n */\n\n#ifndef GIT_CRYPT_UTIL_HPP\n#define GIT_CRYPT_UTIL_HPP\n\n#include <string>\n#include <ios>\n#include <iosfwd>\n#include <stdint.h>\n#include <sys/types.h>\n#include <fstream>\n#include <vector>\n\nstruct System_error {\n\tstd::string\taction;\n\tstd::string\ttarget;\n\tint\t\terror;\n\n\tSystem_error (const std::string& a, const std::string& t, int e) : action(a), target(t), error(e) { }\n\n\tstd::string message () const;\n};\n\nclass temp_fstream : public std::fstream {\n\tstd::string\tfilename;\npublic:\n\t~temp_fstream () { close(); }\n\n\tvoid\t\topen (std::ios_base::openmode);\n\tvoid\t\tclose ();\n};\n\nvoid\t\tmkdir_parent (const std::string& path); // Create parent directories of path, __but not path itself__\nstd::string\tour_exe_path ();\nint\t\texec_command (const std::vector<std::string>&);\nint\t\texec_command (const std::vector<std::string>&, std::ostream& output);\nint\t\texec_command_with_input (const std::vector<std::string>&, const char* p, size_t len);\nint\t\texit_status (int wait_status); // returns -1 if process did not exit (but was signaled, etc.)\ninline bool\tsuccessful_exit (int wait_status) { return exit_status(wait_status) == 0; }\nvoid\t\ttouch_file (const std::string&); // ignores non-existent files\nvoid\t\tremove_file (const std::string&); // ignores non-existent files\nstd::string\tescape_shell_arg (const std::string&);\nuint32_t\tload_be32 (const unsigned char*);\nvoid\t\tstore_be32 (unsigned char*, uint32_t);\nbool\t\tread_be32 (std::istream& in, uint32_t&);\nvoid\t\twrite_be32 (std::ostream& out, uint32_t);\nvoid*\t\texplicit_memset (void* s, int c, size_t n);\t// memset that won't be optimized away\nbool\t\tleakless_equals (const void* a, const void* b, size_t len); // compare bytes w/o leaking timing\nvoid\t\tinit_std_streams ();\nvoid\t\tcreate_protected_file (const char* path); // create empty file accessible only by current user\nint\t\tutil_rename (const char*, const char*);\nstd::vector<std::string> get_directory_contents (const char* path);\n\n#endif\n\n"
  }
]